playsound developer on retainer: Linux GStreamer backend bus.poll(Gst.MessageType.EOS, Gst.CLOCK_TIME_NONE) ignores GST_MESSAGE_ERROR from missing MP3 codec — Celery worker threads hang on first playback call; all 20 workers depleted within 2 hours; notification service 100% unavailable — subprocess.run fix — 2 weeks — playsound developer on monthly retainer

playsound 1.2.2 • Python 3.9; playsound.playsound('alert.mp3', block=True) • Northfield Playsound Ltd. (real-time event notification service; 2,000 active user sessions; 20 Celery worker threads, each calling playsound('alert.mp3', block=True) on task execution; Ubuntu 22.04 minimal production server in Docker; playsound 1.2.2 Linux backend creates Gst.ElementFactory.make('playbin', 'playbin') pipeline; calls bus.poll(Gst.MessageType.EOS, Gst.CLOCK_TIME_NONE) to block until EOS; MP3 codec — gst-plugins-ugly — absent from production Docker image; GStreamer emits GST_MESSAGE_ERROR for unrecognized MP3 format; bus.poll() filtered to EOS only — ignores error message — blocks forever; Celery worker thread hangs; workers depleted one-by-one at notification rate; all 20 workers hung within 2 hours of deployment; 2,000 alert tasks queued, 0 delivered; 100% notification failure for 2 weeks; fix: subprocess.run(['ffplay', '-nodisp', '-autoexit', '-loglevel', 'quiet', sound_file], timeout=30); 1.5h retainer engagement

Northfield Playsound Ltd. built a real-time event notification service for a facility management platform. When a monitored sensor crossed a threshold — a temperature alarm, a door-open event, an equipment fault — the platform queued a Celery task that played an MP3 audio alert through the server’s audio output to operators monitoring a local display. The developer had used playsound successfully in development on a personal Ubuntu workstation with a full desktop installation. After containerising the application in a Docker image based on ubuntu:22.04, pushing to staging, and then to production, the deployment appeared to succeed. The first alert tasks were processed normally by the health check — a 1-second WAV file that worked correctly. MP3 alerts were routed to the same code path without additional testing. Within 10 minutes of go-live, Celery workers began stalling. The task monitor showed 20 tasks in “active” state with 0% completion. No exception was raised, no traceback appeared in the logs, no error was recorded. The tasks were simply never finishing. After 2 hours all 20 workers in the pool were occupied by permanently stalled alert tasks. Incoming events accumulated in the queue — 2,000 undelivered alerts by the end of the first day. The notification service delivered 0% of alerts for 2 weeks while the team investigated.

The root cause was identified using py-spy, a sampling profiler for live Python processes. Attaching to a stalled Celery worker showed every thread blocked inside playsound._playsoundNix at the line bus.poll(Gst.MessageType.EOS, Gst.CLOCK_TIME_NONE). The playsound 1.2.2 Linux backend creates a GStreamer playbin pipeline and blocks until the pipeline bus delivers an EOS (end-of-stream) message. The Gst.CLOCK_TIME_NONE argument means: wait indefinitely, no timeout. The Gst.MessageType.EOS argument means: only unblock for an EOS message. When GStreamer cannot decode the audio file — because gst-plugins-ugly, the GStreamer package containing the MP3 decoder, was not installed in the Docker image — GStreamer emits a GST_MESSAGE_ERROR on the bus instead of an EOS. The bus.poll() call receives the error message, discards it because it does not match the EOS filter, and continues waiting. No exception is raised anywhere in the call stack. The function blocks forever. The developer’s workstation had accumulated gst-plugins-ugly from prior software installs; the Docker image, built from ubuntu:22.04 without that package, exposed the gap. The fix replaced every playsound(sound_file) call with subprocess.run(['ffplay', '-nodisp', '-autoexit', '-loglevel', 'quiet', sound_file], timeout=30, check=True). ffmpeg was already in the Docker image for video processing. subprocess.run() raises subprocess.TimeoutExpired if playback exceeds 30 seconds and subprocess.CalledProcessError if ffplay exits non-zero — both catchable, loggable, and actionable. After the fix, alert delivery recovered to 100%.

The annotated buggy and fixed playsound code, with a GStreamer codec diagnostic helper:

# Northfield Playsound Ltd. — playsound 1.2.2 Linux GStreamer EOS-only poll hang
# playsound 1.2.2; Python 3.9; Ubuntu 22.04; Docker ubuntu:22.04 base image
# Pipeline: Celery worker → playsound('alert.mp3', block=True) → GStreamer playbin
# Problem: bus.poll(Gst.MessageType.EOS, CLOCK_TIME_NONE) ignores GST_MESSAGE_ERROR
#          missing gst-plugins-ugly → GStreamer emits ERROR, not EOS → hangs forever
#          20 Celery workers depleted within 2 hours; 0% alert delivery
# Fix: subprocess.run(['ffplay', '-nodisp', '-autoexit', sound_file], timeout=30)

import subprocess
import shutil
import os


ALERT_TIMEOUT_S = 30  # maximum seconds to allow audio playback


# ── GStreamer codec diagnostic ───────────────────────────────────────────────

def diagnose_gstreamer_mp3() -> None:
    """
    Check if GStreamer can decode MP3 without hanging.
    Run once at service startup to catch missing codec before workers start.
    """
    # Check gst-plugins-ugly is installed (dpkg-based systems)
    result = subprocess.run(
        ['dpkg', '-l', 'gstreamer1.0-plugins-ugly'],
        capture_output=True, text=True
    )
    if result.returncode != 0 or 'ii' not in result.stdout:
        print("WARNING: gstreamer1.0-plugins-ugly is NOT installed.")
        print("  playsound('*.mp3', block=True) will hang indefinitely on this system.")
        print("  Fix: apt-get install -y gstreamer1.0-plugins-ugly")
        print("  Or use subprocess.run(['ffplay', '-nodisp', '-autoexit', sound_file])")
    else:
        print("gstreamer1.0-plugins-ugly is installed — MP3 decoding available.")

    # Confirm ffplay is available as fallback
    if shutil.which('ffplay'):
        print("ffplay found at:", shutil.which('ffplay'), "— subprocess fallback available.")
    else:
        print("WARNING: ffplay not found. Install ffmpeg for reliable audio playback fallback.")


# ── BUGGY playsound call ─────────────────────────────────────────────────────

def play_alert_buggy(sound_file: str) -> None:
    """
    BUG: playsound 1.2.2 Linux backend.
    bus.poll(Gst.MessageType.EOS, Gst.CLOCK_TIME_NONE) ignores GST_MESSAGE_ERROR.
    If gst-plugins-ugly is absent, GStreamer emits ERROR (not EOS) for MP3 files.
    bus.poll() discards ERROR message; continues waiting with no timeout.
    Calling thread blocks forever. No exception raised. Celery worker depleted.
    """
    import playsound
    playsound.playsound(sound_file, block=True)  # BUG: hangs if codec missing


# ── FIXED playsound replacement ───────────────────────────────────────────────

def play_alert_fixed(sound_file: str, timeout_s: float = ALERT_TIMEOUT_S) -> None:
    """
    FIX: use subprocess.run() with ffplay for reliable cross-codec audio playback.
    - Works for MP3, WAV, OGG, AAC without GStreamer codec installation.
    - Raises subprocess.TimeoutExpired if playback exceeds timeout_s seconds.
    - Raises subprocess.CalledProcessError if ffplay exits non-zero.
    - Both exceptions are catchable; Celery worker is never permanently stalled.
    """
    if not os.path.isfile(sound_file):
        raise FileNotFoundError(f"Alert sound file not found: {sound_file!r}")

    subprocess.run(
        ['ffplay', '-nodisp', '-autoexit', '-loglevel', 'quiet', sound_file],
        timeout=timeout_s,
        check=True,
    )


def play_alert_wav_only(sound_file: str, timeout_s: float = ALERT_TIMEOUT_S) -> None:
    """
    FIX (WAV files only): use aplay from alsa-utils — present by default on
    most Linux distributions, no extra codec packages required.
    '--' separator prevents filenames beginning with '-' from being treated as flags.
    """
    subprocess.run(
        ['aplay', '-q', '--', sound_file],
        timeout=timeout_s,
        check=True,
    )


# ── Worker-safe wrapper with timeout fallback ────────────────────────────────

def play_alert(sound_file: str) -> None:
    """
    Production-safe alert player for Celery workers.
    Uses ffplay with explicit timeout; logs errors; never hangs the worker thread.
    """
    import logging
    logger = logging.getLogger(__name__)

    try:
        play_alert_fixed(sound_file, timeout_s=ALERT_TIMEOUT_S)
        logger.debug("Alert played: %s", sound_file)
    except subprocess.TimeoutExpired:
        logger.error(
            "Alert playback timed out after %ss: %s — skipping",
            ALERT_TIMEOUT_S, sound_file
        )
    except subprocess.CalledProcessError as exc:
        logger.error(
            "Alert playback failed (ffplay exit %s): %s — skipping",
            exc.returncode, sound_file
        )
    except FileNotFoundError as exc:
        logger.error("Alert sound file not found: %s", exc)


# ── Root cause summary ────────────────────────────────────────────────────────

if __name__ == '__main__':
    diagnose_gstreamer_mp3()
    print()
    print("Root cause: playsound 1.2.2 Linux backend")
    print("  bus.poll(Gst.MessageType.EOS, Gst.CLOCK_TIME_NONE)")
    print("  Waits forever for EOS; ignores GST_MESSAGE_ERROR from missing codec")
    print("  gst-plugins-ugly absent from Docker image → ERROR emitted for MP3")
    print("  20 Celery workers hang; 0% alert delivery; 2 weeks")
    print()
    print("Fix: subprocess.run(['ffplay', '-nodisp', '-autoexit', sound_file], timeout=30)")
    print("  Alert delivery: 0% → 100%; worker hang rate: 0; 1.5h")

How playsound’s GStreamer backend, the bus.poll() message filter, and Linux codec packaging interact — and the correct pattern for production-safe audio playback in long-running Python services

playsound 1.2.2 uses three different backends depending on the platform: winmm.mciSendString on Windows, AppKit.NSSound on macOS, and GStreamer via gi.repository on Linux. Each backend has its own failure modes. The Linux GStreamer backend creates a playbin element — GStreamer’s high-level auto-plugging media player element — which automatically selects and chains decoders, demuxers, and audio sinks based on the file format and what plugins are installed. If playbin cannot find a suitable decoder for the input format, it transitions to an error state and emits a GST_MESSAGE_ERROR on the bus. playsound’s bus.poll(Gst.MessageType.EOS, Gst.CLOCK_TIME_NONE) explicitly filters for only EOS messages; CLOCK_TIME_NONE means no timeout. The GStreamer documentation describes bus.poll() as blocking “until a message of the given type is queued on the bus or until the given timeout has expired.” If the timeout is CLOCK_TIME_NONE and the matching message type never arrives — because only an ERROR message was emitted — the call never returns. This is not a GStreamer bug; it is correct behavior given the arguments passed. The issue is playsound’s choice to filter only for EOS without a concurrent ERROR handler. On Ubuntu, GStreamer codec packages are split across four groups: gst-plugins-base (Ogg, Theora, Vorbis), gst-plugins-good (FLAC, WAV, AAC via FAAD), gst-plugins-ugly (MP3 via libmad/libmpg123), and gst-plugins-bad (various). Ubuntu minimal images and many Docker base images include only gst-plugins-base. Full desktop installations and images built for media applications accumulate all four packages. MP3 decoding requires gst-plugins-ugly specifically. The discrepancy between a developer workstation with gst-plugins-ugly installed (from VLC, Rhythmbox, or similar) and a Docker image without it is the most common trigger for this hang. The practical mitigation: (1) add RUN apt-get install -y gstreamer1.0-plugins-ugly to the Dockerfile if playsound with MP3 files is a requirement; (2) convert all alert sounds to WAV and use subprocess.run(['aplay', '-q', '--', sound_file]) which requires only alsa-utils; (3) use subprocess.run(['ffplay', '-nodisp', '-autoexit', '-loglevel', 'quiet', sound_file]) with an explicit timeout=N for any format, ensuring ffmpeg is a declared Docker dependency; (4) add a startup health check that plays a test sound file with a threading timeout and aborts service startup if audio delivery fails. The retainer engagement was 1.5h: 0.5h triage (Celery workers stalled at 20/20 active; py-spy profiler attached to worker PID; every thread shows bus.poll() in call stack; playsound GStreamer backend identified); 0.5h root cause (GST_DEBUG=3 confirms GST_MESSAGE_ERROR for MP3 format; dpkg -l gstreamer1.0-plugins-ugly returns not-installed in Docker image; bus.poll() EOS-only filter confirmed in playsound 1.2.2 source at _playsoundNix); 0.25h fix (subprocess.run ffplay replacement; Docker image rebuild with ffmpeg dependency); 0.25h validation (20 MP3 alert tasks complete in 18 seconds; 0 hangs; 100% delivery confirmed; 1.5h total). Hours logged to HourTab with per-session breakdown.

Related retainer posts


Track retainer hours without a client portal

HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.

See pricing →