How to Use WebSockets in FFmpeg

This article provides a practical guide on how to use the WebSocket protocol (ws:// and wss://) within FFmpeg for real-time media streaming. You will learn how to verify your FFmpeg installation’s WebSocket support, stream video output to a WebSocket server, and ingest a WebSocket stream as an input source using clear, command-line examples.

Verifying WebSocket Support in FFmpeg

Before attempting to stream, you must ensure that your FFmpeg build supports the WebSocket protocol. This support typically requires FFmpeg to be compiled with the libwebsockets library.

To check if your FFmpeg installation supports WebSockets, run the following command in your terminal:

ffmpeg -protocols | grep ws

If supported, you will see ws (unencrypted) and wss (encrypted) listed in the output under both input and output protocols.

Streaming Output to a WebSocket Server

FFmpeg can act as a client that sends a live media stream to a WebSocket server. Because WebSockets handle raw data packets, you should package your media into a streamable container format. MPEG-TS (-f mpegts) and fragmented MP4 (-f mp4 -movflags frag_keyframe+empty_moov) are the most common formats used for this purpose.

To stream a local video file to a WebSocket server, use the following command:

ffmpeg -re -i input.mp4 -f mpegts ws://127.0.0.1:8080

Receiving Input from a WebSocket Server

You can also use FFmpeg to connect to a WebSocket server that is broadcasting a media stream, and either save it to a file or transcode it in real-time.

To capture a stream from a WebSocket server and save it as an MP4 file, run:

ffmpeg -i ws://127.0.0.1:8080 -c copy output.mp4

Advanced Configuration Options

FFmpeg allows you to pass specific headers and options to the WebSocket protocol. If your WebSocket server requires a custom header or basic authentication, you can pass these parameters using the -headers option:

ffmpeg -re -i input.mp4 -headers "Authorization: Bearer Token123" -f mpegts ws://example.com/live