How to Stream RTSP to WebSocket with FFmpeg
Streaming live video from an RTSP IP camera to a web browser often requires converting the feed into a WebSocket-compatible format for low-latency playback. Since web browsers cannot native play RTSP streams, FFmpeg is used to capture the camera feed, transcode it, and send it to a WebSocket relay server. This guide provides the exact FFmpeg command required to achieve this pipeline, along with a clear explanation of how each parameter works.
The Streaming Pipeline
Because FFmpeg cannot act as a WebSocket server directly, the
standard approach is to stream the video from FFmpeg to a local relay
server (such as a Node.js helper script or jsmpeg relay)
via TCP or HTTP. The relay server then broadcasts the incoming stream to
connected web browsers via WebSockets.
The FFmpeg Command
Run the following command in your terminal to capture the RTSP stream, transcode it to MPEG-TS (highly compatible with web-based WebSocket players like JSMpeg), and output it to your local relay server:
ffmpeg -rtsp_transport tcp -i rtsp://username:password@camera_ip:554/stream_path -f mpegts -codec:v mpeg1video -s 1280x720 -b:v 1500k -r 30 -bf 0 -codec:a mp2 -ar 44100 -ac 1 http://127.0.0.1:8081/supersecretCommand Parameter Breakdown
-rtsp_transport tcp: Forces FFmpeg to use TCP instead of UDP to receive the RTSP stream. This prevents packet loss and video corruption over unstable network connections.-i rtsp://...: Specifies the input URL of your RTSP camera, including the credentials, IP address, port, and stream path.-f mpegts: Sets the output container format to MPEG-TS, which is streamable and can be parsed in real-time by JavaScript players.-codec:v mpeg1video: Transcodes the video to the MPEG-1 codec. This is required if you are using lightweight players like JSMpeg for browser decoding without heavy CPU usage.-s 1280x720: Resizes the output resolution to 720p (optional; adjust as needed to save bandwidth).-b:v 1500k: Sets the video bitrate to 1500 kbps to balance quality and network performance.-r 30: Sets the output framerate to 30 frames per second.-bf 0: Disables B-frames. This reduces decoding latency significantly, ensuring the stream remains as close to real-time as possible.-codec:a mp2: Transcodes the audio stream to MP2, which is the standard audio codec used alongside MPEG-1 video in MPEG-TS containers. If you do not need audio, replace this and the following audio flags with-an.-ar 44100 -ac 1: Sets the audio sample rate to 44.1 kHz and downmixes the audio to a single channel (mono).http://127.0.0.1:8081/supersecret: The destination URL where your WebSocket relay server is listening for the incoming HTTP POST stream.
By running this command alongside a WebSocket relay utility, you can achieve near-instantaneous IP camera viewing inside any modern web browser without requiring third-party browser plugins.