Skip to content
LinuxDeep Dive Published Updated 7 min readViews unavailable

Linux ALSA PCM: Ring Buffers, Periods, and XRUN Recovery

Understand ALSA PCM ring-buffer states, periods, application pacing, underruns, recovery, and the limits of device-level latency tuning.

An ALSA PCM stream is not simply a function that sends one audio block to a sound card. The application and driver coordinate a cyclic buffer through hardware and software pointers, period notifications, thresholds, timestamps, and a stream state machine. A playback underrun or capture overrun, commonly reported as an XRUN, means one side failed to keep the ring moving within its configured constraints.

A small buffer can reduce latency but makes scheduling delays more visible. A large buffer can tolerate longer pauses but adds latency and may not fix a driver, clock, or application pacing defect. Diagnose the period, buffer, device, format, access mode, and actual wakeup behavior before changing global audio settings.

Discover the PCM device and its actual parameters

ALSA exposes hardware devices and higher-level plugin devices. A name such as default can route through a server or plugin layer that converts sample rate, format, channels, or timing. The hardware PCM device provides the closest view of kernel and driver capabilities, but bypassing an audio server can disrupt desktop routing or exclusive-use policy.

Read-only inventory examples:

aplay -l
arecord -l
cat /proc/asound/cards
cat /proc/asound/pcm

The commands list devices and substreams; availability depends on installed ALSA utilities and permission. Record the exact card, device, subdevice, driver, kernel, sample rate, channel count, sample format, and whether the application uses an audio server or direct hardware access. Do not infer that a device named USB Audio or HDMI has identical timing or format support to another machine.

The PCM API negotiates hardware parameters such as access mode, format, rate, channels, period size, and buffer size. Constraints can couple these values. A requested sample rate may be rounded or rejected, and a period size may need to satisfy integer, alignment, or device-specific rules. Always query the values the library actually committed rather than logging only the application’s requested settings.

Periods and the cyclic buffer

The PCM buffer is a ring shared across successive periods. Playback writes samples ahead of the hardware pointer; capture reads samples after the hardware has produced them. A period boundary is a notification opportunity, not necessarily one complete application message or an exact wall-clock deadline. The driver and hardware may expose period wakeups with different granularity.

The total buffer duration is approximately the frame capacity divided by the negotiated frames per second. A period is one part of that capacity. With a small period, the application wakes more frequently and may reduce buffering latency, but it also pays more scheduling and wakeup overhead. The buffer must leave enough slack for the worst-case scheduling pause and processing cost.

Software parameters shape when the application is considered ready or late. The availability threshold can control how much data is needed before a blocking write proceeds. Start and stop thresholds can determine when playback begins or stops on underrun. These are stream semantics, not magic latency knobs. A threshold that starts too early can expose an underfilled ring; a stop threshold that is too permissive can produce repeated silence and recovery.

Playback and capture have different ownership direction

For playback, userspace produces frames and the device consumes them. The producer must maintain enough queued data that the hardware never reaches an empty point. For capture, the hardware produces data and userspace must consume it before the ring wraps and overwrites unread frames. The same period settings can therefore have different consequences in each direction.

Treat PCM frame counts as frames, not bytes. A frame contains one sample for each channel; sample format determines bytes per sample, while interleaving and channel map determine layout. Confusing frames with bytes can overrun an application buffer even when the negotiated ALSA ring size is correct. For non-interleaved access, each channel plane has its own address and stride.

Memory-mapped access changes how userspace obtains ring areas but does not remove the need to track available frames and hardware position. An mmap commit or transfer operation advances the application-visible pointer according to the API. Do not hold a mapped area indefinitely or assume the pointer remains valid after stream teardown.

Detect and recover from XRUNs precisely

An XRUN is a state transition, not a short read that can always be retried. Playback typically enters an underrun state when the device exhausts queued frames; capture can overrun when the application falls behind. The application should identify the error, recover or prepare the PCM stream through the documented library operation, and decide whether to restart from a known position or report loss.

Blindly retrying the same write can loop forever if the stream remains in XRUN state. Recovery can discard queued audio or capture samples, so application logic should report a discontinuity when sample continuity matters. A media player may tolerate a short restart differently from a measurement recorder or a synchronized communication stream.

Instrument wakeup time, available frames, application processing duration, hardware pointer where supported, and XRUN count. Compare the application event loop with system scheduling, CPU pressure, power states, and device suspend. Raising a buffer may mask a long pause; it does not explain whether the pause came from CPU contention, a blocked callback, USB transport, a clock mismatch, or a device reset.

Timestamps and clocks

Audio devices and applications can use distinct clock domains. The PCM sample clock, system monotonic clock, and wall clock are not interchangeable. A timestamp identifies a point according to its clock type and the API’s accuracy rules. If an application aligns audio with video or network media, it must measure drift and convert clocks deliberately.

Long-running streams can drift even when each individual buffer is processed on time. If capture and playback devices have independent oscillators, one side may slowly gain or lose frames. A resampler or clock-recovery mechanism may be needed; repeatedly dropping a period causes audible discontinuities and poor synchronization.

Collect timestamp and pointer data only when the driver supports the selected mode, and retain the reported timestamp type. Do not derive an exact physical DAC or ADC time from a generic wakeup timestamp. It may represent a kernel event or estimated hardware position rather than the electrical instant at the connector.

Diagnose without changing the global sound stack

Start with the application’s negotiated parameters and whether it uses a plugin, PipeWire, PulseAudio, or direct ALSA. Inspect kernel logs for codec, USB, HDMI, or runtime-PM errors. A stream that works through a server but fails on direct hardware may reflect exclusive access, a format constraint, or a server policy rather than a broken PCM device.

Use the ALSA utility appropriate to the target device and a short, disposable test signal. Do not run a test that plays unexpectedly loud output on an attached amplifier. For capture, confirm input selection and gain at the device; a valid PCM stream can still capture silence from the wrong source.

When changing period or buffer values, change one parameter at a time and measure end-to-end latency, XRUN count, CPU wakeups, and audio quality under load. Re-test suspend/resume and hotplug. A setting tuned on AC power may behave differently on a laptop using deeper idle states.

Acceptance criteria

A stable PCM application records the actual negotiated format, period and buffer sizes, access mode, clock source, and device identity. It handles short transfers and XRUN recovery without infinite retry, exposes discontinuities to downstream consumers, and shuts down or resumes without stale mappings. Validate playback and capture separately with idle, loaded, and suspend/resume tests.

The ALSA ring is a timing contract shared by the application and device. The useful diagnosis is not “make the buffer larger,” but “which side owned the next frames, how much slack remained, which threshold controlled wakeup, and what clock defined the observed delay?”

Related:

Sources:

Comments