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 ¶
- Variables
- type Attachment
- type BranchFailureError
- type BranchFailurePolicy
- type BranchSnapshot
- type BranchState
- type BuildError
- type CompositeArg
- type Destination
- func Custom(dest provider.Destination, opts ...DestinationOption) Destination
- func Sink(sink pipeline.Sink, opts ...DestinationOption) Destination
- func ToURI(uri string, opts ...DestinationOption) Destination
- func Write(name string, writer io.Writer, opts ...DestinationOption) Destination
- func WriteFunc(name string, open provider.OpenFunc, opts ...DestinationOption) Destination
- type DestinationOption
- type DestinationSnapshot
- type DestinationState
- type DetachOption
- type EventFilter
- type Input
- func (s Input) Audio(options ...StreamOption) Stream
- func (s Input) OnStream(match sourcepkg.StreamMatch) Stream
- func (s Input) Stream(options ...StreamOption) Stream
- func (s Input) To(destinations ...Destination) Output
- func (s Input) Video(options ...StreamOption) Stream
- func (s Input) With(opts ...InputOption) Input
- func (spec Input) Wrap(wrap func(pipeline.Source) pipeline.Source) Input
- type InputOption
- type JoinOption
- type MediaOption
- type MixArg
- type Output
- type RebranchArg
- type ResampleOption
- type ResizeOption
- type Runtime
- func (r *Runtime) Build(ctx context.Context, outs ...Output) (*Task, error)
- func (r *Runtime) Describe(outs ...Output) (pipeline.Spec, error)
- func (r *Runtime) Explain(ctx context.Context, outs ...Output) (plan.Report, error)
- func (r *Runtime) Probe(ctx context.Context, request format.ProbeRequest) (format.ProbeResult, error)
- func (r *Runtime) Run(ctx context.Context, outs ...Output) error
- type Stream
- func (s Stream) As(name string) Stream
- func (s Stream) Auto(policies ...shape.Policy) Stream
- func (s Stream) Buffer(buffer flow.BranchBuffer) Stream
- func (s Stream) Decode(options ...codec.Option) Stream
- func (s Stream) Do(stages ...pipeline.Stage) Stream
- func (s Stream) Encode(spec codec.Spec) Stream
- func (s Stream) Playout(policy flow.PlayoutPolicy) Stream
- func (s Stream) Prefer(spec shape.Spec) Stream
- func (s Stream) Require(spec shape.Spec) Stream
- func (s Stream) Resample(sampleRate int, channels int, options ...ResampleOption) Stream
- func (s Stream) Resize(width int, height int, options ...ResizeOption) Stream
- func (s Stream) Shape(spec shape.Spec) Stream
- func (s Stream) Sync(policy flow.SyncPolicy) Stream
- func (s Stream) Tap(name string) Stream
- func (s Stream) To(destinations ...Destination) Output
- type StreamOption
- type Subscription
- type SwitchBoundary
- type TapSnapshot
- type Task
- func (t *Task) Attach(ctx context.Context, outs ...Output) (Attachment, error)
- func (t *Task) Close() error
- func (t *Task) CloseContext(ctx context.Context) error
- func (t *Task) Control(ctx context.Context, ctrl control.Control) error
- func (t *Task) Detach(ctx context.Context, attachment Attachment, options ...DetachOption) error
- func (t *Task) EncoderDescriptors() []codec.Descriptor
- func (t *Task) Explain(context.Context) (plan.Report, error)
- func (t *Task) MuxerDescriptors() []format.Descriptor
- func (t *Task) Pause(ctx context.Context) error
- func (t *Task) Resume(ctx context.Context) error
- func (t *Task) Route(route pipeline.Route) Stream
- func (t *Task) Run(ctx context.Context) error
- func (t *Task) Snapshot() TaskSnapshot
- func (t *Task) Spec() pipeline.Spec
- func (t *Task) Stats() pipeline.GraphStats
- func (t *Task) Tap(name string) Stream
- func (t *Task) Taps() []TapSnapshot
- func (t *Task) Track(input Input, stream av.Stream) Stream
- func (t *Task) Watch(filters ...EventFilter) Subscription
- type TaskSnapshot
- type TaskState
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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 CompositeArg ¶ added in v0.3.0
type CompositeArg interface {
// contains filtered or unexported methods
}
CompositeArg is one argument of Composite: a Stream, a Stream placed At a position, or a JoinOption such as ByPTS. It is sealed: only goav values implement it.
func At ¶
func At(s Stream, x, y int) CompositeArg
At places a Composite input's top-left corner at (x, y) on the canvas.
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 ¶
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 ¶
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 ¶
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 JoinOption ¶ added in v0.3.0
type JoinOption struct {
// contains filtered or unexported fields
}
JoinOption is a shared option accepted by both Mix and Composite (such as ByPTS).
func ByPTS ¶
func ByPTS() JoinOption
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 MixArg ¶ added in v0.3.0
type MixArg interface {
// contains filtered or unexported methods
}
MixArg is one argument of Mix: a Stream or a JoinOption such as ByPTS. It is sealed: only goav values implement it.
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 ¶
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) Explain ¶
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 ¶
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 ...CompositeArg) 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 Mix ¶
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 ¶
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 ¶
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 ¶
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) Do ¶
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) Playout ¶
func (s Stream) Playout(policy flow.PlayoutPolicy) Stream
Playout holds media until its time is due on the task timeline.
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) 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 ¶
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 ¶
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 struct {
// contains filtered or unexported fields
}
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
func (*Task) Attach ¶
Attach adds Outputs fed from the task's taps, tracks, and graph routes to the running task.
func (*Task) Control ¶
Control injects an out-of-band control into the running task's graph, delivering it to the node named by ctrl.Node() on that node's serial worker. It is safe to call concurrently with Run: the control rides the target node's normal queue, so the node's Handle still sees one message at a time and needs no extra locking. Reposition controls (seek, segment) are the exception: sources have no queue, so they are handed to each source's Control method synchronously — and once a source can accept one, stale media in its exclusive downstream queues is flushed (flushSeekBacklog) before delivering the control. Shared queues keep their admitted tail so another source's media cannot be lost. Rate is task-wide: it scales the task's shared timeline, which every paced consumer (clock-aware sources and playout gates) sleeps on, and never targets a node.
func (*Task) Detach ¶
func (t *Task) Detach(ctx context.Context, attachment Attachment, options ...DetachOption) error
func (*Task) EncoderDescriptors ¶ added in v0.3.0
func (t *Task) EncoderDescriptors() []codec.Descriptor
EncoderDescriptors lists encoder factories registered on the task runtime.
func (*Task) MuxerDescriptors ¶ added in v0.3.0
func (t *Task) MuxerDescriptors() []format.Descriptor
MuxerDescriptors lists muxer factories registered on the task runtime.
func (*Task) Snapshot ¶
func (t *Task) Snapshot() TaskSnapshot
func (*Task) Stats ¶
func (t *Task) Stats() pipeline.GraphStats
func (*Task) Taps ¶
func (t *Task) Taps() []TapSnapshot
func (*Task) Watch ¶
func (t *Task) Watch(filters ...EventFilter) Subscription
Watch returns an independent, filtered subscription to the task's event stream. See Task.Watch for the delivery, overflow, and closure contract.
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" )
Source Files
¶
- attach_plan.go
- attachment_stats.go
- branch_failure.go
- build_error.go
- byte_input.go
- codec_spec.go
- compile.go
- compile_attach.go
- compile_lower.go
- destination.go
- destination_handle.go
- destination_outcome.go
- detach_policy.go
- gate.go
- goav.go
- graph.go
- graph_plan.go
- input.go
- input_sniff.go
- internal_errcodes.go
- join_arm_file.go
- join_lower.go
- media_plan_build.go
- media_sink.go
- media_transform.go
- mux_destination.go
- operation.go
- playout.go
- provider.go
- qos.go
- rebranch_policy.go
- recipe_explain.go
- recipe_graph.go
- reconnect.go
- runtime.go
- runtime_attach.go
- runtime_attach_errors.go
- runtime_attachment.go
- runtime_attachment_handle.go
- runtime_attachment_helpers.go
- runtime_builder.go
- runtime_decode.go
- runtime_demux.go
- runtime_destination.go
- runtime_encode.go
- runtime_format_error.go
- runtime_graph_detail.go
- runtime_plan.go
- runtime_plan_clone.go
- runtime_select.go
- runtime_stream_rule.go
- source.go
- stream.go
- stream_errors.go
- sync.go
- task_control.go
- task_pause.go
- task_view.go
- transform.go
- uri.go
- watch.go
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
|
|
|
gio-webrtc-showcase
module
|
|
|
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
|
|
|
Package playoutav adapts scheduled packets, frames, and events into a goav source provider.
|
Package playoutav adapts scheduled packets, frames, and events into a goav source provider. |
|
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
|
|
|
bench/internal/benchbaseline
command
|
|
|
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
|