Streaming Basics

FFmpeg RTMP Broken Pipe and Other Push Errors: Causes, Fixes, 24/7 Setup

By the StreamLivestic team · · 13 min read

FFmpeg Broken Pipe Fixed — ffmpeg rtmp broken pipe

An ffmpeg rtmp broken pipe error means the server on the other end closed the connection while FFmpeg was still writing video to it. FFmpeg is rarely the cause. YouTube or Facebook hung up on purpose (bad or expired key, broadcast ended, a second encoder on the same key) or the network dropped. The fix is to find out which one happened, then run FFmpeg under a supervisor that reconnects after a network drop and stops retrying once the failure is permanent.

Quick fix: Check that the stream key is current and that no other encoder is using it. Run ffmpeg -protocols | grep rtmps to confirm your build supports RTMPS, and check that your URL looks exactly like rtmp://a.rtmp.youtube.com/live2/KEY or rtmps://live-api-s.facebook.com:443/rtmp/KEY, with no double slash and no trailing space. Then push with -re -stream_loop -1 -i file.mp4 -c copy -f flv -flvflags no_duration_filesize from a file that already has 2-second keyframes, and wrap it in a reconnect loop with backoff and a cap on quick failures.

What the error actually means

FFmpeg's RTMP output is a single TCP (or TLS) connection to the platform's ingest server. FFmpeg writes FLV packets into that socket nonstop. When the far end closes the socket, the next write fails, and the operating system's error comes back up through FFmpeg:

So when you search for an ffmpeg rtmp broken pipe fix, remember that the platform is not measuring your bitrate when it hangs up. It is enforcing session rules: is this key valid, is this broadcast still allowed to receive video, is someone else already sending on it. Most "random" broken pipes on a 24/7 server turn out to be one of those rules.

Why it happens

These are ordered by how often we see them behind an ffmpeg rtmp broken pipe on unattended server pushes, most common first.

The platform ended the broadcast

Facebook's Live Video API docs say a stream URL can be streamed to for up to 8 hours once used, and it must be used within 24 hours of creation (Meta Live Video API overview). At the limit Facebook closes the socket and you get a broken pipe or connection reset. Every reconnect after that fails, because that key is finished. YouTube can also end a broadcast: you or a moderator stopped it in Studio, the event's auto-stop was triggered by a data gap, or the stream hit a policy action.

The stream key is wrong, expired or rotated

A typo, a key you reset in YouTube Studio, a one-time Facebook key that has already been used, or a key with an invisible trailing newline from a config file. With a bad key, the connection usually opens and is then refused at publish time. You see Input/output error almost immediately, not after hours of streaming.

Two encoders on one key

OBS on a laptop and FFmpeg on a VPS, both pointed at the same key. Or a stale FFmpeg process your supervisor never killed, still holding the session while the new one tries to connect. Depending on the ingest you get Already publishing, or the older session gets kicked with a broken pipe. Either way they keep knocking each other off.

Network drop or route change

VPS network maintenance, a NAT or conntrack table timing out an idle-looking flow, a provider reroute, or the ingest server you were on being drained. These are the genuinely temporary failures, and a reconnect fixes them.

Wrong URL format

FFmpeg splits an RTMP URL as rtmp://server[:port]/app/playpath (FFmpeg protocols docs). If you join a base URL that already ends in / with another / and the key, you get live2//KEY. The app name or playpath then comes out wrong and the server rejects the publish. Other common mistakes: pasting the key into the URL and also passing it separately, using rtmp:// for Facebook (which requires RTMPS), and leaving out :443 on RTMPS hosts.

No TLS in the FFmpeg build

RTMPS is RTMP inside TLS. FFmpeg can only do it if it was compiled against OpenSSL, GnuTLS or mbedTLS. Some minimal Docker images and hand-built binaries leave TLS out, so rtmps:// fails with Protocol not found before any packet is sent.

The stream itself is malformed

This is rarer. Platforms tend to complain in their dashboard rather than drop you, but long keyframe gaps, broken timestamps at a loop point or a codec the ingest doesn't accept can lead to a disconnect or a broadcast that never goes healthy. YouTube asks for a keyframe every 2 seconds and flags anything over 4 seconds as a critical error (YouTube live streaming error messages).

How to fix it

1. Read the first error, not the last

Run FFmpeg once by hand with -loglevel info and look at the first error line and at how long the stream ran before it:

What you seeWhenMost likely causeRetry?
Input/output error on openWithin 1–2 s, every timeBad, used or ended key; broadcast closedNo. Fix the key
Already publishingOn connectAnother encoder or zombie process on the keyOnly after killing the other publisher
Broken pipe / Connection resetAfter ~8 h on Facebook8-hour live limitNot on the same key. You need a new live video
Broken pipe / Connection resetRandom, after minutes or hoursNetwork drop, ingest maintenanceYes, with backoff
Connection timed out / RTMP_Connect0On connectDNS, firewall, wrong host or portA few times, then alert
Protocol not foundInstantlyFFmpeg built without TLSNever. Replace the binary

2. Get the URL exactly right

# YouTube RTMP
rtmp://a.rtmp.youtube.com/live2/xxxx-xxxx-xxxx-xxxx-xxxx

# YouTube RTMPS
rtmps://a.rtmps.youtube.com:443/live2/xxxx-xxxx-xxxx-xxxx-xxxx

# Facebook (RTMPS only)
rtmps://live-api-s.facebook.com:443/rtmp/FB-123456789-0-Abc...

Build the URL in a way that can't produce a double slash, and strip whitespace from the key:

BASE="${BASE%/}"                              # drop trailing slash
KEY="$(printf '%s' "$KEY" | tr -d '[:space:]')"
URL="$BASE/$KEY"

Copy the server URL from the platform each time you set up a new destination rather than from an old note. YouTube's encoder settings page lists both RTMP and RTMPS and recommends RTMPS (YouTube encoder settings).

3. Fix "Protocol not found (rtmps)"

ffmpeg -hide_banner -protocols | grep -E 'rtmps|tls'
ffmpeg -hide_banner -buildconf | grep -E 'openssl|gnutls|mbedtls'

If rtmps isn't listed under output protocols, install an FFmpeg that includes TLS. Debian and Ubuntu distro packages and the common static Linux builds normally have it. Slimmed-down container images often don't. If you compile FFmpeg yourself, add --enable-openssl (or --enable-gnutls). Avoid --enable-librtmp unless you need it: it replaces the native RTMP code and gives you librtmp's terser error messages, such as RTMP_Connect0.

4. Kill duplicate publishers

pgrep -af 'ffmpeg.*live2'        # anything still pushing?
pkill -f 'ffmpeg.*YOUR_JOB_ID'   # kill the stale one, then wait 5–10 s

Use one key per encoder, always. If you test from OBS, use a separate test key or a private test broadcast. The supervisor in step 7 also has to make sure the old FFmpeg has actually exited before it starts a new one. Otherwise your own restart logic can cause "Already publishing".

5. Prepare the file once, then stream with -c copy

For a 24/7 loop, re-encoding live wastes CPU and adds another thing that can break. Encode the file once, with fixed keyframes and platform-friendly settings:

ffmpeg -i source.mov \
  -c:v libx264 -preset veryfast -profile:v high -pix_fmt yuv420p \
  -r 30 -g 60 -keyint_min 60 -sc_threshold 0 \
  -b:v 4500k -maxrate 4500k -bufsize 9000k \
  -c:a aac -b:a 128k -ar 44100 -ac 2 \
  -movflags +faststart -shortest loop.mp4

-g 60 at 30 fps gives a keyframe every 2 seconds. -sc_threshold 0 stops x264 adding extra keyframes on scene cuts. At 60 fps, use -g 120 -keyint_min 120. AAC at 44.1 kHz and 128 kbps matches YouTube's audio recommendation. -shortest keeps audio and video the same length, which matters at the loop point.

Use -c copy when the file is already H.264 + AAC with a regular GOP of 4 seconds or less. Re-encode instead when the source is HEVC, VP9 or variable frame rate, when keyframes are sparse or irregular, when you add overlays or text, or when the bitrate is too high for your uplink.

6. The push command

ffmpeg -hide_banner -nostats -loglevel warning \
  -re -stream_loop -1 -i loop.mp4 \
  -c copy -f flv -flvflags no_duration_filesize \
  -rw_timeout 15000000 \
  -progress pipe:1 \
  "$URL"

In our test, our 24/7 engine ran exactly this pattern (-re -stream_loop -1 -c copy -f flv) over RTMP to YouTube for more than 9 hours and over RTMPS to Facebook for 8 hours, with zero drops. When a properly prepared file is pushed like this, the remaining failures come from the platform or the network, not from FFmpeg.

7. Read -progress to detect stalls

Every second or so, -progress pipe:1 prints a block of key=value lines such as frame=, fps=, bitrate=, total_size=, out_time=, speed=, drop_frames=, ending with progress=continue, or progress=end when it exits. The useful checks:

ffmpeg ... -progress pipe:1 "$URL" 2>>"$ERRLOG" | while IFS='=' read -r k v; do
  case "$k" in
    total_size) echo "$(date +%s) $v" > /run/stream/heartbeat ;;
    speed)      SPEED="$v" ;;
  esac
done

A separate watchdog can then compare the heartbeat's timestamp with the current time.

8. Supervise with backoff, and know when to give up

This is where most ffmpeg rtmp broken pipe guides stop at while true; do ffmpeg ...; sleep 5; done. That loop is dangerous. In our test, after Facebook ended the live at the 8-hour mark, FFmpeg failed every ~2 seconds with Error opening output files: Input/output error (exit code 251) and retried 766 times overnight. It never had a chance of reconnecting, because that broadcast was over. The fix was to classify failures:

#!/usr/bin/env bash
# push.sh  —  usage: PLATFORM=facebook BASE=... KEY=... ./push.sh loop.mp4
set -u
IN="$1"
BASE="${BASE%/}"; KEY="$(printf '%s' "$KEY" | tr -d '[:space:]')"
URL="$BASE/$KEY"
MASK="${KEY:0:4}****"
LOG=/var/log/stream/push.log
backoff=5; quick=0

mask() { sed -u "s#${KEY}#${MASK}#g"; }

while true; do
  start=$(date +%s)
  ffmpeg -hide_banner -nostats -loglevel warning \
    -re -stream_loop -1 -i "$IN" \
    -c copy -f flv -flvflags no_duration_filesize \
    -rw_timeout 15000000 -progress pipe:1 "$URL" \
    2> >(mask >> "$LOG") >/dev/null &
  pid=$!
  while kill -0 "$pid" 2>/dev/null; do sleep 2; done   # 2-second liveness check
  wait "$pid"; code=$?
  ran=$(( $(date +%s) - start ))
  echo "$(date -Is) exit=$code ran=${ran}s" | mask >> "$LOG"

  [ "$code" -eq 0 ] && break                       # clean finish
  if [ "${PLATFORM:-}" = facebook ] && [ "$ran" -ge 27000 ]; then
    echo "Facebook 8h limit reached; need a new live video" >> "$LOG"; exit 3
  fi
  if [ "$ran" -lt 30 ]; then quick=$((quick+1)); else quick=0; backoff=5; fi
  if [ "$quick" -ge 5 ]; then
    echo "5 quick failures (last exit $code): permanent, stopping" >> "$LOG"; exit 2
  fi
  sleep "$backoff"
  backoff=$(( backoff*2 > 60 ? 60 : backoff*2 ))
done

27,000 seconds is 7.5 hours. Exit codes 2 and 3 tell systemd, or whatever wraps the script, that this was a deliberate stop.

9. Run it under systemd

# /etc/systemd/system/[email protected]
[Unit]
Description=24/7 RTMP push %i
After=network-online.target
Wants=network-online.target

[Service]
EnvironmentFile=/etc/stream/%i.env      # PLATFORM, BASE, KEY (chmod 600)
ExecStart=/usr/local/bin/push.sh /srv/video/%i.mp4
Restart=on-failure
RestartSec=10
RestartPreventExitStatus=2 3            # permanent failures: don't restart
KillMode=control-group                  # never leave a zombie ffmpeg on the key
TimeoutStopSec=10

[Install]
WantedBy=multi-user.target

RestartPreventExitStatus carries the "know when to give up" logic into systemd, and KillMode=control-group makes sure stopping the unit also kills the FFmpeg child process. Without it, the child can keep publishing and cause "Already publishing" on the next start. Start each stream with systemctl enable --now push@mychannel.

10. Understand the exit codes

On current FFmpeg builds, a failed run usually exits with the negated system error code truncated to 8 bits, which is how Input/output error (EIO, 5) shows up as 251. By the same arithmetic you would expect Broken pipe (EPIPE, 32) as 224 and Connection reset (ECONNRESET, 104) as 152 on Linux. Older builds often just return 1, and 255 usually means FFmpeg was stopped by a signal (Ctrl+C, SIGTERM from your supervisor). Treat the numbers as hints and confirm them on your own binary. The supervisor above relies on how long the run lasted more than on the code, which works on every version.

11. Keep the stream key out of your logs

FFmpeg prints the full output URL, key included, in the Output #0, flv, to 'rtmp://...' line and in most error lines. Anyone who reads that log, or the support ticket you paste it into, can stream to your channel. Pipe stderr through a masking filter as the script does (sed -u "s#$KEY#${KEY:0:4}****#g"), keep keys in a chmod 600 env file rather than on the command line where possible, and remember that ps aux shows FFmpeg's full arguments to every user on the box. On shared servers, restrict /proc visibility (hidepid=2) or run each stream under its own user. If a key ever leaks, reset it on the platform.

If you'd rather not maintain this yourself, StreamLivestic runs the same FFmpeg push with the quick-failure cap, Facebook 8-hour detection and key masking built in.

How to stop the ffmpeg rtmp broken pipe error coming back

FAQ

Why does FFmpeg say Broken pipe when streaming to YouTube?

The YouTube ingest closed the connection while FFmpeg was still sending. The usual reasons are an ended broadcast, a reset or wrong stream key, a second encoder on the same key, or a network drop. Check the first error line and how long the stream ran to tell which.

Why does FFmpeg stop streaming to Facebook after 8 hours?

Meta's Live Video API lets a stream URL be used for up to 8 hours. After that the socket is closed and the same key will refuse every reconnect, so you need to create a new live video and stream key.

How do I fix Protocol not found for rtmps in FFmpeg?

Your FFmpeg build has no TLS support. Run ffmpeg -protocols and look for rtmps; if it is missing, install a build compiled with OpenSSL, GnuTLS or mbedTLS.

What does Server error: Already publishing mean?

Another encoder, or an old FFmpeg process that never exited, is already publishing on that stream key. Kill the other publisher, wait a few seconds and reconnect, and use one key per encoder.

Can I use -c copy with -stream_loop -1 for a 24/7 stream?

Yes, if the file is already H.264 and AAC with keyframes every 2 seconds and audio and video of equal length. Otherwise re-encode the file once with fixed keyframes and then stream it with -c copy.

What does FFmpeg exit code 251 mean?

On current builds FFmpeg exits with the negated error code truncated to 8 bits, so 251 corresponds to Input/output error (EIO). When streaming, it usually means the server refused the session, for example because of a bad or finished stream key.

How do I hide my stream key in FFmpeg logs?

Pipe FFmpeg's stderr through a filter such as sed that replaces the key with a masked version, keep the key in a permission-restricted env file, and limit who can see process arguments on the server.

FFmpegRTMPRTMPSYouTube LiveFacebook Live24/7 streamingBroken pipesystemdStream key

Sources & official docs