October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
VGSources
FFmpeg

How to Monitor FFmpeg YouTube Stream Progress With a Watchdog Script

A watchdog can detect stale FFmpeg progress and process exits, but YouTube ingest and playback need separate checks. Learn the signals, setup and recovery safeguards.

By VGSources Team 9 min read
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use FFmpeg’s machine-readable -progress output as a heartbeat, then have a supervisor distinguish a stalled process from a process that exited. That tells you whether FFmpeg is still advancing—not whether YouTube is receiving a healthy stream. Check YouTube Live Control Room separately for ingest status and inspect playback for viewer-facing audio and video quality.

What a watchdog can—and cannot—tell you

There are four different signals to monitor. Treat them separately rather than reducing them to one “stream healthy” flag:

  • FFmpeg progress heartbeat: FFmpeg is producing complete progress updates. This indicates process activity, not successful delivery to YouTube.
  • Process status and stderr: The process may exit, or it may report errors while running. Capture its exit code and diagnostic output.
  • YouTube ingest status: Live Control Room reports the stream status and its own error messages. See YouTube’s live stream metrics guidance.
  • Playback and media quality: Check that the player receives the expected picture and continuous audio. YouTube recommends monitoring stream quality during an event in its live streaming tips.

A progressing FFmpeg process can still send content YouTube rejects, or produce audio or video problems that a process heartbeat cannot detect.

How FFmpeg progress records work

FFmpeg’s -progress option emits machine-readable key=value lines. A group of lines forms an update, and its final line is progress=continue or progress=end. Parse complete groups and update the watchdog heartbeat only when the terminating progress line arrives; a partial group is not a fresh heartbeat. The FFmpeg CLI documentation specifies a default reporting period of 0.5 seconds. The example below explicitly requests one second so the heartbeat cadence is easy to reason about.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Send progress to a dedicated channel such as stdout with -progress pipe:1, and keep human-readable diagnostics on stderr. Do not parse FFmpeg’s ordinary status display as though it were a stable machine interface.

Set up an FFmpeg-to-YouTube stream

  1. Get the ingest URL and key. In YouTube Live Control Room, create or open the stream and copy its server URL and stream key. YouTube explains the RTMPS setup in Encrypt your stream using RTMPS. Keep the key private: do not commit it to a repository, publish it in a script, or print it into logs.
  2. Choose a supported output. YouTube documents RTMP and RTMPS encoder streaming and recommends RTMPS. Its current recommendations cover H.264, H.265/HEVC and AV1, up to 60 fps, and a recommended two-second keyframe interval that should not exceed four seconds. Bitrate depends on codec, resolution and frame rate, so consult the current YouTube encoder settings and bitrate table for your actual output.
  3. Test FFmpeg before adding automatic restarts. Use your normal input and encoding options, but include -progress pipe:1 -stats_period 1 -nostdin. FFmpeg’s -nostdin disables interactive standard input, which is useful for unattended runs. Confirm that progress records appear and that the stream reaches YouTube before relying on a watchdog.
  4. Supply credentials safely. The sample takes the RTMPS URL and key from environment variables, not command-line arguments in the script. Environment variables are not a complete secret-management system: use an appropriately protected service environment and restrict access to the host and its process information.

A Python watchdog for progress, exit status and bounded restarts

This POSIX-oriented example launches one FFmpeg process at a time, reads its progress channel, timestamps stderr, detects stale complete updates, and applies a capped retry count with exponential backoff. It stops rather than retrying forever. It does not certify YouTube ingest health; pair it with Live Control Room monitoring.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
#!/usr/bin/env python3
import os
import signal
import subprocess
import sys
import threading
import time
from datetime import datetime, timezone

# Replace this with the real input and encoding options for your source.
# Keep the stream key out of this file and out of logs.
RTMPS_URL = os.environ["YOUTUBE_RTMPS_URL"].rstrip("/")
STREAM_KEY = os.environ["YOUTUBE_STREAM_KEY"]
DESTINATION = f"{RTMPS_URL}/{STREAM_KEY}"

PROGRESS_PERIOD = 1.0       # requested FFmpeg reporting period, seconds
STALE_AFTER = 30.0          # operator-selected; validate for your source/network
MAX_RESTARTS = 5             # retries after the first attempt
BACKOFF_INITIAL = 2.0       # seconds
BACKOFF_CAP = 60.0          # seconds
STOP = threading.Event()


def log(message):
    stamp = datetime.now(timezone.utc).isoformat(timespec="seconds")
    print(f"{stamp} {message}", file=sys.stderr, flush=True)


def handle_signal(signum, _frame):
    STOP.set()


signal.signal(signal.SIGTERM, handle_signal)
signal.signal(signal.SIGINT, handle_signal)


def stderr_reader(pipe, proc):
    # Preserve diagnostics with timestamps; never print the command or key.
    for line in iter(pipe.readline, ""):
        if line:
            log(f"ffmpeg[{proc.pid}] {line.rstrip()}")
    pipe.close()


def run_once():
    command = [
        "ffmpeg", "-nostdin",
        # Add your input and encoding options here, before the output URL.
        # Example input: "-re", "-i", "/path/to/video.mp4",
        "-re", "-i", "/path/to/video.mp4",
        "-c:v", "libx264", "-preset", "veryfast", "-b:v", "4500k",
        "-maxrate", "4500k", "-bufsize", "9000k",
        "-g", "60", "-c:a", "aac", "-b:a", "160k",
        "-f", "flv",
        "-progress", "pipe:1", "-stats_period", str(PROGRESS_PERIOD),
        DESTINATION,
    ]
    # Replace the example media and encoding settings to match your source,
    # output resolution/frame rate, and YouTube's current guidance.
    proc = subprocess.Popen(
        command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
        text=True, bufsize=1,
    )
    last_update = time.monotonic()
    fields = {}
    stderr_thread = threading.Thread(
        target=stderr_reader, args=(proc.stderr, proc), daemon=True
    )
    stderr_thread.start()
    log(f"started FFmpeg pid={proc.pid}")

    try:
        while not STOP.is_set():
            # readline can block if FFmpeg stops writing; poll the process and
            # heartbeat from a separate reader to enforce the stale timeout.
            line = proc.stdout.readline()
            if line:
                line = line.rstrip("rn")
                if "=" in line:
                    key, value = line.split("=", 1)
                    fields[key] = value
                    if key == "progress":
                        last_update = time.monotonic()
                        status = value
                        log(f"progress update status={status} "
                            f"frame={fields.get('frame', 'not reported')} "
                            f"out_time={fields.get('out_time', 'not reported')}")
                        fields.clear()
                        if status == "end":
                            break
            code = proc.poll()
            if code is not None:
                return ("exit", code)
            if time.monotonic() - last_update > STALE_AFTER:
                return ("stale", None)
        return ("stop", None)
    finally:
        if proc.poll() is None:
            proc.terminate()
            try:
                proc.wait(timeout=10)
            except subprocess.TimeoutExpired:
                proc.kill()
                proc.wait()
        if proc.stdout:
            proc.stdout.close()
        stderr_thread.join(timeout=2)


restarts = 0
while not STOP.is_set():
    reason, code = run_once()
    if reason == "stop":
        break
    if reason == "exit" and code == 0:
        log("FFmpeg exited normally")
        break
    log(f"FFmpeg attempt ended reason={reason} exit_code={code}")
    if restarts >= MAX_RESTARTS:
        log("restart limit reached; stopping for operator review")
        sys.exit(1)
    delay = min(BACKOFF_INITIAL * (2 ** restarts), BACKOFF_CAP)
    restarts += 1
    log(f"restart {restarts}/{MAX_RESTARTS} in {delay:g}s")
    STOP.wait(delay)

In HTML, the ampersand comparisons in the code block are shown as > by this article format; when saving as a Python file, write the Python comparison operators > as the literal > character (for example, time.monotonic() - last_update > STALE_AFTER should be time.monotonic() - last_update > STALE_AFTER in source). Set STALE_AFTER to a threshold appropriate for the input, network and host load; neither FFmpeg nor YouTube prescribes a universal watchdog timeout. The values shown for threshold, retry count and backoff are operator choices, not reliability guarantees.

Important: as written, the sample’s synchronous stdout.readline() can block while FFmpeg is alive but silent, preventing the loop from checking its timeout. For a production deployment, read stdout in a dedicated thread and have the supervisor consume updates from a thread-safe queue with a timed wait, or use nonblocking I/O or an OS service manager with an independent timeout. Also test signal handling and child cleanup on the target host. This limitation is why the listing is an implementation pattern, not a drop-in production supervisor.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Make the progress reader nonblocking before unattended use

For a production watchdog, move progress parsing into a reader thread that places only completed progress records into a queue. The supervisor should wait on that queue with a timeout, check proc.poll() on each timeout, and compare the last completed record’s monotonic timestamp with the selected stale threshold. If the queue wait expires and the process is alive past the threshold, terminate the child, wait for it, then apply the bounded retry policy. Preserve the FFmpeg stderr reader and ensure termination also works when the parent receives SIGTERM or SIGINT.

The sample’s illustrative video bitrate, audio bitrate, GOP and preset are not universal YouTube settings. Replace them for your source and target resolution/frame rate using YouTube’s current codec-specific table; in particular, make the GOP/keyframe interval consistent with the documented two-second recommendation and four-second maximum.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose the timeout and restart policy

Use complete updates, not individual lines

Refresh the heartbeat only when a whole key/value group ends in progress=continue or progress=end. A process that emits some keys but never completes an update has not produced a fresh heartbeat.

Allow for normal variation

A one-second reporting period does not mean the watchdog should restart after one missed second. Set a larger, operator-selected stale threshold that allows for ordinary network stalls, irregular sources and host load. Validate it under the conditions in which the stream will run; no single threshold is appropriate for every source.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Bound retries and retain evidence

Record timestamps, the process exit code and stderr for every attempt. Use capped retries or backoff rather than a tight restart loop. If losing an event is costly, alert an operator before restarting and decide explicitly whether a normal exit or progress=end means completion or a reason to start another item.

How do I know if FFmpeg is still streaming to YouTube?

Check the heartbeat first to answer whether FFmpeg is advancing. Then check the process exit status and stderr for termination or local errors, Live Control Room for YouTube’s ingest status and errors, and the player for actual audio and video. FFmpeg progress by itself cannot confirm successful ingestion or viewer-facing quality.

Common watchdog and stream failures

Symptom Likely interpretation What to check or do
No completed progress updates; process still exists FFmpeg may be hung, blocked on input/output, or unable to make progress. Check source availability, host load and stderr. Apply the chosen stale policy only after allowing for normal variation.
FFmpeg exited This is a process termination, not a stale heartbeat. Record the exit code and stderr, then apply the configured retry or alert policy. Do not discard the diagnostic log when starting a replacement process.
Progress continues, but YouTube reports an error The encoder is active, but ingest may be rejected or unhealthy. Read the specific Live Control Room message and verify the RTMPS destination, stream key and encoder settings.
Live status appears healthy, but audio or video is wrong Process and ingest signals do not prove viewer-facing quality. Inspect playback and audio/video continuously during the event; use YouTube’s stream-health messages as an additional signal.
Repeated restarts The source, network, configuration or host may be persistently failing. Stop after a bounded number of attempts, preserve logs and investigate instead of allowing a crash loop.

Test recovery before a live event

Test the primary-to-backup path before relying on it. YouTube’s live streaming tips recommend testing a backup encoder by stopping the primary encoder or disconnecting its Ethernet, then checking that the player rolls over to the backup. Confirm separately that your watchdog detects a stale progress feed, cleans up the old child process and respects its retry limit.

Or let it run in the cloud

If your goal is to keep uploaded, prerecorded videos looping on a YouTube channel—not to broadcast a live camera or gameplay capture—StreamNeo is a cloud alternative: upload a recording or build a playlist, add your YouTube stream key once, and go live. Nothing has to stay on at home; every slot streams the uploaded quality up to 4K 60fps at one flat price per slot, with automatic recovery if YouTube drops the stream. The first day is free with no card. Monthly billing is $9.99 per month. In India, UPI and cards are supported; card checkout is available worldwide. Start the free day with StreamNeo.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from Patch Notes

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.