goavtest

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 22 Imported by: ? modules, 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 goavtest provides utilities for testing goav pipelines, in the spirit of net/http/httptest: deterministic sources, a recording sink, a fake clock, and passthrough codec and container fakes. Nothing here couples to *testing.T and nothing asserts — every helper returns a real grammar value (goav.Input, goav.Destination, runconfig.Option, *goav.Runtime), so test code is pipeline code.

A complete pipeline test is three values and one Run:

out := goavtest.NewCollector()
mix := goav.Mix(
    goavtest.Audio(48000, 1, []int16{100}, []int16{200}).Audio(),
    goavtest.Audio(48000, 1, []int16{50}, []int16{-50}).Audio(),
)
_ = goavtest.Runtime().Run(ctx, mix.To(out.Sink()))
// out.S16() == [[150] [150]]

The sources (Audio, Video, Packets, LiveAudio, NewTestSource with TestSourceScript) are PTS-stamped with coherent durations and declare their shape, so the planner solves conversions exactly as it would for production inputs. The Collector keeps references to everything a destination receives; WaitFrames, WaitPackets, and WaitEvents are the usual live-test synchronization points. Runtime is the one-liner deterministic runtime: standard filters, a passthrough codec for every well-known codec id, a byte-faithful container for every well-known container format id, and a fake clock so realtime pacing never sleeps for real.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Audio

func Audio(sampleRate, channels int, frames ...[]int16) goav.Input

Audio returns a deterministic S16 frame source: one interleaved audio frame per sample slice, then end of stream. Frames are PTS-stamped in sample time (frame n starts at the samples already played, timebase 1/sampleRate) with matching durations, so PTS-aligned joins and pacing behave coherently. Each call gets a distinct generated name (and stream id), so several Audio inputs can stand side by side as Mix/Composite/Select arms.

Example

ExampleAudio runs the smallest possible pipeline test: a deterministic audio source straight into a collector, asserting on the samples.

package main

import (
	"context"
	"fmt"

	"github.com/thesyncim/goav/goavtest"
)

func main() {
	ctx := context.Background()
	out := goavtest.NewCollector()
	err := goavtest.Runtime().Run(ctx, goavtest.Audio(48000, 1, []int16{1, 2}, []int16{3}).
		Audio().
		To(out.Sink()))
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(out.S16())
}
Output:
[[1 2] [3]]

func Codec

func Codec(id av.CodecID) runconfig.Option

Codec returns a runtime option registering a deterministic fake encoder+decoder pair for id, so chains can .Encode(...) and .Decode() without a real codec implementation. The encoder wraps each frame — headers, planes, and bytes — into one keyframe packet carrying the frame's PTS and duration; the decoder unwraps it byte-faithfully. Decoding a packet that was NOT produced by this encoder (a Packets fixture, say) yields one deterministic silent/black frame shaped by the stream's declared codec parameters, so packet-domain fixtures still flow through decode chains.

The registered descriptor is media-agnostic (it matches audio and video alike) and capability-open, so it never fails a compatibility check.

func Format

func Format(id av.FormatID) runconfig.Option

Format returns a runtime option registering a deterministic fake container for id: a muxer that writes a trivial length-prefixed framing (stream header, then one record per packet — stream id, timing, keyframe flag, and the payload verbatim), the matching demuxer that reads it back byte-faithfully, and a prober matching the "."+id name extension. A file muxed through it demuxes to the exact packets that were written, so File→FileInput round trips work without a real container.

func LiveAudio

func LiveAudio(name string, sampleRate, channels int, frames ...[]int16) goav.Input

LiveAudio returns an S16 frame source that never ends: it replays the given frames in a loop with continuously advancing PTS until the task stops — the input control-plane tests need (SelectActive, Rebranch, live Control), where the stream must outlive the assertion. The caller names it because the name is the stream id controls target (control.SelectActive(name)). With no frames it loops a single one-sample silent frame. The source retries on backpressure and returns cleanly when the task stops.

func LiveVideo

func LiveVideo(name string, width, height int) goav.Input

LiveVideo returns an I420 video source that never ends: it emits frames at 30fps PTS (frame n carries luma byte(n), like Video) until the task stops, for tests that attach, switch, or control a running video task. The caller names it because the name is the stream id controls target. The source retries on backpressure and returns cleanly when the task stops.

func Packets

func Packets(codecID av.CodecID, packets ...av.Packet) goav.Input

Packets returns a deterministic packet-domain source: it pushes the given packets in order, then ends the stream. Keyframe flags, PTS/DTS, durations, and payload bytes are honored verbatim — never restamped. Each packet's StreamID is rewritten to the source's generated stream id (a custom source carries exactly one stream, so foreign ids would route nowhere); an empty Type inherits the source's media kind, which is taken from the first packet that declares one, else inferred from a well-known codecID, else video.

func Runtime

func Runtime(opts ...runconfig.Option) *goav.Runtime

Runtime builds the deterministic test runtime. It contains exactly:

  • the standard frame filters (resample, resize), so shape-solver conversions work;
  • Codec(id) for every well-known av.Codec* id (opus, vorbis, flac, aac, vp8, vp9, h264, av1, pcm, text_utf8) — the passthrough fake, so .Encode(codec.Opus()) round-trips bytes instead of running a real encoder;
  • Format(id) for every well-known container av.Format* id (flv, ogg, ivf, annexb, matroska, webm, mp4) — the byte-faithful fake container, so goav.Write destinations and goav.FileInput sources work without real containers;
  • runconfig.WithClock(NewClock()), so realtime pacing advances a fake clock instead of sleeping.

opts are applied last and registration is last-wins, so extra options can both add adapters and override any of the defaults (including the clock).

func Video

func Video(width, height, frames int) goav.Input

Video returns a deterministic I420 video source emitting the given number of frames, then end of stream. Frame n is identifiable from its pixels: the luma plane is filled with byte(n) and both chroma planes with the neutral 128, so a test can tell which source frame any output pixel came from. Frames are stamped at 30fps (PTS n, duration 1, timebase 1/30). Each call gets a distinct generated name (and stream id).

Types

type Clock

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

Clock is a deterministic av.Clock for paced pipelines: Sleep never blocks — it records the requested wait and advances Now by it — so a realtime task runs instantly while a test asserts the exact sleep sequence the pacer asked for. Pair it with runconfig.WithClock (Runtime injects one by default). Advance moves the reading manually for code that polls Now without sleeping. Safe for concurrent use.

func NewClock

func NewClock() *Clock

NewClock returns a Clock reading zero with no recorded sleeps.

func (*Clock) Advance

func (c *Clock) Advance(d time.Duration)

Advance moves Now forward by d without recording a sleep.

func (*Clock) Now

func (c *Clock) Now() time.Duration

Now reports the elapsed time on the fake timeline: the sum of every positive Sleep plus every Advance so far.

func (*Clock) Sleep

func (c *Clock) Sleep(ctx context.Context, d time.Duration) error

Sleep implements av.Clock without blocking: it records d and advances Now by it when positive, returning ctx.Err() only when ctx is already done.

func (*Clock) Sleeps

func (c *Clock) Sleeps() []time.Duration

Sleeps returns every wait requested through Sleep, in order — the pacing trace a test asserts against.

type Collector

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

Collector is a recording destination: point a chain at Sink() and read back everything it received through the ordered, race-safe accessors. Collected frames and packets are references taken at delivery (Frame.Ref, Packet.Ref): their own headers over the delivered payload, which they keep alive, so a producer reusing its pool can never corrupt what a test asserts on; events are copies. Treat the returned values as read-only.

The zero Collector is not usable; construct with NewCollector.

Example

ExampleCollector mixes two deterministic inputs and reads the summed samples back — test code is pipeline code.

package main

import (
	"context"
	"fmt"

	"github.com/thesyncim/goav"
	"github.com/thesyncim/goav/goavtest"
)

func main() {
	ctx := context.Background()
	out := goavtest.NewCollector()
	task, err := goavtest.Runtime().Build(ctx, goav.Mix(
		goavtest.Audio(48000, 1, []int16{100}, []int16{200}).Audio(),
		goavtest.Audio(48000, 1, []int16{50}, []int16{-50}).Audio(),
	).
		To(out.Sink()))
	if err != nil {
		fmt.Println(err)
		return
	}
	defer task.Close()
	if err := task.Run(ctx); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(out.S16())
}
Output:
[[150] [150]]

func NewCollector

func NewCollector() *Collector

NewCollector returns a ready Collector with a distinct generated sink name, so several collectors can terminate different branches of one job.

func (*Collector) Events

func (c *Collector) Events() []av.Event

Events returns the collected events in delivery order.

func (*Collector) Frames

func (c *Collector) Frames() []*av.Frame

Frames returns the collected frames in delivery order.

func (*Collector) Packets

func (c *Collector) Packets() []*av.Packet

Packets returns the collected packets in delivery order.

func (*Collector) S16

func (c *Collector) S16() [][]int16

S16 returns the interleaved samples of every collected S16 audio frame, in delivery order — the one accessor almost every audio assertion wants. Frames that are not S16 audio are skipped.

func (*Collector) Sink

func (c *Collector) Sink() goav.Destination

Sink returns the Collector's destination. It is a stable handle — every call returns the same value — so branches can share it like any other goav.Destination.

func (*Collector) Wait

func (c *Collector) Wait(ctx context.Context, cond func(*Collector) bool) error

Wait polls until cond reports true or ctx ends — the wait-until-observed pattern for live pipelines, where a control lands asynchronously and the test waits for its effect to reach the collector:

err := out.Wait(ctx, func(c *goavtest.Collector) bool {
    return len(c.Frames()) >= 3
})

It returns nil once cond holds and ctx.Err() when the context ends first.

func (*Collector) WaitEvents

func (c *Collector) WaitEvents(ctx context.Context, n int) ([]av.Event, error)

WaitEvents blocks until at least n events have reached the collector, then returns the collected event copies.

func (*Collector) WaitFrames

func (c *Collector) WaitFrames(ctx context.Context, n int) ([]*av.Frame, error)

WaitFrames blocks until at least n frames have reached the collector, then returns the collected frames. It is the common case wrapper around Wait for live or control-driven tests.

Example

ExampleCollector_WaitFrames shows the common count-based wait helper used by live and control-driven pipeline tests.

package main

import (
	"context"
	"fmt"

	"github.com/thesyncim/goav/goavtest"
)

func main() {
	ctx := context.Background()
	out := goavtest.NewCollector()
	err := goavtest.Runtime().Run(ctx, goavtest.Audio(48000, 1, []int16{1}, []int16{2}).
		Audio().
		To(out.Sink()))
	if err != nil {
		fmt.Println(err)
		return
	}
	frames, err := out.WaitFrames(ctx, 2)
	fmt.Println(len(frames), err)
}
Output:
2 <nil>

func (*Collector) WaitPackets

func (c *Collector) WaitPackets(ctx context.Context, n int) ([]*av.Packet, error)

WaitPackets blocks until at least n packets have reached the collector, then returns the collected packets.

type TestSource

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

TestSource is a provider-backed, controllable source fixture for integration tests. It opens through goav.Input, emits a deterministic script of frames, packets, and events, records every source-control event it receives, and can run once or loop as a live source.

func NewTestSource

func NewTestSource(name string, spec shape.Spec, options ...TestSourceOption) *TestSource

NewTestSource creates a reusable source fixture. If spec leaves Domain empty it defaults to frame-domain media; if spec leaves StreamID empty it uses name.

func (*TestSource) Close

func (s *TestSource) Close() error

Close stops a live TestSource.

func (*TestSource) Control

func (s *TestSource) Control(_ context.Context, msg *pipeline.Message) error

Control records a source-control event. It validates that the message is an event message and rejects malformed source time controls instead of silently accepting them.

func (*TestSource) Controls

func (s *TestSource) Controls() []av.Event

Controls returns every control event recorded so far.

func (*TestSource) Detail

func (s *TestSource) Detail() string

Detail returns the source node detail for Describe output.

func (*TestSource) Input

func (s *TestSource) Input() goav.Input

Input adapts the source fixture into a goav recipe input. Apply recipe input options with the returned value's With method.

func (*TestSource) Name

func (s *TestSource) Name() string

Name returns the source node name.

func (*TestSource) OpenSource

func (s *TestSource) OpenSource(context.Context) (pipeline.Source, []av.Stream, error)

OpenSource opens the fixture as a running pipeline source.

func (*TestSource) SourceShape

func (s *TestSource) SourceShape() shape.Spec

SourceShape declares the media shape the fixture produces.

func (*TestSource) Start

func (s *TestSource) Start(ctx context.Context, emitter pipeline.Emitter) error

Start emits the configured script once, or repeats it while live mode is set.

func (*TestSource) String

func (s *TestSource) String() string

String returns a compact diagnostic name for the source fixture.

func (*TestSource) WaitControl

func (s *TestSource) WaitControl(ctx context.Context, typ av.EventType) (av.Event, error)

WaitControl blocks until a control of the requested type arrives. An empty type matches the next control of any type.

type TestSourceMessage

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

TestSourceMessage is one scripted emission for TestSource. Build values with TestSourceFrame, TestSourcePacket, or TestSourceEvent so caller-owned media is cloned before the source starts.

func TestSourceEvent

func TestSourceEvent(event av.Event) TestSourceMessage

TestSourceEvent builds a scripted event emission.

func TestSourceFrame

func TestSourceFrame(frame *av.Frame) TestSourceMessage

TestSourceFrame builds a scripted frame emission.

func TestSourcePacket

func TestSourcePacket(packet *av.Packet) TestSourceMessage

TestSourcePacket builds a scripted packet emission.

type TestSourceOption

type TestSourceOption func(*TestSource)

TestSourceOption configures a TestSource.

func TestSourceAppend

func TestSourceAppend(messages ...TestSourceMessage) TestSourceOption

TestSourceAppend appends mixed frame, packet, and event emissions to the current script. It composes with TestSourceScript, TestSourceFrames, TestSourcePackets, and TestSourceEvents in option order.

func TestSourceDetail

func TestSourceDetail(detail string) TestSourceOption

TestSourceDetail sets the Describe detail returned by the source node.

func TestSourceEvents

func TestSourceEvents(events ...av.Event) TestSourceOption

TestSourceEvents sets the event script emitted by the source.

func TestSourceFrames

func TestSourceFrames(frames ...*av.Frame) TestSourceOption

TestSourceFrames sets the frame script emitted by the source.

func TestSourceLive

func TestSourceLive() TestSourceOption

TestSourceLive makes the source repeat its script until the task stops.

func TestSourcePackets

func TestSourcePackets(packets ...*av.Packet) TestSourceOption

TestSourcePackets sets the packet script emitted by the source.

func TestSourceScript

func TestSourceScript(messages ...TestSourceMessage) TestSourceOption

TestSourceScript replaces the source script with a mixed sequence of frames, packets, and events. Each message is cloned when the option is applied, and Start clones again on delivery, so tests can mutate inputs and collected outputs without corrupting future runs.

Example

ExampleTestSourceScript shows a provider-shaped fixture with a mixed script: frame data plus an in-band event, both delivered through the source seam.

package main

import (
	"context"
	"fmt"

	"github.com/thesyncim/goav/av"
	"github.com/thesyncim/goav/goavtest"
	"github.com/thesyncim/goav/pipeline"
	"github.com/thesyncim/goav/shape"
)

func main() {
	ctx := context.Background()
	frame := &av.Frame{
		Type: av.MediaAudio,
		Audio: &av.AudioFrame{
			SampleRate:   8000,
			Channels:     1,
			SampleFormat: av.SampleFormatS16,
			Samples:      1,
		},
		Planes: []av.Plane{{
			Buffer: av.Buffer{Bytes: []byte{7, 0}},
		}},
	}
	source := goavtest.NewTestSource("fixture",
		shape.Frame(av.MediaAudio, shape.Audio(8000, 1, av.SampleFormatS16), shape.Codec(av.CodecPCM)),
		goavtest.TestSourceScript(
			goavtest.TestSourceFrame(frame),
			goavtest.TestSourceEvent(av.Event{Type: av.EventStats, Reason: "ready"}),
		),
	)
	opened, _, err := source.OpenSource(ctx)
	if err != nil {
		fmt.Println(err)
		return
	}
	emitter := &exampleScriptEmitter{}
	err = opened.Start(ctx, emitter)
	fmt.Println("err:", err)
	fmt.Println("frames:", emitter.frames)
	fmt.Println("events:", emitter.events, emitter.firstReason)
}

type exampleScriptEmitter struct {
	frames      int
	events      int
	firstReason string
}

func (e *exampleScriptEmitter) Emit(_ context.Context, msg *pipeline.Message) error {
	if msg.Frame != nil {
		e.frames++
	}
	if msg.Event != nil {
		e.events++
		if e.firstReason == "" {
			e.firstReason = msg.Event.Reason
		}
	}
	return nil
}
Output:
err: <nil>
frames: 1
events: 2 ready

Directories

Path Synopsis
expect module

Jump to

Keyboard shortcuts

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