FFmpeg Tee Muxer: Record and Transcode Live Streams
This article explains how to use the FFmpeg tee muxer to
simultaneously transcode an incoming live stream and write the output to
multiple destinations, such as a local backup file and a remote
streaming server. By using the tee muxer, you can perform
the resource-intensive transcoding process only once and safely
duplicate the resulting stream, saving significant CPU and memory
resources.
Understanding the Tee Muxer
The tee muxer behaves similarly to the standard Unix
tee command. It takes a single encoded audio/video stream
and splits it into multiple identical outputs. This is highly efficient
for live streaming workflows where you need to archive a broadcast
locally while broadcasting it live to platforms like YouTube, Twitch, or
a private RTMP server.
The Command Structure
To transcode an incoming stream and output it to both a local MP4 file and a remote RTMP destination, use the following basic command structure:
ffmpeg -i rtmp://source-server/live/input \
-c:v libx264 -preset veryfast -b:v 4000k -g 60 \
-c:a aac -b:a 128k \
-f tee -map 0:v -map 0:a \
"local_record.mp4|[f=flv]rtmp://dest-server/live/output"Parameter Breakdown
-i rtmp://source-server/live/input: Defines the incoming live stream source.-c:v libx264 -preset veryfast -b:v 4000k -g 60: Transcodes the incoming video to H.264 at a 4000k bitrate. The-g 60option sets the keyframe interval (GOP size), which is crucial for stable live streaming.-c:a aac -b:a 128k: Transcodes the audio to AAC at 128 kbps.-f tee: Tells FFmpeg to use theteemuxer for the output.-map 0:v -map 0:a: Explicitly maps the transcoded video and audio streams to theteemuxer."local_record.mp4|[f=flv]rtmp://dest-server/live/output": Specifies the outputs, separated by a pipe (|) character.local_record.mp4is the path for the local recording. FFmpeg automatically infers the container format from the.mp4file extension.[f=flv]rtmp://...specifies the RTMP destination. Because RTMP destinations do not have a standard file extension, you must explicitly define the format using the[f=flv]prefix option.
Handling Network Failures
with onfail
During a live stream, remote network connections can drop. By
default, if one of the tee muxer’s outputs fails, the
entire FFmpeg process will stop. To prevent a remote network glitch from
interrupting your local recording, you can use the
onfail=ignore option.
ffmpeg -i rtmp://source-server/live/input \
-c:v libx264 -preset veryfast -b:v 4000k \
-c:a aac -b:a 128k \
-f tee -map 0:v -map 0:a \
"local_record.mp4|[f=flv:onfail=ignore]rtmp://dest-server/live/output"In this configuration, if the connection to
rtmp://dest-server/live/output drops, FFmpeg will print a
warning to the console but will continue transcoding and saving the
local file local_record.mp4 without interruption.