How to Stream to RTMP and Save Locally with FFmpeg Tee
This guide explains how to use the FFmpeg tee muxer to
simultaneously broadcast a live video stream to an RTMP destination and
save a copy to your local storage. By utilizing the tee
muxer, you can split your output stream into multiple destinations using
a single command, saving significant CPU resources by encoding the video
and audio only once.
The Basic FFmpeg Tee Muxer Command
To stream and record at the same time without re-encoding, you use
the -f tee option. This tells FFmpeg to write the encoded
packets to multiple outputs.
Here is the template command:
ffmpeg -i input_source -c:v libx264 -c:a aac -map 0:v -map 0:a -f tee "[f=flv]rtmp://your-rtmp-endpoint/live/stream_key|[f=mp4]local_backup.mp4"Command Breakdown
-i input_source: Your input, which can be a webcam, capture card, local file, or RTSP stream.-c:v libx264 -c:a aac: Encodes the video to H.264 and the audio to AAC, which are the standard, compatible formats for both RTMP and MP4 files.-map 0:v -map 0:a: Explicitly maps the first video stream and first audio stream to the output. Theteemuxer requires explicit stream mapping to function correctly.-f tee: Selects the tee muxer."[f=flv]rtmp://...|[f=mp4]local_backup.mp4": This is the compound output string enclosed in double quotes:|(Pipe): Separates the different output destinations.[f=flv]: Specifies that the container format for the RTMP stream must be FLV.[f=mp4]: Specifies that the container format for the local file must be MP4.
Handling Network Drops (Important)
By default, if one of the outputs in a tee command fails
(for example, if your internet connection blips and the RTMP connection
drops), FFmpeg will terminate the entire process. This means your local
recording will also stop.
To prevent this, use the onfail=ignore option on the
RTMP output. This ensures that if the stream fails, FFmpeg will continue
recording locally.
ffmpeg -i input_source -c:v libx264 -c:a aac -map 0:v -map 0:a -f tee "[f=flv:onfail=ignore]rtmp://your-rtmp-endpoint/live/stream_key|[f=mp4]local_backup.mp4"Real-World Example with a Webcam
If you are capturing from a local webcam (on Windows using
dshow) and want to stream to YouTube while saving a local
backup, use the following command:
ffmpeg -f dshow -i video="USB Video Device":audio="Microphone" -c:v libx264 -preset veryfast -b:v 3000k -maxrate 3000k -bufsize 6000k -c:a aac -b:a 128k -map 0:v -map 0:a -f tee "[f=flv:onfail=ignore]rtmp://a.rtmp.youtube.com/live2/your-stream-key|[f=mp4]C:/Videos/local_stream_backup.mp4"