goav

package module
v0.1.0-alpha.4 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: Apache-2.0 Imports: 38 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.

README

goav

Media pipelines in pure Go. Decode, transform, encode, and mux inside your service:
the core needs no cgo, no FFmpeg, and no system libraries.

CI Go Reference

You describe media work as plain Go values, and goav plans it, builds the graph, and runs it. The codecs and containers are pure Go (VP8, VP9, AV1, Opus; WebM, Matroska, MP4), so your service still ships as one static binary.

go get github.com/thesyncim/goav@latest   # Go 1.27+
GOEXPERIMENT=simd go build ./...         # always: enables the SIMD codec paths

Build, test, and run with GOEXPERIMENT=simd. It switches the codecs onto Go 1.27's portable SIMD paths; without it they fall back to scalar code. On one machine (Apple M4 Max, 128x96 test clips) that cut codec benchmark time by roughly half; treat it as a direction, not a guarantee (measurements and scope).

Quick start

package main

import (
	"context"
	"log"
	"os"

	"github.com/thesyncim/goav"
	"github.com/thesyncim/goav/bundle"
	"github.com/thesyncim/goav/codec"
)

// Scale a WebM to 720p and re-encode it as VP9.
func main() {
	src, err := os.Open("in.webm")
	if err != nil {
		log.Fatal(err)
	}
	defer src.Close()
	dst, err := os.Create("out.webm")
	if err != nil {
		log.Fatal(err)
	}
	video := goav.Read("in.webm", src).Video().
		Decode().
		Resize(1280, 720).
		Encode(codec.VP9(codec.Bitrate(2_000_000)))
	if err := bundle.Run(context.Background(), video.To(goav.Write("out.webm", dst))); err != nil {
		log.Fatal(err)
	}
}

goav.Read takes any io.Reader and goav.Write any io.Writer; bundle.Run closes the writer when the run ends.

No WebM handy? Make a test clip with the CLI.
GOEXPERIMENT=simd go run github.com/thesyncim/goav/cmd/goav@latest run \
  'testsrc video size=1920x1080 duration=2s ! encode vp9 ! file in.webm
   testsrc audio duration=2s ! encode opus ! file in.webm'

Fan out by reuse

Every operation returns a new goav.Stream, so a stream you use twice forks, and the work before the fork runs once. Here one decode feeds two renditions, and one Opus encode of the input's audio track is muxed into both files:

in := goav.Read("in.webm", src)
video := in.Video().Decode()
audio := in.Audio().Decode().Encode(codec.Opus())
hd, sd := goav.Write("hd.webm", hdFile), goav.Write("sd.webm", sdFile)

err := bundle.Run(ctx,
    video.Resize(1280, 720).Encode(codec.VP9()).As("hd").To(hd),
    video.Resize(640, 360).Encode(codec.VP9()).As("sd").To(sd),
    audio.To(hd, sd),
)

stream.To(...) makes an Output. bundle.Run runs Outputs together with the bundled codecs and containers; a runtime of your own runs them the same way: rt.Run(ctx, outputs...).

The same recipe as text, for a command line, a config file, or a control socket. It builds the identical graph (launch, CLI):

GOEXPERIMENT=simd go install github.com/thesyncim/goav/cmd/goav@latest
goav run 'v := file in.webm ! video ! decode
          v ! resize 1280x720 ! encode vp9 ! as hd ! file hd.webm
          v ! resize 640x360 ! encode vp9 ! as sd ! file sd.webm
          file in.webm ! audio ! decode ! encode opus ! file hd.webm, file sd.webm'

See the plan first

A recipe is data until it runs. bundle.Describe(outputs...) returns the exact graph a run would build, without opening anything, and graphrender.RenderURI(spec, "goav:graph") prints it. The quick start's nodes:

pipeline goav
  source in.webm [demux, protocol=file]
  stage select-video [select, type=video]
  stage decode-video [packets -> frames, type=video]
  stage resize-video [resize, 1280x720, exact]
  stage encode-video [frames -> packets, codec=vp9, backend=govpx (go)]
  stage out.webm [mux, protocol=file]

Errors name the fix

A mistake comes back before anything opens, as a *goav.BuildError with a stable code and the fix. Leave out the encoder and you get:

goav: cannot build job for video: decoded frames cannot be written to a muxed output without an encoder
Suggestions:
  - call .Encode(codec.VP8(...)), .Encode(codec.VP9(...)), or .Encode(codec.AV1(...)) before .To(goav.Write(...))
  - send decoded frames to goav.Sink(...)
  - leave out .Decode() to copy the packets: input.Video().To(output)

See Errors for matching on codes; graphrender also renders DOT and Mermaid.

What's in the box

Decode / demux Encode / mux
Video VP8, VP9, AV1, H.264 (-tags goav_goh264) VP8, VP9, AV1
Audio Opus Opus (in WebM, Matroska, or MP4)
Containers Matroska, WebM, IVF, MP4 Matroska, WebM, MP4 (progressive or fragmented), IVF, Annex B (H.264)

Plus Resize and Resample. bundle registers all of these; goav.New(...) builds a runtime with only the adapters you choose, and there is no global registry. AAC comes from libcodec (AudioToolbox, macOS) or the opt-in gplcodec (pure Go, arm64 only, GPL). Everything bundle links is permissive, except LGPL H.264 under its tag; see licenses.

Recipes

Need Shape
Remux without decoding in.To(goav.Write("out.mkv", w))
Audio and video in one file pass in.Video()…To(out) and in.Audio()…To(out) to one Run
Frames into your code in.Video().Decode().To(goav.Sink(component.SinkFunc("frames", fn)))
Mix, composite, switch goav.Mix(a, b), goav.Composite(cam, goav.At(screen.Resize(480, 270), 1420, 790)), goav.Select(a, b)
Package for HLS goav.Custom(hls.New("live.m3u8", hls.Dir(dir), hls.Window(6))); hls.NewLadder for renditions, hls.Parts with an hls.Server for LL-HLS, or goav run --serve :8080 '... ! hls live.m3u8 parts=250ms'
Change a running task task.Attach(ctx, task.Tap("live").Encode(codec.VP8()).To(preview))
Test a pipeline goavtest: deterministic sources, a recording sink, a fake clock

RTP and WebRTC, in and out, live in their own modules (RTP & WebRTC), and your own sources, codecs, and sinks plug in through small interfaces (Extension cookbook). More in Use cases, Operations, and examples/, including a browser WebRTC ladder and a native Gio control room.

Built for live services

  • One clock per task. Pacing, playout, pause and resume, seek, and rate share one timeline. Each fork can backpressure or drop on its own, and every drop is counted. See Flow control.
  • Change it while it runs. Attach and detach outputs, switch inputs, and drive it all over a control socket (Control plane).
  • Fast without codec assembly or unsafe. The root module uses no unsafe and no assembly; graph, codec, and filter stages allocate nothing per message, and GOEXPERIMENT=simd enables Go 1.27 SIMD codec paths. See Performance.

Modules

Module Adds
github.com/thesyncim/goav recipes, planner, runtime; bundled adapters in bundle
goav/rtpav RTP in and out: jitter buffer, (de)packetizers, RTCP feedback (Pion)
goav/webrtcav WebRTC tracks in and out, WHEP and WHIP (Pion)
goav/playoutav scheduled packet, frame, and event playout
goav/player a playback window, synced to the speaker: play in programs, goav play FILE
goav/cameraav cgo-free camera capture with bounded zero-allocation frame delivery
goav/libcodec codecs in shared libraries and OS frameworks, no cgo: VideoToolbox, AudioToolbox, OpenH264
goav/gplcodec opt-in copyleft codecs: gplcodec.AAC(), a pure-Go AAC-LC decoder (GPL; your binary becomes GPL)
goav/cmd/goav the goav CLI: run, describe, explain, play, cameras, ctl (CLI)
goav/goavtest/expect go-cmp assertions for pipeline tests

The core module never pulls in Pion.

Status

Pre-v1: breaking changes can land until the first tag (see Roadmap). Not related to github.com/giorgisio/goav, a cgo binding to FFmpeg.


Docs · Architecture · Adapter authoring · RTP & WebRTC · Changelog · Contributing · Security

Documentation

Overview

Package goav is a pure-Go realtime media grammar: describe media work as values, then run it with an explicit runtime.

The grammar is small. An input's Video, Audio, or Stream method selects a Stream; operations are methods that return a new Stream (.Decode(), .Resize(), .Encode(codec.VP9(...))), so a Stream used twice fans out and the work before the fork runs once. Mix, Composite, Select, and Join converge Streams into one, Tap names attach points, and .To(destinations...) routes a Stream to destinations built by Write, ToURI, WriteFunc, Custom, or Sink, making an Output. A runtime runs Outputs together: rt.Run(ctx, outputs...), or rt.Build for a Task with events, snapshots, runtime Attach/Detach, and live controls.

New(opts...) builds a bare runtime and returns option/configuration errors. Import github.com/thesyncim/goav/bundle when the application wants the bundled pure-Go adapters. Build errors are structured: every refusal is a *BuildError carrying an errcode.Family, detailed errcode.Code, the failing operation, and concrete fixes.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrBackpressure is returned by source.Push/component.Emit when a
	// downstream buffer is full and the message was not delivered. On a Blocking
	// branch the producer is paced instead; on a dropping branch the message is
	// shed and the producer may keep going. A source that can pace itself should
	// slow down on this.
	ErrBackpressure = pipeline.ErrBackpressure
	// ErrClosed is returned when emitting into a graph or stage that has shut
	// down (the task stopped, or its context was cancelled). A source should
	// treat it as a signal to return cleanly.
	ErrClosed = pipeline.ErrClosed
)

Runtime flow-control sentinels, surfaced on the front door so source.Func, component.PacketFunc, component.FrameFunc, or component.SinkFunc can react to backpressure and shutdown with errors.Is — without importing the pipeline package. They share identity with the values the runtime returns, so errors.Is matches either name.

Functions

This section is empty.

Types

type Attachment

type Attachment interface {
	// ID is the task-unique attachment identifier; Name is the branch name,
	// taken from each Output's .As or else its first destination (a name may
	// be reused across attachments).
	ID() string
	Name() string
	// Spec returns the branch's private graph patch as a structured spec, and
	// Stats its counters, over the same node set; once the branch detaches
	// both report its final nodes. Snapshot returns the branch-owned
	// point-in-time view (lifecycle state, spec, stats, published taps).
	Spec() pipeline.Spec
	Stats() pipeline.GraphStats
	Snapshot() BranchSnapshot
	// Pause stops delivery to this branch without touching the source or its
	// siblings; messages are skipped while paused. Resume restores delivery.
	Pause(context.Context) error
	Resume(context.Context) error
	// Rebranch replaces this branch with new ones in place: the replacements are
	// attached and start receiving before this branch is detached (no gap), so a
	// live subscriber can be switched (e.g. to a different simulcast layer)
	// without rebuilding the task. On attach failure this branch is left intact
	// by default. Pass replacement Outputs (built from task.Tap or task.Track,
	// like Attach) plus lifecycle policies:
	// SwitchAt(NextFrame()/NextKeyframe()) delays
	// the switch to that stream boundary — the replacements shed media until the
	// boundary and this branch detaches at it — and
	// DrainBranch/AbortBranch select whether this
	// branch's destinations commit or abort on detach.
	// Without options the switch is immediate, exactly like Detach after Attach.
	Rebranch(context.Context, ...RebranchArg) (Attachment, error)
	// Close detaches this branch and any dependent branches anchored on its
	// taps; equivalent to task.Detach.
	Close(context.Context) error
}

Attachment is a live runtime branch attached to a task.

Example (Rebranch)

ExampleAttachment_rebranch rotates a live recording without a delivery gap: the replacement attaches and starts receiving before the old branch detaches, gated to the next keyframe so the new file starts at a decodable sync point.

ctx := context.Background()
var part1, part2 bytes.Buffer

task, err := mustRuntime().Build(ctx, goav.Read("input.ivf", bytes.NewReader(tinyIVF())).
	Video().
	Tap("video.encoded").
	To(goav.Write("live.ivf", io.Discard)))
if err != nil {
	fmt.Println(err)
	return
}
defer task.Close()

rec, err := task.Attach(ctx,
	task.Tap("video.encoded").
		As("rec").
		To(goav.Write("part-001.ivf", &part1)),
)
if err != nil {
	fmt.Println(err)
	return
}

go func() { _ = task.Run(ctx) }()

// Rotate to the next file at a clean decode point; the replaced branch
// drains so part-001 commits complete.
if _, err := rec.Rebranch(ctx,
	task.Tap("video.encoded").As("rec").To(goav.Write("part-002.ivf", &part2)),
	goav.SwitchAt(goav.NextKeyframe()),
	goav.DrainBranch(),
); err != nil {
	fmt.Println(err)
}

type BranchFailureError

type BranchFailureError = pipeline.FaultError

BranchFailureError identifies an isolated handler error and unwraps its cause.

type BranchFailurePolicy

type BranchFailurePolicy string

BranchFailurePolicy determines the scope of a returned handler error.

const (
	// FailTask is the default: the first handler error stops the task.
	FailTask BranchFailurePolicy = "fail_task"
	// IsolateBranch retires this Output's exclusive suffix on its first
	// handler error. Shared upstream errors still fail the task. Panics and
	// stalls are outside this policy; blocking queues still pace producers.
	IsolateBranch BranchFailurePolicy = "isolate_branch"
)

type BranchSnapshot

type BranchSnapshot struct {
	ID             string                `json:"id"`
	Name           string                `json:"name"`
	State          BranchState           `json:"state"`
	FailurePolicy  BranchFailurePolicy   `json:"failurePolicy,omitempty"`
	Err            error                 `json:"-"`
	Error          string                `json:"error,omitempty"`
	PendingCleanup int                   `json:"pendingCleanup,omitempty"`
	Retired        bool                  `json:"retired,omitempty"`
	AnchorTaps     []string              `json:"anchorTaps,omitempty"`
	AnchorNodes    []string              `json:"anchorNodes,omitempty"`
	Nodes          []pipeline.NodeRef    `json:"nodes,omitempty"`
	Taps           []TapSnapshot         `json:"taps,omitempty"`
	Destinations   []DestinationSnapshot `json:"destinations,omitempty"`
	Spec           pipeline.Spec         `json:"spec"`
	Stats          pipeline.GraphStats   `json:"stats"`
}

BranchSnapshot is an immutable point-in-time view of one runtime branch attached to a running task, returned by Attachment.Snapshot and listed in TaskSnapshot.Branches.

type BranchState

type BranchState string

BranchState is the lifecycle state a BranchSnapshot reports.

const (
	// BranchAttached reports a runtime branch that is attached to its task.
	BranchAttached BranchState = "attached"
	// BranchDetached reports a runtime branch that was detached from its task.
	BranchDetached BranchState = "detached"
	// BranchFailed retains an isolated processing failure after retirement.
	BranchFailed BranchState = "failed"
)

type BuildError

type BuildError struct {
	Phase     string
	Family    errcode.Family
	Code      errcode.Code
	Operation string
	Node      string
	Reason    string
	// contains filtered or unexported fields
}

BuildError is the one structured refusal goav raises from build, validation, attach, and explain paths. Family identifies the stable application branch key, Code identifies the detailed diagnostic leaf (see the errcode package), Phase says when in the lifecycle it happened, Operation/Node say where, Reason says why, Detail exposes typed machine-readable facts, and DetailLines and FixLines expose rendered details and repair actions. Match build-shape refusals through Family and Code; Unwrap preserves low-level causes for errors.Is where a pipeline or runtime sentinel is still part of that lower-level contract.

Example

ExampleBuildError matches a structured refusal: every failed build carries a stable family, a typed detailed code, the failing operation, and concrete fixes, and wraps a sentinel for errors.Is.

// Decoded frames cannot feed a muxed file without an encoder: the build
// refuses before any resource opens.
_, err := mustRuntime().Build(context.Background(), goav.Read("input.ivf", bytes.NewReader(tinyIVF())).
	Video().
	Decode().
	To(goav.Write("frames.ivf", io.Discard)))

if buildErr, ok := errors.AsType[*goav.BuildError](err); ok {
	fmt.Println("code:", buildErr.Code)
	fmt.Println("family match:", buildErr.Family == errcode.FamilyEncode)
	fmt.Println("has fixes:", len(buildErr.FixLines()) > 0)
}
Output:
code: encode_missing
family match: true
has fixes: true

func (*BuildError) Detail

func (e *BuildError) Detail[T any](key string) (T, bool)

Detail returns the detail named key as a T, reporting false when the error carries no such detail or it is not a T:

format, ok := buildErr.Detail[av.FormatID]("format")

func (*BuildError) DetailLines

func (e *BuildError) DetailLines() []string

DetailLines returns the human-readable detail lines rendered in Error.

func (*BuildError) Error

func (e *BuildError) Error() string

Error renders the one goav error shape: "goav: cannot <operation> for <node>: <reason>" followed by Details and Suggestions lines.

func (*BuildError) FixLines

func (e *BuildError) FixLines() []string

FixLines returns the human-readable fix lines rendered in Error.

func (*BuildError) MarshalJSON

func (e *BuildError) MarshalJSON() ([]byte, error)

MarshalJSON renders the BuildError as a stable machine-readable document: phase, family, code, operation, node, reason, typed key/value details, and concrete fixes. It is the JSON contract consumed by tooling and pinned by the golden error tests; Detail values keep their real type.

func (*BuildError) Unwrap

func (e *BuildError) Unwrap() error

Unwrap exposes the underlying cause to errors.Is.

type Destination

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

Destination is an opaque handle for a file, URI, writer, or media sink. The handle is the output's identity: pass the same value to .To(...) from several streams or branches and they feed one mux or sink (With keeps that identity); separately constructed handles are separate outputs. The zero value is intentionally not a valid destination; construct handles with Write, ToURI, Sink, WriteFunc, or Custom.

func Custom

func Custom(dest provider.Destination, opts ...DestinationOption) Destination

Custom wraps a reusable provider.Destination as a destination value: the provider owns naming, contract, and opening, while the returned Destination stays the stable routing handle branches share. Override its name with goav.Name(...).

func Sink

func Sink(sink pipeline.Sink, opts ...DestinationOption) Destination

Sink creates a media-message destination for decoded frames or packets. Like every destination constructor it accepts options; Name overrides the label outputs group and dedupe by (byte-stream options such as Format and MIME state nothing about a sink).

func ToURI

func ToURI(uri string, opts ...DestinationOption) Destination

ToURI declares a destination written to a URL — goav.ToURI("file:///srv/out.mp4") — resolved like FromURI through the runtime's schemes, which open the bytes goav muxes once the format and streams are known. The container comes from the URL's extension, Format, MIME, or the scheme's contract.

func Write

func Write(name string, writer io.Writer, opts ...DestinationOption) Destination

Write creates a writer-backed destination from an already-open writer. When the writer also implements io.Closer it is closed exactly once when the destination finalizes (run end, drained detach, or failure); a plain writer is left open for the caller.

func WriteFunc

func WriteFunc(name string, open provider.OpenFunc, opts ...DestinationOption) Destination

WriteFunc creates a byte destination opened on demand: the callback runs after goav has selected the format and streams, so the writer sees the final destination metadata (provider.Info). The writer closes exactly once. When the returned writer also implements provider.TransactionalWriter, Commit runs after a successful run or drained detach and Abort runs on failure — the seam for object-store uploads with an explicit commit boundary.

func (Destination) With

func (d Destination) With(opts ...DestinationOption) Destination

With returns a copy of the destination with the options applied — the same option vocabulary the constructors take, for layering config onto an already-constructed value. The copy keeps the original's routing identity.

type DestinationOption

type DestinationOption interface {
	// contains filtered or unexported methods
}

DestinationOption configures a destination value (Write, ToURI, WriteFunc, Custom, Sink, or Destination.With). Build one with Format, which pins the container, or with Name, MIME, or Metadata, the direction-agnostic MediaOption constructors. It is sealed: only goav option constructors implement it.

func Format

func Format(format av.FormatID) DestinationOption

Format pins the destination's container format explicitly instead of probing it from the name or MIME type. It is destination-only: input containers are always probed from the name, MIME type, or leading bytes.

type DestinationSnapshot

type DestinationSnapshot struct {
	// ID identifies the destination within its task or attachment.
	ID        string             `json:"id,omitempty"`
	Name      string             `json:"name"`
	Operation plan.OperationKind `json:"operation,omitempty"`
	Component string             `json:"component,omitempty"`
	Format    av.FormatID        `json:"format,omitempty"`
	Branches  []string           `json:"branches,omitempty"`
	State     DestinationState   `json:"state"`
	Err       error              `json:"-"`
	Error     string             `json:"error,omitempty"`
	// Open mirrors State == DestinationOpen.
	Open bool `json:"open"`
}

DestinationSnapshot is an immutable point-in-time view of a planned task or branch destination.

type DestinationState

type DestinationState string

DestinationState is the lifecycle state a DestinationSnapshot reports. It is also the contract external destinations are reported through: a custom provider.TransactionalWriter surfaces as DestinationOpen while accepting media, DestinationCommitted after actual successful finalization (Commit), DestinationAborted after successful abandonment (Abort), and DestinationClosed when closed without a run outcome.

const (
	// DestinationOpen reports a destination that is open and accepting media.
	DestinationOpen DestinationState = "open"
	// DestinationFinalizing reports an output awaiting its actual close/commit.
	DestinationFinalizing DestinationState = "finalizing"
	// DestinationFailed reports a failed close, commit, or abort.
	DestinationFailed DestinationState = "failed"
	// DestinationCommitted reports a destination finalized by a run that
	// completed without error.
	DestinationCommitted DestinationState = "committed"
	// DestinationAborted reports a destination abandoned by a run that ended
	// with an error.
	DestinationAborted DestinationState = "aborted"
	// DestinationClosed reports a destination closed without a run outcome,
	// such as a detached branch destination or a task closed before running.
	DestinationClosed DestinationState = "closed"
)

type DetachOption

type DetachOption interface {
	RebranchArg
	// contains filtered or unexported methods
}

DetachOption selects how a removed runtime branch's destinations are finalized: DrainBranch commits them, AbortBranch aborts them, and with neither they close without a recorded outcome. Task.Detach takes it for the detached branch and Attachment.Rebranch for the replaced one. It is sealed: only goav option constructors implement it.

func AbortBranch

func AbortBranch() DetachOption

AbortBranch finalizes the removed branch as abandoned: its destinations are aborted when it detaches.

func DrainBranch

func DrainBranch() DetachOption

DrainBranch finalizes the removed branch as drained: its destinations are committed when it detaches.

type EventFilter

type EventFilter func(av.Event) bool

EventFilter reports whether a watcher wants an event. Filters passed to Task.Watch AND together: an event is delivered when every filter matches. A watch with zero filters receives every event. Any predicate works; WatchTypes and WatchStream cover the common cases.

func WatchStream

func WatchStream(id av.StreamID) EventFilter

WatchStream matches events published for the given stream.

func WatchTypes

func WatchTypes(types ...av.EventType) EventFilter

WatchTypes matches events whose Type is one of types.

type Input

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

Input is one declared recipe input: a file-like reader, a URL, a custom source, or a provider input, plus the optional name and MIME facts the planner uses before opening it. Construct one with Read, FromURI, Source, or From; configure it with options (Name, MIME, Metadata, Reconnect) and decorate the opened source with Wrap. The zero value is intentionally not a valid input.

func From

func From(src provider.Input, opts ...InputOption) Input

From adapts a provider input into a recipe input: a provider.Source, whose media the provider produces, or a provider.ByteSource, whose container bytes the runtime probes (from goav.Name, goav.MIME, or SourceShape().Format) and demuxes. The declared shape seeds the input's codec intent and realtime policy, so the recipe planner can select streams and pick decoders before the input is opened:

in := goav.From(rtpav.Receive(reader, rtpav.WithCodec(codec.Opus())))
err := rt.Run(ctx, in.Audio().To(out))

func FromURI

func FromURI(uri string, opts ...InputOption) Input

FromURI declares an input read from a URL: goav.FromURI("https://cdn.example/a.mp4"). The runtime resolves it while planning through the scheme registered for the URL's scheme (runconfig.WithScheme; bundle registers file, http, and https), and a bare path is a file. The scheme decides what the input is — container bytes the runtime probes and demuxes, as for an http resource, or media a transport produces, as for whep — and whether it is live. Describe, Explain, errors, events, and snapshots show the URL redacted: no userinfo, and secret query values (token, key, password, signature) replaced; only the scheme sees it verbatim.

func Read

func Read(name string, reader io.Reader, opts ...InputOption) Input

Read declares a file-like input read from reader. Its container is detected from its first bytes when it opens; name (its extension) is the hint used when the bytes match no format, and names the input.

func Source

func Source(name string, spec shape.Spec, fn sourcepkg.Func, opts ...InputOption) Input

Source declares a custom input the application pushes media into: spec states the media facts the planner needs before the source opens (shape.Packet, shape.Frame, or shape.Event plus format facts), and fn runs on the task pushing through source.Push. Custom sources participate in streams, branches, taps, explain, and runtime attach exactly like built-in inputs.

Example (PushAccounting)
package main

import (
	"context"
	"encoding/binary"
	"fmt"

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

func exampleFrame(sample int16) av.Frame {
	payload := make([]byte, 2)
	binary.LittleEndian.PutUint16(payload, uint16(sample))
	return av.Frame{
		Type:  av.MediaAudio,
		Audio: &av.AudioFrame{SampleRate: 48000, Channels: 1, SampleFormat: av.SampleFormatS16, Samples: 1},
		Planes: []av.Plane{{
			Buffer: av.Buffer{Bytes: payload},
		}},
	}
}

func main() {
	ctx := context.Background()
	accepted, dropped := 0, 0
	input := goav.Source("mic",
		shape.Frame(av.MediaAudio, shape.Audio(48000, 1, av.SampleFormatS16)),
		func(_ context.Context, push source.Push) error {
			for _, sample := range []int16{1, 2} {
				frame := exampleFrame(sample)
				result, err := push.Frame(&frame)
				if err != nil {
					return err
				}
				if result.Accepted {
					accepted++
				}
				if result.Dropped {
					dropped++
				}
			}
			return push.EOS()
		})

	out := goavtest.NewCollector()
	err := goavtest.Runtime().Run(ctx, input.
		Audio().
		To(out.Sink()))

	fmt.Println("err:", err)
	fmt.Println("pushes:", accepted, "accepted,", dropped, "dropped")
	fmt.Println("frames:", out.S16())

}
Output:
err: <nil>
pushes: 2 accepted, 0 dropped
frames: [[1] [2]]

func (Input) Audio

func (s Input) Audio(options ...StreamOption) Stream

Audio selects the input's audio stream; with several, StreamID or StreamIndex narrows the choice.

func (Input) OnStream

func (s Input) OnStream(match sourcepkg.StreamMatch) Stream

OnStream is each stream the input discovers while it runs that match selects: Outputs built from it attach for every such stream, named per stream, and detach when the stream ends. The attach happens on the source's emit path, as GStreamer's pad-added does: the source's Emit of the av.EventStreamAdded announce returns once the branch exists, so the branch receives the stream from its first packet. A rule destination's Open therefore runs on the source's goroutine, bounded by the task's context; keep it fast or hand slow setup to a goroutine of its own.

func (Input) Stream

func (s Input) Stream(options ...StreamOption) Stream

Stream selects one stream of any media kind, narrowed by StreamID or StreamIndex when the input carries several.

func (Input) To

func (s Input) To(destinations ...Destination) Output

To copies every stream of the input, without decoding, into destinations.

func (Input) Video

func (s Input) Video(options ...StreamOption) Stream

Video selects the input's video stream; with several, StreamID or StreamIndex narrows the choice.

func (Input) With

func (s Input) With(opts ...InputOption) Input

With returns a copy of the input with the options applied — the same option vocabulary the constructors take, for layering config onto an already-constructed value (renaming a generated test input, say).

func (Input) Wrap

func (spec Input) Wrap(wrap func(pipeline.Source) pipeline.Source) Input

Wrap returns a copy of spec whose opened pipeline.Source is decorated by wrap. Wraps compose in declaration order (last added is outermost). Planning identity, probes, and Describe() node names remain pinned to the underlying source; optional capabilities (such as pipeline.ControllableSource) are visible only if the decorator delegates them.

type InputOption

type InputOption interface {
	// contains filtered or unexported methods
}

InputOption configures an input value (Read, FromURI, Source, From, or Input.With). Build one with Name, MIME, Metadata, or Reconnect. It is sealed: only goav option constructors implement it.

func Live

func Live() InputOption

Live marks an input live: it delivers on its own clock (a capture device on a pipe, an Icecast mount, an MPEG-TS stream over HTTP), so its run plans realtime, Explain reports it live, and Reconnect applies. Providers declare liveness with SourceShape().Realtime, and an http input that opens with no length and no ranges, or as an Icecast stream, is live without it; Live says so before anything opens.

func Reconnect

func Reconnect(attempts int, backoff time.Duration) InputOption

Reconnect makes a live input reopen when it fails: when its source stops with an error before the run's context ends, goav waits backoff (doubling for each consecutive failure, capped at 30s, with jitter) and opens the input again, up to attempts consecutive failures (0 retries until the run ends). A reconnect that delivers media resets the count. Each attempt, and the recovery, publish an av.EventReconnect on the task's Watch, and the input announces av.EventDiscontinuity downstream once it is back. It applies to live provider and URI inputs (a whep URL, a live transport, an http stream that opens live, or any input marked Live); a file or an application-pushed source refuses it.

type JoinArg

type JoinArg interface {
	// contains filtered or unexported methods
}

JoinArg is one argument of Mix or Composite: a Stream (an input of the join), a Stream placed At a position (Composite only), or a join option such as ByPTS. It is sealed: only goav values implement it.

func At

func At(s Stream, x, y int) JoinArg

At places a Composite input's top-left corner at (x, y) on the canvas.

func ByPTS

func ByPTS() JoinArg

ByPTS aligns a Mix or Composite's inputs by presentation time instead of arrival order: goav.Mix(a, b, goav.ByPTS()).

Example

ExampleByPTS aligns join arms by timestamp instead of arrival order: arm two starts one 20ms frame later, so the leading step plays arm one alone, the PTS-matched frames sum, and the trailing step plays arm two alone.

var mixed [][]int16
var pts []int64
out := goav.Sink(component.SinkFunc("out", func(_ context.Context, msg component.Message) error {
	if msg.Frame != nil {
		mixed = append(mixed, pcmSamples(msg.Frame))
		pts = append(pts, msg.Frame.PTS.Value)
	}
	return nil
}))

err := mustRuntime().Run(context.Background(), goav.Mix(
	pcmSourceAt("song-a", 48_000, 1, []int64{0, 20}, []int16{10, 10}, []int16{20, 20}).Audio(),
	pcmSourceAt("song-b", 48_000, 1, []int64{20, 40}, []int16{1, 1}, []int16{2, 2}).Audio(),
	goav.ByPTS(),
).
	To(out))

fmt.Println(err, mixed, pts)
Output:
<nil> [[10 10] [21 21] [2 2]] [0 20 40]

type MediaOption

type MediaOption interface {
	InputOption
	DestinationOption
}

MediaOption is a direction-agnostic option accepted by both input and destination constructors. Name, MIME, and Metadata state the same fact about either end of a recipe, so goav.Read(name, r, goav.MIME(...)) and goav.Write(name, w, goav.MIME(...)) share one vocabulary. It is sealed: only goav option constructors implement it.

func MIME

func MIME(mimeType string) MediaOption

MIME sets the value's MIME type, which drives format probing when the name carries no extension: input MIME selects the demuxer, destination MIME selects the output format and is reported to destination openers.

func Metadata

func Metadata(metadata av.Metadata) MediaOption

Metadata attaches caller metadata to the value: input metadata rides format.Input to the opening adapter, destination metadata reaches openers on provider.Info (an uploader can store it as object metadata).

func Name

func Name(name string) MediaOption

Name overrides the value's label. On an input it is the name its source node, errors, and Explain use; on a destination it is the label outputs group and dedupe by.

type Output

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

Output routes a Stream to destinations. A runtime runs Outputs together: streams written to one Destination value share its container.

func (Output) OnFailure

func (o Output) OnFailure(policy BranchFailurePolicy) Output

OnFailure selects the failure scope for this Output at Build or Attach. Isolation is refused for shared destinations, joins, or unsafe egress.

type RebranchArg

type RebranchArg interface {
	// contains filtered or unexported methods
}

RebranchArg is one argument to Attachment.Rebranch: a replacement Output built from task.Tap or task.Track, a switch boundary from SwitchAt, or a DetachOption for the replaced branch. It is sealed: only goav values implement it.

func SwitchAt

func SwitchAt(boundary SwitchBoundary) RebranchArg

SwitchAt delays the rebranch switch to the given stream boundary. Without SwitchAt, rebranch switches immediately.

type ResampleOption

type ResampleOption = func(*filter.ResampleConfig)

ResampleOption configures a Stream.Resample operation.

type ResizeOption

type ResizeOption = func(*filter.ResizeConfig)

ResizeOption configures a Stream.Resize operation (for example filter.Fit or filter.Fill).

type Runtime

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

Runtime is the composition root for applications embedding goav: it holds the codec, format, and filter registries, the buffer and pool settings, and the clock that tasks run with. Build it with New, or import github.com/thesyncim/goav/bundle for the bundled adapter set. Applications run Outputs on it with Run (one shot) or Build (a Task), and inspect them without opening anything with Describe and Explain. Its fields are unexported: construction and adapter registration go through runconfig options.

func New

func New(options ...runconfig.Option) (*Runtime, error)

New builds a bare runtime: per-runtime registries with no adapters beyond content sniffing, realtime pacing off (live inputs pace automatically; see runconfig.WithRealtime). Import github.com/thesyncim/goav/bundle for a runtime with the bundled adapters already registered. Runtime options live in github.com/thesyncim/goav/runconfig.

func (*Runtime) Build

func (r *Runtime) Build(ctx context.Context, outs ...Output) (Task, error)

Build builds the Outputs into one task without starting it.

func (*Runtime) Describe

func (r *Runtime) Describe(outs ...Output) (pipeline.Spec, error)

Describe returns the graph the Outputs build, without opening them.

func (*Runtime) Explain

func (r *Runtime) Explain(ctx context.Context, outs ...Output) (plan.Report, error)

Explain reports the typed plan the Outputs build, without opening them. On a refusal it returns both the structured BuildError and a partial report naming what is missing.

func (*Runtime) Probe

func (r *Runtime) Probe(ctx context.Context, request format.ProbeRequest) (format.ProbeResult, error)

Probe asks the runtime's registered probers which container format a request names, the same lookup inputs and destinations resolve through.

func (*Runtime) Run

func (r *Runtime) Run(ctx context.Context, outs ...Output) error

Run builds the Outputs into one task and runs it to completion. It returns the first build refusal or runtime error; destinations commit on success and abort on failure. Finalize failures surface here too: if both the run and close/finalization fail, Run returns errors.Join(runErr, closeErr).

Example

ExampleRuntime_Run is the direct stream: a custom source feeding decode, encode, and a typed destination — the front door of the recipe grammar.

package main

import (
	"context"
	"fmt"

	"github.com/thesyncim/goav"
	"github.com/thesyncim/goav/av"
	"github.com/thesyncim/goav/bundle"
	"github.com/thesyncim/goav/codec"
	"github.com/thesyncim/goav/component"
	"github.com/thesyncim/goav/shape"
	"github.com/thesyncim/goav/source"
)

// opusTestPacket returns a self-delimiting CELT packet the Opus decoder
// accepts, standing in for media a capture pipeline would produce.
func opusTestPacket() []byte {
	data := make([]byte, 50)
	data[0] = 0xf8
	for i := 1; i < len(data); i++ {
		data[i] = byte(i * 7)
	}
	return data
}

func main() {
	ctx := context.Background()

	// A custom source pushes encoded packets the application already owns.
	mic := goav.Source("mic",
		shape.Packet(av.MediaAudio, av.CodecOpus, shape.Audio(48_000, 1, av.SampleFormatS16)),
		func(_ context.Context, push source.Push) error {
			packet := av.Packet{StreamID: "mic", Payload: av.Buffer{Bytes: opusTestPacket()}}
			if _, err := push.Packet(&packet); err != nil {
				return err
			}
			return push.EOS()
		})

	// Decode to PCM, re-encode at 96 kbps, and count the packets at a sink:
	// the frame's own packet, then the flush that drains the encoder lookahead.
	encoded := 0
	err := bundle.MustNew().Run(ctx, mic.
		Audio().
		Decode().
		Encode(codec.Opus(codec.Bitrate(96_000))).
		To(goav.Sink(component.SinkFunc("count", func(_ context.Context, msg component.Message) error {
			if msg.Packet != nil {
				encoded++
			}
			return nil
		}))))

	fmt.Println(err, encoded)
}
Output:
<nil> 2
Example (MultipleInputs)

ExampleRuntime_Run_multipleInputs feeds two live inputs into one run: each stream comes from its own input, and one destination value muxes both encoded streams into one container.

camera := i420Source("camera", 16, 16, 100)
mic := pcmSource("mic", 48_000, 1, make([]int16, 960))
out := goav.Write("call.webm", io.Discard)

spec, err := mustRuntime().Describe(
	camera.Video().Encode(codec.VP8(codec.Bitrate(1_000_000))).To(out),
	mic.Audio().Encode(codec.Opus(codec.Bitrate(96_000))).To(out),
)
if err != nil {
	fmt.Println(err)
	return
}
streams := 0
for _, edge := range spec.Edges {
	if edge.To == "call.webm" {
		streams++
	}
}
fmt.Printf("%d encoded streams mux into call.webm\n", streams)
Output:
2 encoded streams mux into call.webm

type Stream

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

Stream is one media stream of a recipe: an input's selected stream, a join's output, or the result of an operation on another Stream. It is an immutable value: every method returns a new Stream and leaves its receiver unchanged, so a Stream used twice fans out and the work before the fork runs once.

v := in.Video().Decode()
hd := v.Resize(1280, 720).Encode(codec.VP9())
sd := v.Resize(640, 360).Encode(codec.VP9())
err := rt.Run(ctx, hd.To(hdOut), sd.To(sdOut))

A Stream does nothing until a runtime runs the Outputs built from it.

func Composite

func Composite(args ...JoinArg) Stream

Composite draws video streams onto one canvas, in order, each at its At position (the canvas origin for a bare Stream). Options such as ByPTS go among the streams.

Example

ExampleComposite paints two video arms onto one canvas at their At positions: a 4x4 camera at the origin and a second 4x4 camera 4 pixels right produce one 8x4 frame.

var canvasW, canvasH int
var leftLuma, rightLuma byte
preview := goav.Sink(component.SinkFunc("preview", func(_ context.Context, msg component.Message) error {
	if msg.Frame != nil && msg.Frame.Video != nil && len(msg.Frame.Planes) != 0 {
		canvasW = msg.Frame.Video.Width
		canvasH = msg.Frame.Video.Height
		luma := msg.Frame.Planes[0].Buffer.Bytes
		leftLuma = luma[0]
		rightLuma = luma[4]
	}
	return nil
}))

err := mustRuntime().Run(context.Background(), goav.Composite(
	goav.At(i420Source("cam", 4, 4, 100).Video(), 0, 0),
	goav.At(i420Source("screen", 4, 4, 200).Video(), 4, 0),
).
	To(preview))
if err != nil {
	fmt.Println(err)
	return
}

fmt.Printf("canvas %dx%d\n", canvasW, canvasH)
fmt.Println("left luma:", leftLuma, "right luma:", rightLuma)
Output:
canvas 8x4
left luma: 100 right luma: 200

func Join

func Join(name string, stage pipeline.Stage, streams ...Stream) Stream

Join converges streams into a custom stage whose Name equals name.

func Mix

func Mix(args ...JoinArg) Stream

Mix sums audio streams into one. Options such as ByPTS go among the streams.

Example

ExampleMix converges two audio sources into one stream: the dual of a fork. The summed output is a normal Stream that takes Encode, Tap, To, and forks like any other.

var mixed [][]int16
speakers := goav.Sink(component.SinkFunc("speakers", func(_ context.Context, msg component.Message) error {
	if msg.Frame != nil {
		mixed = append(mixed, pcmSamples(msg.Frame))
	}
	return nil
}))

err := mustRuntime().Run(context.Background(), goav.Mix(
	pcmSource("mic-1", 48_000, 1, []int16{100, 200}).Audio(),
	pcmSource("mic-2", 48_000, 1, []int16{50, -50}).Audio(),
).
	To(speakers))

fmt.Println(err, mixed)
Output:
<nil> [[150 150]]

func Select

func Select(streams ...Stream) Stream

Select forwards one of its streams at a time; control.SelectActive switches which.

Example

ExampleSelect forwards exactly one live arm and switches arms through the control plane — no node names, no rebuild.

ctx := context.Background()
preview := goav.Sink(component.SinkFunc("preview", func(context.Context, component.Message) error {
	return nil
}))

task, err := mustRuntime().Build(ctx, goav.Select(
	i420Source("cam-1", 16, 16, 100).Video(),
	i420Source("cam-2", 16, 16, 200).Video(),
).
	To(preview))
if err != nil {
	fmt.Println(err)
	return
}
defer task.Close()

go func() { _ = task.Run(ctx) }()

// The first arm is live by default; switch to the second mid-run.
if err := task.Control(ctx, control.SelectActive("cam-2")); err != nil {
	fmt.Println(err)
}

func (Stream) As

func (s Stream) As(name string) Stream

As names the stream from here on: a fork's name is its node prefix and the id of the stream it encodes, which live controls address (control.SetBitrate("hd", ...)).

func (Stream) Auto

func (s Stream) Auto(policies ...shape.Policy) Stream

Auto lets the planner insert the conversions the policies allow.

Example

ExampleStream_Auto opts the stream into the shape solver: the mic is 44.1kHz but Opus pins 48kHz, so under the explicit AllowResample policy the planner inserts the conversion as a real planned operation and Explain reports it.

package main

import (
	"context"
	"encoding/binary"
	"fmt"
	"io"

	"github.com/thesyncim/goav"
	"github.com/thesyncim/goav/av"
	"github.com/thesyncim/goav/bundle"
	"github.com/thesyncim/goav/codec"
	"github.com/thesyncim/goav/shape"
	"github.com/thesyncim/goav/source"
)

// pcmSource returns a custom frame-domain input that pushes one S16 PCM frame
// per sample slice, then ends the stream.
func pcmSource(name string, sampleRate int, channels int, frames ...[]int16) goav.Input {
	return pcmSourceAt(name, sampleRate, channels, nil, frames...)
}

// pcmSourceAt is pcmSource with an optional PTS stamp (in milliseconds, 20ms
// frames) per pushed frame, for the PTS-aligned join examples.
func pcmSourceAt(name string, sampleRate int, channels int, ptsMS []int64, frames ...[]int16) goav.Input {
	return goav.Source(name,
		shape.Frame(av.MediaAudio, shape.Audio(sampleRate, channels, av.SampleFormatS16), shape.Stream(av.StreamID(name))),
		func(_ context.Context, push source.Push) error {
			for i, samples := range frames {
				pcm := make([]byte, len(samples)*2)
				for j, sample := range samples {
					binary.LittleEndian.PutUint16(pcm[j*2:], uint16(sample))
				}
				frame := av.Frame{
					StreamID: av.StreamID(name),
					Type:     av.MediaAudio,
					Audio:    &av.AudioFrame{SampleRate: sampleRate, Channels: channels, SampleFormat: av.SampleFormatS16, Samples: len(samples) / channels},
					Planes:   []av.Plane{{Buffer: av.Buffer{Bytes: pcm}}},
				}
				if i < len(ptsMS) {
					frame.PTS = av.Timestamp{Value: ptsMS[i], Base: av.TimeBase{Num: 1, Den: 1000}}
					frame.Duration = av.Duration{Value: 20, Base: av.TimeBase{Num: 1, Den: 1000}}
				}
				if _, err := push.Frame(&frame); err != nil {
					return err
				}
			}
			return push.EOS()
		})
}

func main() {
	mic := pcmSource("mic", 44_100, 2, make([]int16, 882*2))

	report, err := bundle.MustNew().Explain(context.Background(), mic.
		Audio().
		Auto(shape.AllowResample()).
		Encode(codec.Opus(codec.Bitrate(96_000))).
		To(goav.Write("voice.webm", io.Discard)))
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, warning := range report.Warnings {
		fmt.Println(warning.Code, warning.Message)
	}
}
Output:
shape_conversion_inserted inserted resample 44.1kHz→48kHz before encode-opus (AllowResample)

func (Stream) Buffer

func (s Stream) Buffer(buffer flow.BranchBuffer) Stream

Buffer runs the rest of this fork behind its own queue, so a slow consumer backpressures or sheds alone.

func (Stream) Decode

func (s Stream) Decode(options ...codec.Option) Stream

Decode turns the stream's packets into frames.

func (Stream) Do

func (s Stream) Do(stages ...pipeline.Stage) Stream

Do runs custom stages on the stream: frame stages on decoded frames, packet stages (a bitstream filter) on packets, before or after the encoder.

func (Stream) Encode

func (s Stream) Encode(spec codec.Spec) Stream

Encode turns frames into packets of the given codec.

func (Stream) Playout

func (s Stream) Playout(policy flow.PlayoutPolicy) Stream

Playout holds media until its time is due on the task timeline.

func (Stream) Prefer

func (s Stream) Prefer(spec shape.Spec) Stream

Prefer asks the planner for the given shape here when it can convert.

func (Stream) Require

func (s Stream) Require(spec shape.Spec) Stream

Require fails the build unless the stream has the given shape here.

func (Stream) Resample

func (s Stream) Resample(sampleRate int, channels int, options ...ResampleOption) Stream

Resample converts decoded audio to sampleRate and channels.

func (Stream) Resize

func (s Stream) Resize(width int, height int, options ...ResizeOption) Stream

Resize scales decoded video frames to width x height.

func (Stream) Shape

func (s Stream) Shape(spec shape.Spec) Stream

Shape declares the stream's shape after a custom stage changes it.

func (Stream) Sync

func (s Stream) Sync(policy flow.SyncPolicy) Stream

Sync places the stream on a shared media timeline; reuse one policy across streams to align them.

func (Stream) Tap

func (s Stream) Tap(name string) Stream

Tap names this point of the stream as a stable outlet: it is listed by task.Taps() and runtime branches attach to it.

func (Stream) To

func (s Stream) To(destinations ...Destination) Output

To routes the stream to destinations: packets mux into a container, frames or packets reach a Sink.

type StreamOption

type StreamOption interface {
	// contains filtered or unexported methods
}

StreamOption narrows the stream selection made by the input selectors (Input.Audio, Input.Video, Input.Stream). Build one with StreamID or StreamIndex. It is sealed: only goav option constructors implement it.

func StreamID

func StreamID(id av.StreamID) StreamOption

StreamID narrows a stream selection to the stream with the given id, as probed or declared by the input.

func StreamIndex

func StreamIndex(index int) StreamOption

StreamIndex narrows a stream selection to the stream at the given probe index (0-based).

type Subscription

type Subscription interface {
	Events() <-chan av.Event
	Close() error
}

Subscription is a disposable event subscription returned by Task.Watch. Events is closed when the task ends or Close unsubscribes the watcher. Close is idempotent.

type SwitchBoundary

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

SwitchBoundary is the stream position where a rebranch hands delivery over from the replaced branch to its replacements: NextFrame, NextKeyframe, or AtMediaTime.

func AtMediaTime

func AtMediaTime(position time.Duration) SwitchBoundary

AtMediaTime switches when the replacement branch sees a packet or frame at or after the given media timestamp.

func NextFrame

func NextFrame() SwitchBoundary

NextFrame switches at the next media message: the replacement branch starts delivering with the first frame or packet that reaches it.

func NextKeyframe

func NextKeyframe() SwitchBoundary

NextKeyframe switches at the next decodable sync point. Raw frames are independently decodable, so on frame streams the next frame qualifies.

type TapSnapshot

type TapSnapshot struct {
	Name      string             `json:"name"`
	MediaKind av.MediaType       `json:"mediaKind,omitempty"`
	Domain    shape.MediaDomain  `json:"domain,omitempty"`
	After     plan.OperationKind `json:"after,omitempty"`
	Shape     shape.Spec         `json:"shape,omitzero"`
	Node      pipeline.NodeRef   `json:"node,omitempty"`
}

TapSnapshot describes one named media outlet a task exposes for runtime branches, as Task.Taps lists it.

type Task

type Task interface {
	// Run drives the graph until every source ends or ctx is done. It returns
	// the first fatal node error; otherwise nil when every source ended, or
	// ctx.Err() when ctx stopped the task. Successful Run leaves destinations
	// finalizing: Close must finish before output success is known.
	Run(context.Context) error
	// Close releases the task's resources and finalizes destinations; it is
	// idempotent and safe to call while Run is still in flight. Finalization
	// errors are retained and returned by subsequent Close calls.
	Close() error
	// Explain reports the planned workflow before any resource opens: inputs,
	// branches, destinations, taps, shapes, planner decisions, and warnings.
	Explain(context.Context) (plan.Report, error)
	// Spec returns the structured graph spec — the same nodes and edges Run
	// executes, node for node, and what Runtime.Describe predicted for the same
	// Outputs. Stats reports over the same node set, as Attachment.Spec and
	// Attachment.Stats do for a branch. Rendering lives outside core
	// (graphrender).
	Spec() pipeline.Spec
	// Taps lists the stable attach points runtime branches can anchor from.
	Taps() []TapSnapshot
	// Snapshot returns a point-in-time diagnostic view without exposing graph handles.
	Snapshot() TaskSnapshot
	// Stats returns per-node counters — packets, frames, drops by reason —
	// over the node set Spec reports, with removed nodes counted only in
	// the graph totals. They are readable while the task runs (lock-free atomic
	// reads).
	Stats() pipeline.GraphStats
	// Tap is the stream at one of the task's taps; Outputs built from it are
	// added to the running task with Attach.
	Tap(name string) Stream
	// Track is a stream one of the task's inputs produces or will produce, for
	// Outputs Attach adds before that stream's first media arrives.
	Track(input Input, stream av.Stream) Stream
	// Route is the stream a graph route carries, for Outputs Attach anchors on
	// an expert graph node: task.Route(node.Out().Route()).
	Route(route pipeline.Route) Stream
	// Attach adds Outputs to the running task, each fed from a task.Tap,
	// task.Track, or task.Route stream. One call applies them atomically: a later Output may
	// read a tap an earlier one declares, and a failure rolls the group back.
	Attach(context.Context, ...Output) (Attachment, error)
	// Detach removes a runtime branch and any dependent branches anchored on
	// its taps. By default destinations finalize as closed; DrainBranch or
	// AbortBranch records a commit/abort outcome for the detached branch.
	Detach(context.Context, Attachment, ...DetachOption) error
	// Control injects an out-of-band control into the running graph, delivered to a
	// target node on its serial worker — the control-plane entry point for live
	// switching (a selector), keyframe requests, and flushes.
	Control(context.Context, control.Control) error
	// Pause freezes the task timeline at its current reading: paced sources
	// stall on their next due wait and playout gates hold delivery, coherently,
	// until Resume. Pause pauses TIME, not the data plane — a free-running task
	// (no paced source, no playout gate) would not stall, so Pause refuses it
	// with format.ErrRateUnsupported exactly like control.Rate does. Pausing a
	// paused task is a no-op; pausing before Run is allowed (the timeline is
	// anchored at build); pausing a closed task is refused with
	// control.ErrNotRunning. Rate changes while paused are accepted and take
	// effect on Resume; seek/segment controls are accepted while paused and
	// apply at the source's next read boundary.
	Pause(context.Context) error
	// Resume continues a paused task timeline from its frozen reading at the
	// current rate — no pause gap enters media time. Resuming a running task is
	// a no-op; the refusal contract mirrors Pause.
	Resume(context.Context) error
	// Watch returns an independent, filtered subscription to the task's event
	// stream. Filters AND together; with zero filters every event is delivered.
	// Each subscription owns a buffered channel sized like the task's event
	// buffer: when a watcher falls behind and its buffer fills, new events are
	// dropped for that watcher only — the data plane and other watchers never
	// block on a slow consumer. Subscription channels close when the task closes
	// or Subscription.Close unsubscribes them. Use an unfiltered Watch() when
	// every event should be delivered.
	Watch(filters ...EventFilter) Subscription
}

Task is a built media composition produced by Runtime.Build: it runs and closes the graph, reports plans/specs/snapshots/stats, and supports live branch attach/detach, out-of-band controls, pause/resume, and event watches.

Example (Attach)

ExampleTask_attach adds a runtime branch to a built task: the branch anchors on a typed tap and receives the same frames as the planned chain, without touching the source or its siblings.

ctx := context.Background()
mainFrames, monitorFrames := 0, 0
countInto := func(counter *int) goav.Destination {
	return goav.Sink(component.SinkFunc("count", func(_ context.Context, msg component.Message) error {
		if msg.Frame != nil {
			*counter++
		}
		return nil
	}))
}

task, err := mustRuntime().Build(ctx, pcmSource("mic", 48_000, 1, []int16{1, 2}).
	Audio().
	Tap("mic.frames").
	To(countInto(&mainFrames)))
if err != nil {
	fmt.Println(err)
	return
}
defer task.Close()

if _, err := task.Attach(ctx,
	task.Tap("mic.frames").
		As("monitor").
		To(countInto(&monitorFrames)),
); err != nil {
	fmt.Println(err)
	return
}

if err := task.Run(ctx); err != nil {
	fmt.Println(err)
	return
}
fmt.Println("main:", mainFrames, "monitor:", monitorFrames)
Output:
main: 1 monitor: 1
Example (Control)

ExampleTask_control drives a running task without naming graph nodes: untargeted controls enter at the source boundary and ride the data path to every relevant node.

ctx := context.Background()

task, err := mustRuntime().Build(ctx, goav.Read("input.ivf", bytes.NewReader(tinyIVF())).
	Video().
	Decode().
	Encode(codec.VP8(codec.Bitrate(1_000_000))).
	To(goav.Write("out.ivf", io.Discard)))
if err != nil {
	fmt.Println(err)
	return
}
defer task.Close()

go func() { _ = task.Run(ctx) }()

for _, control := range []control.Control{
	control.Keyframe("video"),                          // every live encoder for the stream produces a keyframe
	control.Must(control.SetBitrate("video", 900_000)), // live encoders retarget mid-stream
	control.Seek(30 * time.Second),                     // sources reposition to a media position
} {
	if err := task.Control(ctx, control); err != nil {
		fmt.Println(err)
	}
}
Example (Flowchart)
package main

import (
	"context"
	"fmt"
	"strings"
	"time"

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

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()

	main := goavtest.NewCollector()
	task, err := goavtest.Runtime().Build(ctx, goavtest.LiveAudio("mic", 48000, 1, []int16{1}).
		Audio().
		Tap("frames").
		To(main.Sink()))
	if err != nil {
		fmt.Println(err)
		return
	}
	runErr := make(chan error, 1)
	go func() { runErr <- task.Run(ctx) }()

	if err := main.Wait(ctx, func(c *goavtest.Collector) bool { return len(c.Frames()) > 0 }); err != nil {
		fmt.Println(err)
		_ = task.Close()
		return
	}
	preview := goavtest.NewCollector()
	if _, err := task.Attach(ctx, task.Tap("frames").As("preview").To(preview.Sink())); err != nil {
		fmt.Println(err)
		_ = task.Close()
		return
	}

	flowchart, err := graphrender.RenderTaskFlowchart(task)
	if err != nil {
		fmt.Println(err)
		_ = task.Close()
		return
	}
	fmt.Println(strings.HasPrefix(flowchart, "flowchart LR"))
	fmt.Println(strings.Contains(flowchart, "branch=preview (attached)"))

	_ = task.Close()
	select {
	case <-runErr:
	case <-time.After(time.Second):
		fmt.Println("run stopped:", false)
	}

}
Output:
true
true
Example (Watch)

ExampleTask_watch subscribes one consumer to a filtered slice of the task's event stream: each watcher owns a buffered channel that closes when the task closes, and a slow watcher sheds events for itself only.

ctx := context.Background()
task, err := mustRuntime().Build(ctx, pcmSource("mic", 48_000, 1, []int16{1, 2}).
	Audio().
	To(goav.Sink(component.SinkFunc("out", func(context.Context, component.Message) error { return nil }))))
if err != nil {
	fmt.Println(err)
	return
}

eos := task.Watch(goav.WatchTypes(av.EventEndOfStream)).Events()

if err := task.Run(ctx); err != nil {
	fmt.Println(err)
	return
}
if err := task.Close(); err != nil {
	fmt.Println(err)
	return
}

ended := false
for event := range eos {
	ended = ended || event.Type == av.EventEndOfStream
}
fmt.Println("end of stream:", ended)
Output:
end of stream: true

type TaskSnapshot

type TaskSnapshot struct {
	State TaskState `json:"state"`
	// Err is the retained execution/finalization error, suitable for errors.Is.
	// Error is its printable form for JSON consumers.
	Err   error  `json:"-"`
	Error string `json:"error,omitempty"`
	// Paused reports whether the task timeline is frozen by Task.Pause. It
	// is orthogonal to State: a paused task still reports its run progress.
	Paused       bool                  `json:"paused,omitempty"`
	Spec         pipeline.Spec         `json:"spec"`
	Stats        pipeline.GraphStats   `json:"stats"`
	Taps         []TapSnapshot         `json:"taps,omitempty"`
	Branches     []BranchSnapshot      `json:"branches,omitempty"`
	Destinations []DestinationSnapshot `json:"destinations,omitempty"`
}

TaskSnapshot is an immutable point-in-time view of a task's graph, taps, active runtime branches, and counters, returned by Task.Snapshot.

type TaskState

type TaskState string

TaskState is the lifecycle state a TaskSnapshot reports.

const (
	// TaskBuilt reports a task that was built but whose Run has not started.
	TaskBuilt TaskState = "built"
	// TaskRunning reports a task whose Run is in progress.
	TaskRunning TaskState = "running"
	// TaskFinalizing reports that execution ended but Close has not completed.
	TaskFinalizing TaskState = "finalizing"
	// TaskClosed reports a task whose resources finished closing without error.
	TaskClosed TaskState = "closed"
	// TaskFailed reports a terminal execution or finalization error. Cleanup
	// may still be pending; Stats.PendingCleanup reports that separately.
	TaskFailed TaskState = "failed"
)

Directories

Path Synopsis
adapters
annexb
Package annexb adapts H264 Annex B packet streams to format mux interfaces.
Package annexb adapts H264 Annex B packet streams to format mux interfaces.
ivf
Package ivf adapts IVF packet streams to the goav format interfaces.
Package ivf adapts IVF packet streams to the goav format interfaces.
resample
Package resample provides a small pure-Go audio resample filter adapter.
Package resample provides a small pure-Go audio resample filter adapter.
resize
Package resize provides a pure-Go planar 4:2:0 video resize filter adapter.
Package resize provides a pure-Go planar 4:2:0 video resize filter adapter.
Package av is the transport-neutral media vocabulary every other package speaks: packets, frames, events, and streams, plus the identifiers (media, codec, format, protocol), rational timestamps, and the reference-counted payload buffers (Buffer, NewBuffer) every branch shares instead of copying.
Package av is the transport-neutral media vocabulary every other package speaks: packets, frames, events, and streams, plus the identifiers (media, codec, format, protocol), rational timestamps, and the reference-counted payload buffers (Buffer, NewBuffer) every branch shares instead of copying.
Package bundle provides the bundled pure-Go runtime adapters for goav recipes.
Package bundle provides the bundled pure-Go runtime adapters for goav recipes.
cameraav module
cmd
goav module
Package codec defines the decoder and encoder contracts: descriptors that declare what an implementation can do, factories that open it, and the caller-owned result buffers that keep decode/encode allocation-free.
Package codec defines the decoder and encoder contracts: descriptors that declare what an implementation can do, factories that open it, and the caller-owned result buffers that keep decode/encode allocation-free.
Package component contains small adapters for custom pipeline components.
Package component contains small adapters for custom pipeline components.
container
ebml
Package ebml contains low-level EBML primitives used by container packages.
Package ebml contains low-level EBML primitives used by container packages.
hls
Package hls packages goav output as HTTP Live Streaming (RFC 8216): fragmented MP4 segments and a media playlist, for live or on-demand delivery.
Package hls packages goav output as HTTP Live Streaming (RFC 8216): fragmented MP4 segments and a media playlist, for live or on-demand delivery.
matroska
Package matroska provides a high-level Matroska muxer and demuxer.
Package matroska provides a high-level Matroska muxer and demuxer.
mp4
Package mp4 is a pure-Go ISO Base Media File Format (ISO/IEC 14496-12) demuxer and muxer for MP4/MOV/M4A/M4V. It registers behind the goav format extension point as the av.FormatMP4 demuxer and muxer.
Package mp4 is a pure-Go ISO Base Media File Format (ISO/IEC 14496-12) demuxer and muxer for MP4/MOV/M4A/M4V. It registers behind the goav format extension point as the av.FormatMP4 demuxer and muxer.
webm
Package webm provides a restricted WebM profile wrapper around Matroska.
Package webm provides a restricted WebM profile wrapper around Matroska.
Package control defines the in-process live task control vocabulary; for exposing those controls over a socket, see package ctlserver.
Package control defines the in-process live task control vocabulary; for exposing those controls over a socket, see package ctlserver.
Package ctlserver is goav's control plane: a running task's capabilities, served to clients over a socket or HTTP.
Package ctlserver is goav's control plane: a running task's capabilities, served to clients over a socket or HTTP.
Package errcode names goav's structured error vocabulary.
Package errcode names goav's structured error vocabulary.
examples
Package expert is the handle-based graph layer deliberately kept off the goav grammar: Graph(runtime) wires caller-provided pipeline Sources, Stages, and Sinks into a goav Task through explicit routes — for compositions the Stream grammar cannot express.
Package expert is the handle-based graph layer deliberately kept off the goav grammar: Graph(runtime) wires caller-provided pipeline Sources, Stages, and Sinks into a goav Task through explicit routes — for compositions the Stream grammar cannot express.
Package filter defines the frame transform contracts: filters that resize, resample, or convert decoded frames through caller-owned result buffers, the capability descriptors the planner and shape solver select adapters by, and the per-runtime registry external filters plug into.
Package filter defines the frame transform contracts: filters that resize, resample, or convert decoded frames through caller-owned result buffers, the capability descriptors the planner and shape solver select adapters by, and the per-runtime registry external filters plug into.
Package flow holds the branch buffer and flow-control vocabulary used to describe how a goav branch queues, drops, or backpressures messages.
Package flow holds the branch buffer and flow-control vocabulary used to describe how a goav branch queues, drops, or backpressures messages.
Package format defines the container contracts: probing detects what bytes are (format and streams) before anything opens, demuxers read packets out of containers, and muxers write them back in.
Package format defines the container contracts: probing detects what bytes are (format and streams) before anything opens, demuxers read packets out of containers, and muxers write them back in.
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.
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.
expect module
Package graphrender renders a pipeline.Spec — the graph Runtime.Describe plans and Task.Spec reports once built — as human-readable text, Graphviz DOT, or Mermaid, and annotates goav.TaskSnapshot and goav.BranchSnapshot views with branch and tap labels.
Package graphrender renders a pipeline.Spec — the graph Runtime.Describe plans and Task.Spec reports once built — as human-readable text, Graphviz DOT, or Mermaid, and annotates goav.TaskSnapshot and goav.BranchSnapshot views with branch and tap labels.
internal
av1
Package av1 reads the parts of an AV1 bitstream containers need: OBU framing, the sequence header, and the AV1CodecConfigurationRecord (av1C) that Matroska CodecPrivate and the ISO BMFF av1C box both carry.
Package av1 reads the parts of an AV1 bitstream containers need: OBU framing, the sequence header, and the AV1CodecConfigurationRecord (av1C) that Matroska CodecPrivate and the ISO BMFF av1C box both carry.
bitio
Package bitio reads the big-endian bit fields codec headers are made of.
Package bitio reads the big-endian bit fields codec headers are made of.
builderr
Package builderr is the refusal vocabulary goav's root package and its compiler share: typed details, fixes, phases, the unsupported-build cause, and Refusal, the compiler's refusal value.
Package builderr is the refusal vocabulary goav's root package and its compiler share: typed details, fixes, phases, the unsupported-build cause, and Refusal, the compiler's refusal value.
compile
Package compile is goav's recipe compiler.
Package compile is goav's recipe compiler.
expertgraph
Package expertgraph is the one hook between the goav root package and the expert package.
Package expertgraph is the one hook between the goav root package and the expert package.
h264
Package h264 holds the H.264 bitstream helpers the containers share: avcC decoder-configuration parsing and AVCC (length-prefixed) to Annex B (start-code) conversion.
Package h264 holds the H.264 bitstream helpers the containers share: avcC decoder-configuration parsing and AVCC (length-prefixed) to Annex B (start-code) conversion.
hevc
Package hevc holds the HEVC (H.265) bitstream helpers the containers share: parameter-set NAL units, the sequence parameter set fields a decoder configuration repeats, and the hvcC decoder configuration record (ISO/IEC 14496-15, 8.3.3).
Package hevc holds the HEVC (H.265) bitstream helpers the containers share: parameter-set NAL units, the sequence parameter set fields a decoder configuration repeats, and the hvcC decoder configuration record (ISO/IEC 14496-15, 8.3.3).
interleave
Package interleave is the contract between the offline pipeline runner and the nodes it may order by time.
Package interleave is the contract between the offline pipeline runner and the nodes it may order by time.
payload
Package payload turns what a codec, filter, or demuxer wrote into its caller-owned result into payload a stage may publish: the stage's own header over buffers it holds a reference to.
Package payload turns what a codec, filter, or demuxer wrote into its caller-owned result into payload a stage may publish: the stage's own header over buffers it holds a reference to.
raceflag
Package raceflag reports whether the race detector is compiled in, so an allocation pin that relies on av.NewBuffer's pool reuse can skip under -race: there sync.Pool drops a share of what it is given, on purpose.
Package raceflag reports whether the race detector is compiled in, so an allocation pin that relies on av.NewBuffer's pool reuse can skip under -race: there sync.Pool drops a share of what it is given, on purpose.
recipeir
Package recipeir is the recipe IR the value grammar compiles to and the planner reads: a DAG of inputs, selected streams, operations, joins, and destinations (Graph), and the branches derived from it (Streams).
Package recipeir is the recipe IR the value grammar compiles to and the planner reads: a DAG of inputs, selected streams, operations, joins, and destinations (Graph), and the branches derived from it (Streams).
specrender
Package specrender renders a pipeline.Spec as text, Graphviz DOT, or Mermaid, selected by a goav:graph URI.
Package specrender renders a pipeline.Spec as text, Graphviz DOT, or Mermaid, selected by a goav:graph URI.
spelling
Package spelling reads the text spellings of values that pipeline programs and control calls share — 2M, true/on, and did-you-mean hints — so a value means the same thing wherever an operator types it.
Package spelling reads the text spellings of values that pipeline programs and control calls share — 2M, true/on, and did-you-mean hints — so a value means the same thing wherever an operator types it.
uri
Package uri is goav's one URL handling for what it reports and reads: the scheme a value names, names without credentials, URLs with their secrets replaced, and source text with its secrets masked in place.
Package uri is goav's one URL handling for what it reports and reads: the scheme a value names, names without credentials, URLs with their secrets replaced, and source text with its secrets masked in place.
Package launch is goav's pipeline language: a goav recipe written as text, for command lines, configuration files, and control sockets.
Package launch is goav's pipeline language: a goav recipe written as text, for command lines, configuration files, and control sockets.
libcodec module
Package metrics bridges a running goav task to monitoring: Handler serves its counters in the Prometheus text exposition format, and Publish exposes the same data through expvar.
Package metrics bridges a running goav task to monitoring: Handler serves its counters in the Prometheus text exposition format, and Publish exposes the same data through expvar.
Package pipeline is the executable graph layer under the goav recipe grammar: sources, stages, and sinks wired by routes into an inspectable, runnable Graph.
Package pipeline is the executable graph layer under the goav recipe grammar: sources, stages, and sinks wired by routes into an inspectable, runnable Graph.
Package plan holds the structured Explain tree: the report a job or task returns about what it will do, which adapters it needs, and the decisions and diagnostics behind the plan.
Package plan holds the structured Explain tree: the report a job or task returns about what it will do, which adapters it needs, and the decisions and diagnostics behind the plan.
player module
playoutav module
Package provider declares the contracts external transports and destinations satisfy to plug into goav with zero goav changes: Source and ByteSource are the inputs goav.From adapts into a recipe input, Destination (with Contract, Info, TransactionalWriter, and OpenFunc) is the seam goav.Custom and goav.WriteFunc wrap behind destination handles, and InputScheme and DestinationScheme bind URLs to them, for goav.FromURI and goav.ToURI.
Package provider declares the contracts external transports and destinations satisfy to plug into goav with zero goav changes: Source and ByteSource are the inputs goav.From adapts into a recipe input, Destination (with Contract, Info, TransactionalWriter, and OpenFunc) is the seam goav.Custom and goav.WriteFunc wrap behind destination handles, and InputScheme and DestinationScheme bind URLs to them, for goav.FromURI and goav.ToURI.
rtmpav module
rtpav module
Package runconfig owns goav runtime construction options.
Package runconfig owns goav runtime construction options.
Package scheme holds goav's built-in URL schemes, the providers goav.FromURI and goav.ToURI resolve through: File for file URLs and bare paths, and HTTP for http and https.
Package scheme holds goav's built-in URL schemes, the providers goav.FromURI and goav.ToURI resolve through: File for file URLs and bare paths, and HTTP for http and https.
scripts
Package shape holds the media-format descriptor vocabulary used across goav to describe the shape of a stream at a point in a pipeline: its domain, media kind, codec, geometry, and audio layout.
Package shape holds the media-format descriptor vocabulary used across goav to describe the shape of a stream at a point in a pipeline: its domain, media kind, codec, geometry, and audio layout.
Package source contains helpers for application-owned media sources.
Package source contains helpers for application-owned media sources.
webrtcav module

Jump to

Keyboard shortcuts

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