### Run standalone binary Source: https://github.com/bluenviron/mediamtx/blob/main/docs/1-kickoff/2-install.md Starts the MediaMTX server from a downloaded standalone binary. ```shell ./mediamtx ``` -------------------------------- ### Windows: Install service Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/17-start-on-boot.md Command to install MediaMTX as a Windows service using WinSW. ```powershell WinSW-x64 install ``` -------------------------------- ### OpenWrt: Enable and start service Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/17-start-on-boot.md Makes the MediaMTX service executable, enables it, and starts it on OpenWrt. ```sh chmod +x /etc/init.d/mediamtx /etc/init.d/mediamtx enable /etc/init.d/mediamtx start ``` -------------------------------- ### Coturn setup with Docker Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/26-webrtc-specific-features.md This shell command shows how to start a Coturn TURN server using Docker, configured for TCP transport and secret-based authentication. ```sh docker run --rm -it \ --network=host \ coturn/coturn \ --log-file=stdout -v \ --no-udp --no-dtls --no-tls \ --min-port=49152 --max-port=65535 \ --use-auth-secret --static-auth-secret=mysecret -r myrealm ``` -------------------------------- ### CPU Profiling Example Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/24-performance.md This command uses the go tool pprof to get a text-based CPU profile from the running MediaMTX server. ```sh go tool pprof -text http://localhost:9999/debug/pprof/profile?seconds=30 ``` -------------------------------- ### Linux: Enable and start service Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/17-start-on-boot.md Reloads systemd, enables, and starts the MediaMTX service on Linux. ```sh sudo systemctl daemon-reload sudo systemctl enable mediamtx sudo systemctl start mediamtx ``` -------------------------------- ### Goroutine Profiling Example Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/24-performance.md This command uses the go tool pprof to get a text-based goroutine profile from the running MediaMTX server. ```sh go tool pprof -text http://localhost:9999/debug/pprof/goroutine ``` -------------------------------- ### URL Encoded Get Request Example Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/10-playback.md Example of a GET request with URL-encoded parameters for path, start date, and duration. ```http http://localhost:9996/get?path=mypath&start=2024-01-14T16%3A33%3A17%2B00%3A00&duration=200.5 ``` -------------------------------- ### Keycloak Docker Run Command Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/06-authentication.md Command to start a Keycloak instance using Docker for JWT authentication setup. ```sh docker run --name=keycloak -p 8080:8080 \ -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=admin \ quay.io/keycloak/keycloak:23.0.7 start-dev ``` -------------------------------- ### Linux: Enable wait-online service Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/17-start-on-boot.md Enables the systemd-networkd-wait-online service to ensure network is ready before MediaMTX starts. ```sh sudo systemctl enable systemd-networkd-wait-online.service ``` -------------------------------- ### Install OpenCV with GStreamer support Source: https://github.com/bluenviron/mediamtx/blob/main/docs/3-publish/18-python-opencv.md This command installs necessary GStreamer development libraries and then clones, builds, and installs OpenCV with GStreamer support enabled. ```bash sudo apt install -y libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev gstreamer1.0-plugins-ugly gstreamer1.0-rtsp python3-dev python3-numpy git clone --depth=1 -b 4.5.4 https://github.com/opencv/opencv cd opencv mkdir build && cd build cmake -D CMAKE_INSTALL_PREFIX=/usr -D WITH_GSTREAMER=ON .. make -j$(nproc) sudo make install ``` -------------------------------- ### Logrotate configuration example Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/18-logging.md Example configuration file for `logrotate` to manage the MediaMTX log file. ```text /my/mediamtx/path/mediamtx.log { daily copytruncate rotate 7 compress delaycompress missingok notifempty } ``` -------------------------------- ### OpenWrt: Move executable and configuration Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/17-start-on-boot.md Moves the MediaMTX executable and configuration file to global directories on OpenWrt. ```sh mv mediamtx /usr/bin/ mkdir -p /usr/etc && mv mediamtx.yml /usr/etc/ ``` -------------------------------- ### Install FreeBSD package Source: https://github.com/bluenviron/mediamtx/blob/main/docs/1-kickoff/2-install.md Installs MediaMTX on FreeBSD using the ports tree or pkg. ```shell cd /usr/ports/multimedia/mediamtx && make install clean pkg install mediamtx ``` -------------------------------- ### Windows: WinSW configuration Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/17-start-on-boot.md XML configuration file for WinSW to manage MediaMTX as a Windows service. ```xml mediamtx mediamtx %BASE%/mediamtx.exe ``` -------------------------------- ### Example CloudFront URL Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/20-scalability.md Example URL format for accessing HLS streams through a CloudFront distribution. ```text https://xxxxxx.cloudfront.net/stream/ ``` -------------------------------- ### Linux: SELinux security context Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/17-start-on-boot.md Adds the correct security context for the MediaMTX executable if SELinux is enabled. ```sh semanage fcontext -a -t bin_t /usr/local/bin/mediamtx restorecon -Fv /usr/local/bin/mediamtx ``` -------------------------------- ### OpenWrt: Create procd service Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/17-start-on-boot.md Creates a procd service file to manage the MediaMTX service on OpenWrt. ```sh tee /etc/init.d/mediamtx >/dev/null << EOF #!/bin/sh /etc/rc.common USE_PROCD=1 START=95 STOP=01 start_service() { procd_open_instance procd_set_param command /usr/bin/mediamtx procd_set_param stdout 1 procd_set_param stderr 1 procd_close_instance } EOF ``` -------------------------------- ### Timespans List JSON Response Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/10-playback.md Example JSON response format for the /list endpoint, detailing start time, duration, and download URL for each timespan. ```json [ { "start": "2006-01-02T15:04:05Z07:00", "duration": 60.0, "url": "http://localhost:9996/get?path=[mypath]&start=2006-01-02T15%3A04%3A05Z07%3A00&duration=60.0" }, { "start": "2006-01-02T15:07:05Z07:00", "duration": 32.33, "url": "http://localhost:9996/get?path=[mypath]&start=2006-01-02T15%3A07%3A05Z07%3A00&duration=32.33" } ] ``` -------------------------------- ### Linux: Create systemd service Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/17-start-on-boot.md Creates a systemd service file to manage the MediaMTX service on Linux. ```sh sudo tee /etc/systemd/system/mediamtx.service >/dev/null << EOF [Unit] After=network-online.target Wants=network-online.target [Service] ExecStart=/usr/local/bin/mediamtx /usr/local/etc/mediamtx.yml [Install] WantedBy=multi-user.target EOF ``` -------------------------------- ### Install Local CA Certificate on Windows Source: https://github.com/bluenviron/mediamtx/blob/main/docs/3-publish/17-obs-studio.md Command to install the local certificate authority's public key on a Windows system. ```powershell certutil -addstore "Root" myca.crt ``` -------------------------------- ### Linux: Move executable and configuration Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/17-start-on-boot.md Moves the MediaMTX executable and configuration file to standard global directories on Linux systems. ```sh sudo mv mediamtx /usr/local/bin/ sudo mv mediamtx.yml /usr/local/etc/ ``` -------------------------------- ### Install Local CA Certificate on Linux Source: https://github.com/bluenviron/mediamtx/blob/main/docs/3-publish/17-obs-studio.md Commands to install the local certificate authority's public key on a Linux system. ```shell sudo mkdir -p /usr/local/share/ca-certificates sudo cp myca.crt /usr/local/share/ca-certificates/ sudo update-ca-certificates ``` -------------------------------- ### Install Arch Linux package Source: https://github.com/bluenviron/mediamtx/blob/main/docs/1-kickoff/2-install.md Clones the AUR repository, builds, and installs the MediaMTX package on Arch Linux. ```shell git clone https://aur.archlinux.org/mediamtx.git cd mediamtx makepkg -si ``` -------------------------------- ### Verify OpenCV installation Source: https://github.com/bluenviron/mediamtx/blob/main/docs/3-publish/18-python-opencv.md This command checks if OpenCV was installed correctly and has GStreamer support enabled by printing its build information. ```bash python3 -c 'import cv2; print(cv2.getBuildInformation())' ``` -------------------------------- ### Read Stream with VLC Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/01-basic-usage.md Use VLC to read a stream from Mediamtx. Ensure VLC is installed. ```sh vlc --network-caching=50 rtsp://localhost:8554/mystream ``` -------------------------------- ### Example structured log entries Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/18-logging.md Example of log entries in structured JSONL format. ```json {"timestamp":"20XX-YY-ZZT10:45:05.999999999+01:00","level":"INF","message":"[RTSP] listener opened on :8554 (TCP/RTSP), :8000 (UDP/RTP), :8001 (UDP/RTCP)"} {"timestamp":"20XX-YY-ZZT10:45:05.999999999+01:00","level":"INF","message":"[RTMP] listener opened on :1935"} {"timestamp":"20XX-YY-ZZT10:45:05.999999999+01:00","level":"INF","message":"[HLS] listener opened on :8888"} {"timestamp":"20XX-YY-ZZT10:45:05.999999999+01:00","level":"INF","message":"[WebRTC] listener opened on :8889 (TCP/HTTP), :8189 (UDP/ICE)"} {"timestamp":"20XX-YY-ZZT10:45:05.999999999+01:00","level":"INF","message":"[SRT] listener opened on :8890 (UDP)"} ``` -------------------------------- ### Build custom Docker image Source: https://github.com/bluenviron/mediamtx/blob/main/docs/1-kickoff/2-install.md Builds a custom MediaMTX Docker image with additional software. ```Dockerfile FROM bluenviron/mediamtx:1 AS mediamtx FROM ubuntu:24.04 COPY --from=mediamtx /mediamtx / COPY --from=mediamtx /mediamtx.yml / # add anything you need. RUN apt update && apt install -y \ gstreamer1.0-tools ENTRYPOINT [ "/mediamtx" ] ``` ```shell docker build . -t my-mediamtx ``` -------------------------------- ### HLS Configuration Options Source: https://github.com/bluenviron/mediamtx/blob/main/docs/4-read/05-hls.md Example YAML configuration for HLS settings in MediaMTX. ```yaml # Allow clients to read streams with the HLS protocol. hls: true # Address of the HLS listener. hlsAddress: :8888 # Enable HTTPS on the HLS server. # This is required for Low-Latency HLS to function correctly on Apple devices. hlsEncryption: false # Path to the server key. This is needed only when encryption is yes. # This can be generated with: # openssl genrsa -out server.key 2048 # openssl req -new -x509 -sha256 -key server.key -out server.crt -days 3650 hlsServerKey: server.key # Path to the server certificate. hlsServerCert: server.crt # Allowed CORS origins. # Supports wildcards: ['http://*.example.com'] hlsAllowOrigins: ["*"] # IPs or CIDRs of proxies placed before the HLS server. # If the server receives a request from one of these entries, IP in logs # will be taken from the X-Forwarded-For header. hlsTrustedProxies: [] # By default, HLS is generated only when requested by a user. # This option allows to generate it always, avoiding the delay between request and generation. hlsAlwaysRemux: false # Variant of the HLS protocol to use. Available options are: # * mpegts - uses MPEG-TS segments, for maximum compatibility. # * fmp4 - uses fragmented MP4 segments, more efficient. # * lowLatency - uses Low-Latency HLS. hlsVariant: lowLatency # Number of HLS segments to keep on the server. # Segments allow to seek through the stream. # Their number doesn't influence latency. hlsSegmentCount: 7 # Minimum duration of each segment. # A player usually puts 3 segments in a buffer before reproducing the stream. # The final segment duration is also influenced by the interval between IDR frames, # since the server changes the duration in order to include at least one IDR frame # in each segment. hlsSegmentDuration: 1s # Minimum duration of each part. # A player usually puts 3 parts in a buffer before reproducing the stream. # Parts are used in Low-Latency HLS in place of segments. # Part duration is influenced by the distance between video/audio samples # and is adjusted in order to produce segments with a similar duration. hlsPartDuration: 200ms # Maximum size of each segment. # This prevents RAM exhaustion. hlsSegmentMaxSize: 50M # Directory in which to save segments and non-low-latency playlists. # This has two purposes: offloading RAM and creating a self-consistent directory # that can be served by a CDN. hlsDirectory: "" # The muxer will be closed when there are no # reader requests and this amount of time has passed. hlsMuxerCloseAfter: 60s # Secret to identify requests coming from a CDN. # The CDN must insert this secret in every request in the # 'Authorization: Bearer' header. hlsCDNSecret: "" ``` -------------------------------- ### Launch MediaMTX using Docker Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/20-scalability.md Commands to install Docker and run MediaMTX as a Docker container on an EC2 instance. ```sh sudo dnf update -y sudo dnf install -y docker sudo systemctl start docker sudo systemctl enable docker sudo usermod -aG docker ec2-user sudo docker run \ -d \ --restart=always \ --name mediamtx \ --network host \ -v $PWD/mediamtx.yml:/mediamtx.yml \ bluenviron/mediamtx:1 ``` -------------------------------- ### Install GStreamer and alsa-utils Source: https://github.com/bluenviron/mediamtx/blob/main/docs/3-publish/12-raspberry-pi-cameras.md Command to install necessary packages for audio support with Raspberry Pi cameras. ```sh sudo apt install -y gstreamer1.0-tools gstreamer1.0-rtsp gstreamer1.0-alsa alsa-utils ``` -------------------------------- ### Install VLC Snap on Ubuntu Source: https://github.com/bluenviron/mediamtx/blob/main/docs/4-read/09-vlc.md Commands to remove the default VLC and install the snap version to fix RTSP playback issues on Ubuntu 21.10. ```sh sudo apt purge -y vlc snap install vlc ``` -------------------------------- ### Cross Compilation - Basic Source: https://github.com/bluenviron/mediamtx/blob/main/docs/6-misc/1-compile.md Example of cross-compiling the mediamtx binary for a different operating system and architecture. ```sh git clone https://github.com/bluenviron/mediamtx cd mediamtx go generate ./... CGO_ENABLED=0 GOOS=my_os GOARCH=my_arch go build . ``` -------------------------------- ### GStreamer and RTSP Source: https://github.com/bluenviron/mediamtx/blob/main/docs/4-read/08-gstreamer.md Example command to read a stream from the server using RTSP. ```sh gst-launch-1.0 rtspsrc location=rtsp://127.0.0.1:8554/mystream latency=0 ! decodebin ! autovideosink ``` -------------------------------- ### GStreamer and SRT Source: https://github.com/bluenviron/mediamtx/blob/main/docs/4-read/08-gstreamer.md Example command to read a stream from the server using SRT. ```sh gst-launch-1.0 srtsrc uri="srt://localhost:8890?streamid=read:mystream" ! tsdemux ! decodebin ! autovideosink ``` -------------------------------- ### Publish Stream with FFmpeg Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/01-basic-usage.md Use FFmpeg to publish a stream from an MP4 file. Ensure FFmpeg is installed and the file exists. ```sh ffmpeg -re -stream_loop -1 -i file.mp4 -c copy \ -f rtsp rtsp://localhost:8554/mystream ``` -------------------------------- ### FFmpeg and SRT Source: https://github.com/bluenviron/mediamtx/blob/main/docs/4-read/07-ffmpeg.md Example command to read a stream from the server using SRT protocol with FFmpeg. ```sh ffmpeg -i 'srt://localhost:8890?streamid=read:test' -c copy output.mp4 ``` -------------------------------- ### SRT Source Configuration Source: https://github.com/bluenviron/mediamtx/blob/main/docs/3-publish/02-srt-cameras-and-servers.md Example configuration for adding an SRT stream source to MediaMTX. ```yaml paths: proxied: # url of the source stream, in the format srt://host:port?streamid=streamid&other_parameters source: srt://original-url ``` -------------------------------- ### Cross Compilation - Linux MIPS with GOMIPS Source: https://github.com/bluenviron/mediamtx/blob/main/docs/6-misc/1-compile.md Example of cross-compiling for Linux MIPS with GOMIPS parameters. ```sh CGO_ENABLED=0 GOOS=linux GOARCH=mips GOMIPS=softfloat go build . ``` -------------------------------- ### Go Profiling Data Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/24-performance.md Example output from a Go profiling tool, showing function call statistics. ```go 0 0% 100% 1 3.70% github.com/bluenviron/mediamtx/internal/servers/webrtc.(*Server).run 0 0% 100% 1 3.70% github.com/datarhei/gosrt.(*listener).Accept2 0 0% 100% 1 3.70% github.com/datarhei/gosrt.(*listener).reader 0 0% 100% 1 3.70% github.com/datarhei/gosrt.Listen.func1 0 0% 100% 1 3.70% github.com/fsnotify/fsnotify.(*inotify).readEvents 0 0% 100% 1 3.70% github.com/gin-contrib/pprof.RouteRegister.WrapH.func9 0 0% 100% 1 3.70% github.com/gin-gonic/gin.(*Context).Next (inline) 0 0% 100% 1 3.70% github.com/gin-gonic/gin.(*Engine).ServeHTTP 0 0% 100% 1 3.70% github.com/gin-gonic/gin.(*Engine).handleHTTPRequest 0 0% 100% 1 3.70% github.com/pion/ice/v4.(*UDPMuxDefault).connWorker 0 0% 100% 5 18.52% internal/poll.(*FD).Accept 0 0% 100% 2 7.41% internal/poll.(*FD).Read 0 0% 100% 4 14.81% internal/poll.(*FD).ReadFromInet6 0 0% 100% 11 40.74% internal/poll.(*pollDesc).wait 0 0% 100% 11 40.74% internal/poll.(*pollDesc).waitRead (inline) 0 0% 100% 11 40.74% internal/poll.runtime_pollWait 0 0% 100% 1 3.70% main.main 0 0% 100% 5 18.52% net.(*TCPListener).Accept 0 0% 100% 5 18.52% net.(*TCPListener).accept 0 0% 100% 4 14.81% net.(*UDPConn).ReadFrom 0 0% 100% 4 14.81% net.(*UDPConn).readFrom 0 0% 100% 4 14.81% net.(*UDPConn).readFromUDP 0 0% 100% 1 3.70% net.(*conn).Read 0 0% 100% 1 3.70% net.(*netFD).Read 0 0% 100% 5 18.52% net.(*netFD).accept 0 0% 100% 4 14.81% net.(*netFD).readFromInet6 0 0% 100% 3 11.11% net/http.(*Server).Serve 0 0% 100% 1 3.70% net/http.(*conn).ServeHTTP 0 0% 100% 1 3.70% net/http.(*connReader).backgroundRead 0 0% 100% 1 3.70% net/http.serverHandler.ServeHTTP 0 0% 100% 1 3.70% net/http/pprof.handler.ServeHTTP 0 0% 100% 1 3.70% os.(*File).Read 0 0% 100% 1 3.70% os.(*File).read (inline) 0 0% 100% 1 3.70% os/signal.loop 0 0% 100% 1 3.70% os/signal.signal_recv 0 0% 100% 1 3.70% runtime.chanrecv 0 0% 100% 1 3.70% runtime.chanrecv1 0 0% 100% 1 3.70% runtime.goparkunlock (inline) 0 0% 100% 1 3.70% runtime.main 0 0% 100% 11 40.74% runtime.netpollblock 0 0% 100% 1 3.70% runtime.pprof_goroutineProfileWithLabels 0 0% 100% 12 44.44% runtime.selectgo 0 0% 100% 1 3.70% runtime.semacquire1 0 0% 100% 1 3.70% runtime/pprof.(*Profile).WriteTo 0 0% 100% 1 3.70% runtime/pprof.writeGoroutine 0 0% 100% 1 3.70% runtime/pprof.writeRuntimeProfile 0 0% 100% 1 3.70% sync.(*WaitGroup).Wait 0 0% 100% 1 3.70% sync.runtime_SemacquireWaitGroup ``` -------------------------------- ### Run with encrypted configuration Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/05-configuration.md Example of running MediaMTX with an encrypted configuration file using the MTX_CONFKEY environment variable. ```sh MTX_CONFKEY=mykey ./mediamtx ``` -------------------------------- ### Download Recordings Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/10-playback.md This endpoint allows downloading recordings. It requires path, start date, and duration, with an optional format parameter. ```APIDOC ## GET /get ### Description Downloads a recording for a specified path, start time, and duration. The output format can be specified. ### Method GET ### Endpoint `http://localhost:9996/get` ### Parameters #### Query Parameters - **path** (string) - Required - The name of the path for the recording. - **start** (string) - Required - The start date in RFC3339 format. - **duration** (float) - Required - The maximum duration of the recording in seconds. - **format** (string) - Optional - The output format of the stream. Available values: "fmp4" (default), "mp4". ### Request Example ``` http://localhost:9996/get?path=mypath&start=2024-01-14T16%3A33%3A17%2B00%3A00&duration=200.5 ``` ### Response #### Success Response (200) - The response is a stream of the recording in the specified format (default: fMP4). #### Response Example (fMP4 stream) ```html ``` #### Response Example (MP4 format) ``` http://localhost:9996/get?path=[mypath]&start=[start_date]&duration=[duration]&format=mp4 ``` ``` -------------------------------- ### GStreamer and RTSP Source: https://github.com/bluenviron/mediamtx/blob/main/docs/3-publish/16-gstreamer.md Example command to publish a stream to an RTSP server using GStreamer. This includes both video and audio. ```sh 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 ``` -------------------------------- ### Cross Compilation - Linux ARM64 with GOARM Source: https://github.com/bluenviron/mediamtx/blob/main/docs/6-misc/1-compile.md Example of cross-compiling for Linux ARM64 with a specific GOARM version. ```sh CGO_ENABLED=0 GOOS=linux GOARCH=arm64 GOARM=7 go build . ``` -------------------------------- ### Enable Playback Server Configuration Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/10-playback.md Configure the playback server by setting 'playback' to 'yes' and specifying the 'playbackAddress'. ```yaml playback: yes playbackAddress: :9996 ``` -------------------------------- ### MediaMTX Origin EC2 User Data Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/20-scalability.md User data script for launching the MediaMTX origin EC2 instance. It installs Docker, starts the service, adds the ec2-user to the docker group, and runs the MediaMTX container. ```sh #!/bin/bash dnf update -y dnf install -y docker systemctl start docker systemctl enable docker usermod -aG docker ec2-user docker run -d \ --name mediamtx \ --restart always \ --network host \ bluenviron/mediamtx:1 ``` -------------------------------- ### OBS Studio RTSP Input Source: https://github.com/bluenviron/mediamtx/blob/main/docs/4-read/10-obs-studio.md Example RTSP URL to input into OBS Studio to read a stream from the server. ```text rtsp://localhost:8554/stream ``` -------------------------------- ### MediaMTX Read Replica EC2 User Data Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/20-scalability.md User data script for launching MediaMTX read replica EC2 instances. It installs Docker, starts the service, adds the ec2-user to the docker group, creates a custom configuration file, and runs the MediaMTX container. ```sh #!/bin/bash dnf update -y dnf install -y docker systemctl start docker systemctl enable docker usermod -aG docker ec2-user mkdir -p /etc/mediamtx/ tee /etc/mediamtx/mediamtx.yml << EOF webrtcLocalUDPAddress: webrtcICEServers2: - url: stun:stun.l.google.com:19302 paths: "~^(.+)$": source: rtsp://dns-of-origin:8554/$G1 sourceOnDemand: yes EOF docker run -d \ --name mediamtx \ --restart always \ --network host \ -v /etc/mediamtx/mediamtx.yml:/mediamtx.yml \ bluenviron/mediamtx:1 ``` -------------------------------- ### Standard Compilation Source: https://github.com/bluenviron/mediamtx/blob/main/docs/6-misc/1-compile.md Steps to clone the repository and build the mediamtx binary using Go. ```sh git clone https://github.com/bluenviron/mediamtx cd mediamtx go generate ./... CGO_ENABLED=0 go build . ``` -------------------------------- ### Run Docker image with environment variables and ports Source: https://github.com/bluenviron/mediamtx/blob/main/docs/1-kickoff/2-install.md Downloads and launches the bluenviron/mediamtx:1 Docker image with specific environment variables and port mappings. ```shell docker run --rm -it \ -e MTX_RTSPTRANSPORTS=tcp \ -e MTX_WEBRTCADDITIONALHOSTS=192.168.x.x \ -p 8554:8554 \ -p 1935:1935 \ -p 8888:8888 \ -p 8889:8889 \ -p 8890:8890/udp \ -p 8189:8189/udp \ bluenviron/mediamtx:1 ``` -------------------------------- ### Configure rclone Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/09-record.md Initialize the rclone configuration utility. ```sh rclone config ``` -------------------------------- ### Launch MediaMTX Origin Instance Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/20-scalability.md Command to launch the MediaMTX origin instance using Docker. ```sh docker run -d \ --name mediamtx \ --restart always \ --network host \ bluenviron/mediamtx:1 ``` -------------------------------- ### JWT Permissions Claim Example Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/06-authentication.md Example of the expected structure for the 'mediamtx_permissions' claim within a JWT. ```json { "mediamtx_permissions": [ { "action": "publish", "path": "" } ] } ``` -------------------------------- ### Initialize WebRTC Player with Query Parameters Source: https://github.com/bluenviron/mediamtx/blob/main/internal/servers/webrtc/read_index.html JavaScript logic to parse URL parameters for video configuration and initialize the MediaMTXWebRTCReader. It handles stream binding, error messaging, and data channel communication. ```javascript const video = document.getElementById('video'); const message = document.getElementById('message'); let defaultControls = false; let reader = null; const setMessage = (str) => { if (str !== '') { video.controls = false; } else { video.controls = defaultControls; } message.innerText = str; }; const parseBoolString = (str, defaultVal) => { str = (str || ''); if (['1', 'yes', 'true'].includes(str.toLowerCase())) { return true; } if (['0', 'no', 'false'].includes(str.toLowerCase())) { return false; } return defaultVal; }; const loadAttributesFromQuery = () => { const params = new URLSearchParams(window.location.search); video.controls = parseBoolString(params.get('controls'), true); video.muted = parseBoolString(params.get('muted'), true); video.autoplay = parseBoolString(params.get('autoplay'), true); video.playsInline = parseBoolString(params.get('playsinline'), true); video.disablepictureinpicture = parseBoolString(params.get('disablepictureinpicture'), false); defaultControls = video.controls; }; window.addEventListener('load', () => { loadAttributesFromQuery(); reader = new MediaMTXWebRTCReader({ url: new URL('whep', window.location.href) + window.location.search, onError: (err) => { setMessage(err); }, onTrack: (evt) => { setMessage(''); video.srcObject = evt.streams[0]; }, onDataChannel: (evt) => { evt.channel.binaryType = 'arraybuffer'; evt.channel.onmessage = (evt) => { console.log('data channel message', evt.data); }; }, }); }); window.addEventListener('beforeunload', () => { if (reader !== null) { reader.close(); } }); ``` -------------------------------- ### RTMPS Connection Example Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/28-rtmp-specific-features.md Example of how to connect to an RTMP stream using the secure RTMPS scheme and the default port. ```shell rtmps://localhost:1937/... ``` -------------------------------- ### Configure Linux Webcam Stream Source: https://github.com/bluenviron/mediamtx/blob/main/docs/3-publish/13-generic-webcams.md Use this configuration for Linux systems. It sets up a webcam stream using FFmpeg. ```yaml paths: cam: runOnInit: ffmpeg -f v4l2 -i /dev/video0 -c:v libx264 -pix_fmt yuv420p -preset ultrafast -b:v 600k -f rtsp rtsp://localhost:$RTSP_PORT/$MTX_PATH runOnInitRestart: yes ``` -------------------------------- ### WebRTC Publisher Initialization and Stream Handling Source: https://github.com/bluenviron/mediamtx/blob/main/internal/servers/webrtc/publish_index.html This JavaScript code handles the initialization of the MediaMTXWebRTCPublisher. It processes user-selected media devices, configures stream constraints, and establishes the connection to the server. ```javascript const onStream = (stream) => { video.srcObject = stream; publisher = new MediaMTXWebRTCPublisher({ url: new URL('whip', window.location.href) + window.location.search, stream, videoCodec: videoForm.codec.value, videoBitrate: videoForm.bitrate.value, audioCodec: audioForm.codec.value, audioBitrate: audioForm.bitrate.value, audioVoice: audioForm.voice.checked, onError: (err) => { setMessage(err); }, onConnected: (evt) => { setMessage(''); }, }); }; ``` -------------------------------- ### Launch MediaMTX Read Replica Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/20-scalability.md Command to launch a MediaMTX read replica instance using Docker, mounting a custom configuration file. ```sh docker run -d \ --name mediamtx \ --restart always \ --network host \ -v $PWD/mediamtx.yml:/mediamtx.yml \ bluenviron/mediamtx:1 ``` -------------------------------- ### Initialize WebRTC Media Devices and Codecs Source: https://github.com/bluenviron/mediamtx/blob/main/internal/servers/webrtc/publish_index.html This function requests user media permissions to detect available devices and uses an RTCPeerConnection to probe for supported video and audio codecs. It populates UI dropdowns with the detected capabilities and releases the stream to prevent hardware locking. ```javascript const populateCodecs = () => { const tempPC = new RTCPeerConnection({}); tempPC.addTransceiver('video', { direction: 'sendonly' }); tempPC.addTransceiver('audio', { direction: 'sendonly' }); return tempPC.createOffer().then((desc) => { const sdp = desc.sdp.toLowerCase(); for (const codec of ['av1/90000', 'vp9/90000', 'vp8/90000', 'h264/90000', 'h265/90000']) { if (sdp.includes(codec)) { const opt = document.createElement('option'); opt.value = codec; opt.text = codec.split('/')[0].toUpperCase(); videoForm.codec.appendChild(opt); } } for (const codec of ['opus/48000', 'g722/8000', 'pcmu/8000', 'pcma/8000']) { if (sdp.includes(codec)) { const opt = document.createElement('option'); opt.value = codec; opt.text = codec.split('/')[0].toUpperCase(); audioForm.codec.appendChild(opt); } } tempPC.close(); }); }; ``` -------------------------------- ### Standard SRT Stream ID Syntax Example Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/25-srt-specific-features.md An example of the standard SRT stream ID syntax, including parameters for mode, path, username, and password. ```text srt://localhost:8890?streamid=#!::m=publish,r=mypath,u=myuser,s=mypass&pkt_size=1316 ``` -------------------------------- ### Run Docker image with host network Source: https://github.com/bluenviron/mediamtx/blob/main/docs/1-kickoff/2-install.md Launches the bluenviron/mediamtx:1 Docker image using the host network, which is not compatible with Windows, macOS, and Kubernetes. ```shell docker run --rm -it --network=host bluenviron/mediamtx:1 ``` -------------------------------- ### SRT Stream URL Example Source: https://github.com/bluenviron/mediamtx/blob/main/docs/4-read/01-srt.md Example URL to read a stream from the server using the SRT protocol. Replace 'mystream' with your actual stream path. ```text srt://localhost:8890?streamid=read:mystream ``` -------------------------------- ### Configure Windows Webcam Stream Source: https://github.com/bluenviron/mediamtx/blob/main/docs/3-publish/13-generic-webcams.md Use this configuration for Windows systems. It sets up a webcam stream using FFmpeg, specifying the webcam by name. ```yaml paths: cam: runOnInit: ffmpeg -f dshow -i video="USB2.0 HD UVC WebCam" -c:v libx264 -pix_fmt yuv420p -preset ultrafast -b:v 600k -f rtsp rtsp://localhost:$RTSP_PORT/$MTX_PATH runOnInitRestart: yes ``` -------------------------------- ### RTMP Publish URL Source: https://github.com/bluenviron/mediamtx/blob/main/docs/3-publish/07-rtmp-clients.md Example URL for publishing a stream using RTMP. ```text rtmp://localhost/mystream ``` -------------------------------- ### Compile for All Supported Platforms Source: https://github.com/bluenviron/mediamtx/blob/main/docs/6-misc/1-compile.md Command to build tarballs for all supported platforms using Docker. ```sh make binaries ``` -------------------------------- ### RTSP Authentication URL Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/06-authentication.md Example of how to include username and password in an RTSP URL for authentication. ```text rtsp rtsp://myuser:mypass@localhost:8554/mystream ``` -------------------------------- ### RTMPS Publish URL Source: https://github.com/bluenviron/mediamtx/blob/main/docs/3-publish/17-obs-studio.md Example of an RTMPS publish URL for OBS Studio. ```shell rtmps://localhost:1936/mystream ``` -------------------------------- ### Launch Traefik Load Balancer Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/20-scalability.md Command to launch Traefik as a load balancer using Docker, mounting configuration files. ```sh docker run -d \ --name traefik \ --restart always \ --network host \ -v $PWD/traefik.yml:/etc/traefik/traefik.yml \ -v $PWD/dynamic_conf.yml:/etc/traefik/dynamic_conf.yml \ traefik:v3.6.14 ``` -------------------------------- ### FFmpeg and RTMP Source: https://github.com/bluenviron/mediamtx/blob/main/docs/4-read/07-ffmpeg.md Example command to read a stream from the server using RTMP protocol with FFmpeg. ```sh ffmpeg -i rtmp://localhost/mystream -c copy output.mp4 ``` -------------------------------- ### FFmpeg and RTSP Source: https://github.com/bluenviron/mediamtx/blob/main/docs/4-read/07-ffmpeg.md Example command to read a stream from the server using RTSP protocol with FFmpeg. ```sh ffmpeg -i rtsp://localhost:8554/mystream -c copy output.mp4 ``` -------------------------------- ### VLC UDP-Multicast Transport Protocol Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/27-rtsp-specific-features.md Example of how to use the UDP-multicast transport protocol with VLC. ```sh vlc --network-caching=50 rtsp://localhost:8554/mystream?vlcmulticast ``` -------------------------------- ### Configure On-Demand Publishing in mediamtx.yml Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/14-on-demand-publishing.md Replace the `paths` section in your `mediamtx.yml` file with this configuration to enable on-demand streaming. The `runOnDemand` command will execute only when a client requests the `ondemand` path. ```yaml paths: ondemand: runOnDemand: ffmpeg -re -stream_loop -1 -i file.mp4 -c copy -f rtsp rtsp://localhost:$RTSP_PORT/$MTX_PATH runOnDemandRestart: yes ``` -------------------------------- ### Create Server Certificate Source: https://github.com/bluenviron/mediamtx/blob/main/docs/3-publish/17-obs-studio.md Command to create a server certificate using the local certificate authority key pair. ```shell openssl req \ -newkey rsa:4096 \ -nodes \ -keyout server.key \ -CA myca.crt \ -CAkey myca.key \ -subj "/CN=localhost" \ -x509 \ -days 3650 \ -out server.crt ``` -------------------------------- ### VLC TCP Transport Protocol Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/27-rtsp-specific-features.md Example of how to use the TCP transport protocol with VLC. ```sh vlc --network-caching=50 --rtsp-tcp rtsp://localhost:8554/mystream ``` -------------------------------- ### Read Stream with GStreamer Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/01-basic-usage.md Use GStreamer's gst-play-1.0 to read a stream from Mediamtx. Ensure GStreamer is installed. ```sh gst-play-1.0 rtsp://localhost:8554/mystream ``` -------------------------------- ### Enable basic stream recording Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/09-record.md Set the record parameter to yes within the pathDefaults configuration to enable stream recording. ```yaml pathDefaults: # Record streams to disk. record: yes ``` -------------------------------- ### Configure Caddy for subfolder exposure Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/16-expose-the-server-in-a-subfolder.md Use handle_path to strip the prefix and header_down to rewrite the Location header. ```caddy :80 { handle_path /subpath/* { reverse_proxy { to mediamtx-ip:8889 header_down Location ^/ /subpath/ } } } ``` -------------------------------- ### SHA256 Hashing Example Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/06-authentication.md Command to hash a password using SHA256 for the internal database authentication. ```sh echo -n "mypass" | openssl dgst -binary -sha256 | openssl base64 ``` -------------------------------- ### Argon2 Hashing Example Source: https://github.com/bluenviron/mediamtx/blob/main/docs/2-features/06-authentication.md Command to hash a password using Argon2id for the internal database authentication. ```sh echo -n "mypass" | argon2 saltItWithSalt -id -l 32 -e ``` -------------------------------- ### WebRTCPublisher.cs Source: https://github.com/bluenviron/mediamtx/blob/main/docs/3-publish/20-unity.md A C# script for Unity that captures video from a camera and publishes it as a WebRTC stream. ```csharp using System.Collections; using UnityEngine; using Unity.WebRTC; using UnityEngine.Networking; public class WebRTCPublisher : MonoBehaviour { public string url = "http://localhost:8889/unity/whip"; public int videoWidth = 1280; public int videoHeight = 720; private RTCPeerConnection pc; private MediaStream videoStream; void Start() { pc = new RTCPeerConnection(); Camera sourceCamera = gameObject.GetComponent(); videoStream = sourceCamera.CaptureStream(videoWidth, videoHeight); foreach (var track in videoStream.GetTracks()) { pc.AddTrack(track); } StartCoroutine(WebRTC.Update()); StartCoroutine(createOffer()); } private IEnumerator createOffer() { var op = pc.CreateOffer(); yield return op; if (op.IsError) { Debug.LogError("CreateOffer() failed"); yield break; } yield return setLocalDescription(op.Desc); } private IEnumerator setLocalDescription(RTCSessionDescription offer) { var op = pc.SetLocalDescription(ref offer); yield return op; if (op.IsError) { Debug.LogError("SetLocalDescription() failed"); yield break; } yield return postOffer(offer); } private IEnumerator postOffer(RTCSessionDescription offer) { var content = new System.Net.Http.StringContent(offer.sdp); content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/sdp"); var client = new System.Net.Http.HttpClient(); var task = System.Threading.Tasks.Task.Run(async () => { var res = await client.PostAsync(new System.UriBuilder(url).Uri, content); res.EnsureSuccessStatusCode(); return await res.Content.ReadAsStringAsync(); }); yield return new WaitUntil(() => task.IsCompleted); if (task.Exception != null) { Debug.LogError(task.Exception); yield break; } yield return setRemoteDescription(task.Result); } private IEnumerator setRemoteDescription(string answer) { RTCSessionDescription desc = new RTCSessionDescription(); desc.type = RTCSdpType.Answer; desc.sdp = answer; var op = pc.SetRemoteDescription(ref desc); yield return op; if (op.IsError) { Debug.LogError("SetRemoteDescription() failed"); yield break; } yield break; } void OnDestroy() { pc?.Close(); pc?.Dispose(); videoStream?.Dispose(); } } ```