stream

package
v1.3.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 10 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package stream bridges a decode.Decoder to a real-time consumer through a single-producer, single-consumer ring buffer.

The ring is deliberately dumb: it copies interleaved float32 frames between two parties and nothing else. Waiting, backpressure, seeking and position accounting live in the streamer, which owns the one goroutine that decodes.

Concurrency contract: exactly one goroutine writes and one goroutine reads. The cursors are atomic and the hot paths never allocate, so a second concurrent writer is undefined behaviour rather than something the ring detects and defends against.

Index

Constants

View Source
const DefaultChunkFrames = 48000 * 100 / 1000

DefaultChunkFrames bounds one decoder read, about 100 ms.

View Source
const DefaultRingFrames = 48000 * 300 / 1000

DefaultRingFrames is the buffered-audio target at 48 kHz: about 300 ms, the middle of the usable 150 to 500 ms range.

Variables

View Source
var ErrClosed = errors.New("stream: closed")

ErrClosed is returned by every operation after Close. It is deliberately not io.EOF, so a consumer can tell a planned stop from the track ending.

View Source
var ErrEndOfStream = errors.New("stream: end of stream")

ErrEndOfStream means the decoder is exhausted, so a seek cannot be applied.

View Source
var ErrNotStarted = errors.New("stream: not started")

ErrNotStarted means Start has not been called, so there is no producer to apply a seek or fill the ring.

View Source
var ErrRunning = errors.New("stream: already started")

ErrRunning means Start was called on a streamer that is already running.

View Source
var ErrSeamlessNotSeekable = errors.New("stream: seamless swap requires a seekable decoder")

ErrSeamlessNotSeekable means a seamless swap was handed a decoder that cannot be positioned at an absolute frame, so the ring could not be kept without risking a duplicated or dropped span. The stream is left untouched.

View Source
var ErrSeekRange = errors.New("stream: seek target out of range")

ErrSeekRange means a seek target lies outside the stream.

Functions

func FramesToDuration

func FramesToDuration(frames int64) time.Duration

FramesToDuration converts a position in the streamer's one frame domain (output frames at 48 kHz) into wall clock time. Every frame-to-time conversion goes through here so no caller can pair a native-rate count with the output clock.

Types

type Config

type Config struct {
	// RingFrames is the ring capacity in output frames, rounded up to a power
	// of two. Zero selects DefaultRingFrames.
	RingFrames int

	// HighWater is the level the producer refills to, in output frames. The
	// producer stops decoding once the ring reaches it, which bounds memory to
	// the ring plus one chunk. Zero selects the ring capacity.
	HighWater int

	// LowWater is the level at which a parked producer resumes. Setting it
	// below HighWater gives hysteresis so a single consumer read does not wake
	// the decoder for one frame. Zero selects half the ring capacity.
	LowWater int

	// ChunkFrames is the largest decoder read per iteration, in output frames.
	// Zero selects DefaultChunkFrames; a value larger than the ring is clamped,
	// because one chunk must never be able to overrun the ring.
	ChunkFrames int

	// Modules are the pre-ring stages, applied in order after decode. They run
	// in the producer goroutine and may allocate.
	Modules []core.Module

	// ForwardSeekFallback permits the reopen-and-discard fallback when a decoder
	// advertises a native seek but refuses it, which is what a forward-only
	// source does. Off by default: a streamer that never expects a forward-only
	// decoder keeps its previous behaviour, where a refused seek surfaces
	// instead of being silently re-opened. The experimental source-upgrade path
	// turns it on because its starting decoder is forward-only.
	ForwardSeekFallback bool
}

Config tunes the buffer. Zero fields take the defaults documented on each field, so the empty Config is the intended 300 ms setup.

type Opener

type Opener func(stop <-chan struct{}) (decode.Decoder, error)

Opener builds a decoder for the stream. It is called once at construction and again by the reopen-and-discard seek fallback, which is why the streamer cannot own a single decoder. The stop channel is closed on shutdown so an opener that reads from an interruptible source can return instead of stranding the producer in a blocking read.

type Ring

type Ring struct {
	// contains filtered or unexported fields
}

Ring is a power-of-two SPSC circular buffer of interleaved float32 frames.

Capacity is measured in frames (one frame is Ch samples) and is always a power of two so every index maps to a slot with a bitmask instead of a modulo. Write and Read report frames, not samples, and both are non-blocking and may transfer less than requested.

func NewRing

func NewRing(frames, ch int) *Ring

NewRing returns a ring with at least frames frames of capacity. The request is rounded up to the next power of two, which is why Cap can exceed it. A non-positive frame or channel count panics: rounding a zero up would hide a caller bug behind a ring that can never hold anything.

func (*Ring) Cap

func (r *Ring) Cap() int64

Cap is the real capacity in frames after rounding, which is what Len and Space are relative to.

func (*Ring) Ch

func (r *Ring) Ch() int

Ch is the interleaved channel count the ring was created with.

func (*Ring) Len

func (r *Ring) Len() int64

Len is the number of frames currently buffered.

func (*Ring) Read

func (r *Ring) Read(p []float32) int

Read copies whole frames into p and returns how many were available. It never waits for data and never writes past len(p).

func (*Ring) Reset

func (r *Ring) Reset()

Reset drops every unread frame by moving the write cursor back to the read cursor. It must not run concurrently with Read: a reader that snapshotted the old write cursor would advance the read cursor past the new one and make the ring look almost full. The streamer calls it only while holding the lock that also excludes consumers.

func (*Ring) Space

func (r *Ring) Space() int64

Space is the number of frames the next Write can accept.

func (*Ring) Write

func (r *Ring) Write(p []float32) int

Write copies whole frames from p and returns how many were stored. A partial trailing frame is ignored, and a full ring accepts nothing.

type Stats

type Stats struct {
	Underruns int64
	Buffered  int64
	Decoded   int64
}

Stats is a snapshot of the streamer's counters. Buffered is read at call time; the rest are cumulative since construction.

type Streamer

type Streamer struct {
	// contains filtered or unexported fields
}

Streamer owns the decoder goroutine and the ring that feeds the consumer. Its position domain is output frames at 48 kHz; nothing else here counts frames, so a native-rate count can never be mixed with the output clock or a sample count.

func New

func New(open Opener, cfg Config) (*Streamer, error)

New opens the decoder, configures the pre-module chain and validates that it ends at 48 kHz stereo float32. Every setup error surfaces here rather than from the producer goroutine, so a bad format fails loudly at construction.

func (*Streamer) Close

func (s *Streamer) Close() error

Close stops the producer, wakes every blocked reader and writer, and releases the decoder. It is safe to call more than once and from several goroutines.

func (*Streamer) Done

func (s *Streamer) Done() <-chan struct{}

Done is closed when the decoder is exhausted or fails, which is the only way EOS is signalled. Close does not close it: a planned shutdown is reported by the read methods returning ErrClosed.

func (*Streamer) Position

func (s *Streamer) Position() int64

Position is the output frame index of the next frame the consumer will receive. It advances as frames are read and jumps to the target on seek.

func (*Streamer) ReadFrames

func (s *Streamer) ReadFrames(dst []float32) (int, error)

ReadFrames copies up to len(dst)/2 frames and returns how many it wrote. It waits only while the ring is empty and the stream is still live, so it never spins; once the decoder is exhausted it returns io.EOF (or the decoder's error) after the buffered tail drains.

The signature is exactly playback.Provider's, so a Streamer can be passed straight to a device.

func (*Streamer) SeekFrame

func (s *Streamer) SeekFrame(frame int64) error

SeekFrame repositions the stream so the next frame the consumer receives is frame, counted in 48 kHz output frames. It returns once the whole sequence has run: the ring is flushed, the decoder is repositioned, position is reset and the ring is refilled. Concurrent seeks collapse to the latest target.

func (*Streamer) Start

func (s *Streamer) Start(ctx context.Context) error

Start launches the decoder goroutine. Cancelling ctx shuts the streamer down exactly like Close. It is an error to start twice or to start after Close.

func (*Streamer) Stats

func (s *Streamer) Stats() Stats

Stats reports the counters. Buffered is the current ring occupancy.

func (*Streamer) SwapDecoder

func (s *Streamer) SwapDecoder(target int64, open Opener) error

SwapDecoder reopens the stream with a different opener, repositions to target, resets the pre-modules and refills. Same gate and latest-wins discipline as SeekFrame.

A swap always builds a new decoder: it never reuses the current one's native seek, because that would keep the implementation being replaced. The opener is handed through the gated slot rather than written to s.open here, since the producer goroutine is the only one that may replace the decoder.

func (*Streamer) SwapDecoderSeamless

func (s *Streamer) SwapDecoderSeamless(open Opener) error

SwapDecoderSeamless installs the decoder built by open without flushing the ring. Opening and validating the new decoder run on the caller goroutine so slow container indexing never stalls the producer's ring refills; only positioning at the frontier and replacing the active decoder run on the producer. The pre-modules are not reset: the samples continue, so their state is still correct.

It is the counterpart of SwapDecoder for the source-upgrade path, where a forward-only stream is replaced by a seekable one over the same audio. The new decoder must implement decode.Seeker so it can be placed on an exact frame; otherwise the call fails with ErrSeamlessNotSeekable and the stream is left untouched.

A caller superseded by a newer request is released with that request's outcome, so a caller that must know whether its own swap happened has to run under the session's single-worker serialization.

func (*Streamer) TryReadFrames

func (s *Streamer) TryReadFrames(dst []float32) (int, error)

TryReadFrames is the read for a callback-based device that must not wait on the audio thread. It never parks for data or blocks on a decode; it copies whatever is buffered and returns. The only critical section is the bounded ring copy, shared with the seek flush, so a seek is the sole operation that can delay it. It reports io.EOF only once the stream is both exhausted and drained.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL