libsippycup

package
v0.0.0-...-3438ddd Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: MIT Imports: 57 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

libsippycup

← Sippycup

Import github.com/ronsor/sippycup/libsippycup. Build a Config, call Validate to check it and prepare defaults, then create an engine. For example, this forwards incoming AudioSocket calls to a second AudioSocket server:

package main

import (
	"context"
	"log"
	"os"
	"os/signal"

	"github.com/ronsor/sippycup/libsippycup"
)

func main() {
	config := &libsippycup.Config{
		Sources: []*libsippycup.Node{
			{Name: "in", Type: "audiosocket", Bind: "127.0.0.1:9019"},
		},
		Endpoints: []*libsippycup.Node{
			{Name: "out", Type: "audiosocket", Address: "127.0.0.1:9020"},
		},
		Routes: []*libsippycup.Route{
			{Name: "forward", Connect: &libsippycup.Connect{Endpoint: "out"}},
		},
	}
	if err := config.Validate(); err != nil {
		log.Fatal(err)
	}

	ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
	defer cancel()

	if err := libsippycup.NewEngine(config).Serve(ctx); err != nil {
		log.Fatal(err)
	}
}

Serve handles startup and cleanup until cancellation. Alternatively, use Start and Close explicitly. DialCommand connects a PCM subprocess to a configured endpoint. HTTP sources include the browser call page automatically. HCL file loading and CLI flag parsing live in the root command, not the library.

The configuration must remain immutable while the engine is running. After Start, call Reload with a fresh, independent configuration to update new calls while preserving existing calls and transports. A rejected reload leaves the running configuration intact. See reload restrictions. Do not call Reload concurrently with Start or Close.

Use Done to observe cancellation and Close to wait for cleanup.

See configuration types, package documentation, subprocess endpoints, and the independent AudioSocket library.

In-process calls

Use Type: "inproc" for a source controlled by your Go application or an endpoint implemented by a Go callback. Sources need no bind address. Set Node.InProcess on each in-process endpoint before calling Config.Validate. The callback is a Go-only field; an embedding frontend can decode HCL nodes and attach callbacks before validation. The standalone CLI cannot supply them.

An endpoint callback has this signature:

func(ctx context.Context, request libsippycup.EndpointRequest) (libsippycup.Leg, error)

The request includes the incoming request, evaluated destination, metadata and identity expressions, requested format, and a CallContext. The callback's ctx limits setup and is canceled when setup ends; use CallContext for returned legs and application workers. Callbacks must honor cancellation and may run concurrently. Returning a leg successfully transfers ownership to the engine. A returned leg must use an explicit, supported format; a forced transcode format must match it.

To originate through a named source, call engine.Accept(ctx, sourceName, request, leg) after Start, usually in a goroutine. It routes and bridges the call until hangup. The engine owns the supplied leg even if setup fails. Metadata stays immutable for the call; application-supplied authentication identity is trusted. Setup errors are returned; established-call media errors are logged.

NewLegPair(ctx, format, capacity) provides two connected MemoryLeg values. Give one to the engine and use the other in your application. Each direction has a bounded frame queue with backpressure. Writes copy audio buffers, and readers own received buffers. Closing either end or canceling the pair's context interrupts both ends. Custom legs must make Close safe concurrently and unblock I/O; an optional Done() <-chan struct{} lets peer closure cancel pending endpoint setup.

In-process nodes default to native early-media signaling. MemoryLeg implements StatefulLeg: state messages travel independently from audio and DTMF. An endpoint returning a StatefulLeg writes StateEarly (optional), then StateAnswered, from its application end. A plain endpoint Leg is treated as immediately answered. An in-process source using native mode requires a StatefulLeg; the application reads its early/answered notifications. The existing disabled and answer policies also apply. Hangup is represented by closure, not an additional state message.

Normal routes, transcoding, DTMF policies, call limits, timeouts, shutdown, and reload snapshots apply. New calls use replacement callbacks after reload; existing calls retain their original legs. As with network sources, changing the configured source set currently requires a restart.

See the runnable in-process echo example.

Documentation

Overview

Package libsippycup routes calls between SIP, AudioSocket, WebRTC, subprocesses, and in-process Go applications. The engine proxies all audio and supports transcoding, DTMF conversion, authentication, and early media.

Engine lifecycle

Build a Config, call Config.Validate, and pass it to NewEngine. HCL parsing and command-line handling belong to the sippycup CLI; Go applications can construct configuration directly.

Engine.Serve starts the engine and runs until its context is canceled or Engine.Close is called. It closes resources before returning. Applications that manage their own lifecycle can use Engine.Start and Engine.Close instead. Do not call both Start and Serve on the same engine.

Engine.Reload applies a fresh configuration to new calls while existing calls keep their original settings. Listener and transport changes that require a restart are rejected. See Reload for the configuration ownership rules and restrictions.

Sources, endpoints, and routes

Sources accept calls; endpoints make calls. Both use Node configuration with a type of sip, audiosocket, audiosocket_ws, webrtc_http, or inproc. Endpoints also support exec to run a subprocess for each call. A SIP source can register with a remote registrar and accept calls through that account.

Routes run in declaration order, matching incoming request information and optionally extracting values with regular expressions. Each route connects to an endpoint or rejects the call. Unmatched calls are rejected. Credentials, media policies, timeouts, and resource limits are configured per node, with global limits bounding total usage.

In-process calls

A Leg carries audio frames and DTMF events. StatefulLeg adds early-media and answered notifications. NewLegPair creates connected legs with bounded in-memory queues for applications that do not need a network transport.

After starting the engine, pass a leg and Request to Engine.Accept to route a call through an inproc source. Accept takes ownership of the leg and blocks until the call ends. For an inproc endpoint, set Node.InProcess to an EndpointFunc that creates a fresh leg for each call. The callback's context covers setup; EndpointRequest.CallContext lasts for the entire call.

Audio and DTMF

Supported audio formats are mono PCMU/PCMA and mono or stereo Opus and signed 16-bit little-endian PCM. Codecs and resampling use pure Go. Transcoding can be automatic, forced to a configured format, or disabled.

SIP and WebRTC default to PCMU and PCMA; Opus is opt-in. Opus encoding uses 48 kHz audio in 20 ms packets, with a default bitrate of 32000 bits per second. Mono is the default; stereo is opt-in. Each Opus Frame contains one complete packet. AudioSocket carries mono PCM, or stereo PCM in extended mode. Opus FEC, DTX, and adaptive jitter buffering are not enabled.

DTMF receive and send policies are relative to the engine and configurable independently for each node. Native events use RTP telephone-event for SIP and WebRTC, digit packets for AudioSocket, and JSON control for subprocesses. SIP INFO and in-band tone detection and synthesis are also supported.

Early media can be disabled, carried with native call-state signaling, or delivered by answering the source early. SIP and extended AudioSocket can preserve early and answered states. WebRTC HTTP and ordinary AudioSocket can carry early audio after accepting the source connection.

Network protocols

AudioSocket supports TCP and WebSocket transports. Extended mode accepts JSON identities containing a UUID and application metadata, and optionally carries call-state messages. The separate audiosocket package provides reusable framing, dialing, and listening without the routing engine.

WebRTC uses a custom bidirectional HTTP signaling profile, not WHEP. An SDP POST creates a session; PATCH adds ICE candidates and DELETE closes it. HTTP sources can share a bind address with distinct paths. Browser requests preferring HTML receive an embedded call page with microphone audio and a DTMF keypad. Microphone access requires HTTPS or localhost.

SIP supports digest authentication, outbound proxies, and symmetric RTP. Public RTP address discovery via STUN is optional; automatic advertisement alone chooses a local address. WebRTC has separate ICE and TURN settings. SIP TLS protects signaling, not RTP.

The engine is not a PBX or registrar. Conferencing, REFER, SIP re-INVITE and hold, SIP SRTP, and SDP renegotiation are not supported.

Further documentation

The repository contains detailed guides for configuration, media, networking, subprocess endpoints, and WebRTC signaling. CLI commands and examples are described in the CLI guide.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func DialCommand

func DialCommand(ctx context.Context, config *Config, name, to string, rate int, command []string) error

DialCommand connects a PCM subprocess to a configured endpoint and waits for the call to end. It starts only the SIP source needed by that endpoint. Config must be validated with Validate and remain immutable during the call. Its routes are not modified. Cancellation closes the call and child.

func NewLegPair

func NewLegPair(ctx context.Context, format Format, capacity int) (*MemoryLeg, *MemoryLeg, error)

NewLegPair creates two connected legs with the same explicit format and a positive queue capacity in frames per direction. Closing either end or canceling ctx closes both ends and interrupts blocked reads and writes. Applications must eventually close the pair, even after setup fails. Opus frames use the pair's stream format, including Channels, even when a stereo stream contains a mono-encoded packet. See Frame for channel semantics.

Types

type AdvertiseConfig

type AdvertiseConfig struct {
	Mode    string `hcl:"mode,optional"`
	Address string `hcl:"address,optional"`
	BaseURL string `hcl:"base_url,optional"`
}

AdvertiseConfig selects the address placed in signaling or media descriptions. Auto selects a local route address; it does not discover a public NAT mapping.

type AuthConfig

type AuthConfig struct {
	Mode          string         `hcl:"mode,optional"`
	Sources       []string       `hcl:"sources,optional"`
	CredentialSet string         `hcl:"credential_set,optional"`
	Credential    hcl.Expression `hcl:"credential,optional"`
	Realm         string         `hcl:"realm,optional"`
	Method        string         `hcl:"method,optional"`
}

AuthConfig defines inbound verification or outbound authentication. Credential expressions on endpoints may refer to the current request.

type AuthIdentity

type AuthIdentity struct {
	Username   string
	Password   string
	Verified   bool
	DigestOnly bool
}

AuthIdentity holds authentication state for one request. Password is private credential material and is excluded from the HCL request context.

type Call

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

Call owns a two-leg media bridge and its reserved capacity. Run manages media transfer and always closes both legs on completion.

func (*Call) Close

func (c *Call) Close()

Close cancels the bridge, closes both legs, and releases capacity exactly once.

func (*Call) Run

func (c *Call) Run()

Run bridges media until a leg ends, a deadline expires, or Close is called. It closes both legs and releases capacity before returning. Call Run once.

type CallState

type CallState uint8

CallState distinguishes provisional media from an answered call.

const (
	// StateEarly means media is available before the call is answered.
	StateEarly CallState = iota + 1
	// StateAnswered means call setup has completed.
	StateAnswered
)

type Capture

type Capture struct {
	Name    string         `hcl:"name,label"`
	Value   hcl.Expression `hcl:"value"`
	Pattern string         `hcl:"pattern"`
	// contains filtered or unexported fields
}

Capture extracts a value and named regular-expression groups into route context.

type Config

type Config struct {
	Credentials    []*Credential    `hcl:"credential,block"`
	CredentialSets []*CredentialSet `hcl:"credential_set,block"`
	Sources        []*Node          `hcl:"source,block"`
	Endpoints      []*Node          `hcl:"endpoint,block"`
	Routes         []*Route         `hcl:"route,block"`
	Runtime        *RuntimeConfig   `hcl:"runtime,block"`

	// EvalContext supplies static variables and functions for route expressions.
	// It may be nil when all expressions are self-contained.
	EvalContext *hcl.EvalContext
}

Config describes the gateway. Call Validate before passing it to NewEngine. Request-dependent expressions are evaluated when calls arrive. A frontend may supply EvalContext for static references and functions.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks references, protocol constraints, and resource settings. It fills configuration defaults and compiles route regular expressions.

type Connect

type Connect struct {
	Endpoint    string         `hcl:"endpoint"`
	Destination hcl.Expression `hcl:"destination,optional"`
	Identity    hcl.Expression `hcl:"identity,optional"`
	Metadata    hcl.Expression `hcl:"metadata,optional"`
	Timeout     string         `hcl:"timeout,optional"`
}

Connect selects an endpoint and evaluates per-call destination or metadata.

type Credential

type Credential struct {
	Name         string        `hcl:"name,label"`
	Username     string        `hcl:"username"`
	Password     *string       `hcl:"password,optional"`
	PasswordHash string        `hcl:"password_hash,optional"`
	Digest       *DigestConfig `hcl:"digest,block"`
}

Credential defines a username and exactly one password, verification hash, or realm-specific SIP digest HA1 value.

type CredentialSet

type CredentialSet struct {
	Name        string   `hcl:"name,label"`
	Credentials []string `hcl:"credentials"`
}

CredentialSet groups named credentials for inbound verification. Usernames must be unique within a set.

type DTMFConfig

type DTMFConfig struct {
	Receive []string `hcl:"receive,optional"`
	Send    string   `hcl:"send,optional"`
}

DTMFConfig selects received and transmitted digit representations. Directions are relative to the gateway and apply independently to each leg.

type DigestConfig

type DigestConfig struct {
	Realm     string `hcl:"realm"`
	Algorithm string `hcl:"algorithm"`
	HA1       string `hcl:"ha1"`
}

DigestConfig holds a SIP digest HA1 value for one realm and algorithm.

type EndpointFunc

type EndpointFunc func(context.Context, EndpointRequest) (Leg, error)

EndpointFunc creates a fresh leg per call. The context limits setup; the callback must return promptly when it is canceled. Use CallContext for the returned leg and application workers. Successful return transfers ownership of the leg to the engine. For a StatefulLeg, send StateEarly (optional), then StateAnswered from its peer; the configured policy controls early audio. A plain Leg is treated as immediately answered. Callbacks may run concurrently.

type EndpointRequest

type EndpointRequest struct {
	Request     Request
	Destination string
	Metadata    any
	Identity    any
	Format      Format
	CallContext context.Context
}

EndpointRequest contains evaluated routing information for a Go endpoint. Request and its nested values are read-only. Format is the requested media format; returning a different valid format permits automatic transcoding. CallContext lasts for the entire call, unlike the callback's setup context.

type Engine

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

Engine owns protocol listeners, sessions, and shared resource accounting. Create it from a validated Config, then call Start and eventually Close.

func NewEngine

func NewEngine(c *Config) *Engine

NewEngine creates an idle engine from a validated configuration. It opens no listeners until Start.

func (*Engine) Accept

func (e *Engine) Accept(ctx context.Context, name string, request Request, leg Leg) error

Accept routes and runs one call through a named inproc source, blocking until it ends. Call it after Start. It takes ownership of a non-nil leg even on failure and closes it on return. Close must be safe concurrently and unblock all I/O. Context cancellation and Engine.Close terminate the call. A leg with Done() also interrupts pending setup when its peer closes.

Metadata must remain immutable until Accept returns. Source is set from name; a missing ID is generated. Auth is trusted application-supplied identity, never independently verified. Setup errors are returned; established-call media errors are logged by the bridge. Native early media requires StatefulLeg.

Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/ronsor/sippycup/libsippycup"
)

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

	echo := func(_ context.Context, request libsippycup.EndpointRequest) (libsippycup.Leg, error) {
		engineLeg, appLeg, err := libsippycup.NewLegPair(request.CallContext, request.Format, 10)
		if err != nil {
			return nil, err
		}

		go func() {
			defer appLeg.Close()
			if err := appLeg.WriteState(request.CallContext, libsippycup.StateAnswered); err != nil {
				return
			}

			for {
				frame, err := appLeg.Read(request.CallContext)
				if err != nil {
					return
				}

				if err := appLeg.Write(request.CallContext, frame); err != nil {
					return
				}
			}
		}()

		return engineLeg, nil
	}

	config := &libsippycup.Config{
		Sources: []*libsippycup.Node{{Name: "app", Type: "inproc"}},
		Endpoints: []*libsippycup.Node{{
			Name: "echo", Type: "inproc", InProcess: echo,
		}},
		Routes: []*libsippycup.Route{{
			Name: "echo", Connect: &libsippycup.Connect{Endpoint: "echo"},
		}},
	}
	if err := config.Validate(); err != nil {
		panic(err)
	}

	engine := libsippycup.NewEngine(config)
	if err := engine.Start(); err != nil {
		panic(err)
	}
	defer engine.Close()

	format := libsippycup.Format{Codec: "pcm_s16le", Rate: 8000, Channels: 1}
	sourceLeg, appLeg, err := libsippycup.NewLegPair(ctx, format, 10)
	if err != nil {
		panic(err)
	}
	defer appLeg.Close()

	done := make(chan error, 1)
	go func() {
		done <- engine.Accept(ctx, "app", libsippycup.Request{}, sourceLeg)
	}()

	if _, err := appLeg.ReadState(ctx); err != nil {
		panic(err)
	}
	if err := appLeg.Write(ctx, libsippycup.Frame{Digit: '5'}); err != nil {
		panic(err)
	}

	frame, err := appLeg.Read(ctx)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Received digit %c\n", frame.Digit)

	appLeg.Close()
	<-done
}
Output:
Received digit 5

func (*Engine) Close

func (e *Engine) Close() error

Close cancels calls, closes listeners, and waits for all workers to exit. It has no overall deadline. Repeated calls are safe.

func (*Engine) Done

func (e *Engine) Done() <-chan struct{}

Done closes when the engine is canceled or a listener failure stops it. Call Close to release resources and wait for workers after Done closes.

func (*Engine) Reload

func (e *Engine) Reload(config *Config) error

Reload publishes a validated configuration for new calls without interrupting existing calls. Config must be a fresh, independent configuration tree and must remain immutable after this call. Reload retains listeners, SIP registrations, dialogs, sessions, and global resource accounting. Source names/types, binds, TLS, SIP transport/advertisement/registration settings, and HTTP header timeouts must stay unchanged; incompatible changes are rejected without modifying the running configuration. HTTP paths may change; existing session URLs continue to use their original configuration and authentication. Call Reload only after Start. Do not call it concurrently with Start or Close.

func (*Engine) Serve

func (e *Engine) Serve(ctx context.Context) error

Serve starts the engine and waits until ctx is canceled or Close is called. It closes all resources before returning. Normal shutdown returns nil. Call Serve at most once, and do not also call Start on the same engine.

func (*Engine) Start

func (e *Engine) Start() error

Start binds sources and starts registrations. Startup failure closes all resources already opened. Call Start at most once.

type Format

type Format struct {
	Codec    string `json:"codec"`
	Rate     int    `json:"sample_rate"`
	Channels int    `json:"channels"`
}

Format describes an audio encoding, sample rate in Hz, and channel count. PCM and Opus support mono or interleaved stereo; G.711 supports mono.

type Frame

type Frame struct {
	Format Format
	Data   []byte
	Digit  byte
}

Frame carries encoded audio or one DTMF event. A nonzero Digit denotes an event and takes precedence over Data. Opus Data is exactly one complete packet; its duration is derived from the TOC, not its byte length. For Opus, Channels describes the PCM layout expected by the consumer, not necessarily the packet encoding: a stereo stream may contain mono packets, which an Opus decoder duplicates into both channels. The packet TOC bit 0x04 identifies stereo encoding. Network readers report that encoded channel count; bridge writers use the destination stream format.

type ICEConfig

type ICEConfig struct {
	IncludeLoopback bool          `hcl:"include_loopback,optional"`
	Bind            string        `hcl:"bind,optional"`
	Interfaces      []string      `hcl:"interfaces,optional"`
	PortRange       []int         `hcl:"port_range,optional"`
	Policy          string        `hcl:"policy,optional"`
	Trickle         bool          `hcl:"trickle,optional"`
	Servers         []*ICEServer  `hcl:"server,block"`
	NATMappings     []*NATMapping `hcl:"nat_mapping,block"`
}

ICEConfig controls WebRTC candidate gathering and connectivity policy. It does not apply to SIP RTP sockets. Loopback candidates require IncludeLoopback or an explicit loopback Bind.

type ICEServer

type ICEServer struct {
	Name       string   `hcl:"name,label"`
	URLs       []string `hcl:"urls"`
	Credential string   `hcl:"credential,optional"`
}

ICEServer identifies STUN or TURN URLs and an optional named TURN credential.

type Leg

type Leg interface {
	Read(context.Context) (Frame, error)
	Write(context.Context, Frame) error
	Format() Format
	Close() error
}

Leg is one side of a call. Read and Write operate in opposite directions and may run concurrently; Close must interrupt blocked operations.

type LimitConfig

type LimitConfig struct {
	MaxCalls           int    `hcl:"max_calls,optional"`
	MaxPendingCalls    int    `hcl:"max_pending_calls,optional"`
	MaxConnections     int    `hcl:"max_connections,optional"`
	MaxProcesses       int    `hcl:"max_processes,optional"`
	MaxIdentityBytes   int    `hcl:"max_identity_bytes,optional"`
	MaxHTTPBodyBytes   int64  `hcl:"max_http_body_bytes,optional"`
	MediaQueueDuration string `hcl:"media_queue_duration,optional"`
}

LimitConfig bounds calls, pending setups, sockets, processes, and buffers. Zero numeric fields inherit defaults rather than disabling protection.

type Match

type Match struct {
	Source   string         `hcl:"source,optional"`
	Sources  []string       `hcl:"sources,optional"`
	Captures []*Capture     `hcl:"capture,block"`
	When     hcl.Expression `hcl:"when,optional"`
}

Match restricts a route by source, extracted captures, and an optional predicate.

type MemoryLeg

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

MemoryLeg is one end of a bounded, bidirectional in-process call. Writes are read by its peer. Audio buffers are copied on Write, so callers may reuse them after Write returns; readers own returned buffers. State notifications use a separate two-entry queue and never consume media capacity.

func (*MemoryLeg) Close

func (l *MemoryLeg) Close() error

Close closes both ends without waiting for queued frames to drain.

func (*MemoryLeg) Done

func (l *MemoryLeg) Done() <-chan struct{}

Done closes when either peer closes or the pair's context is canceled.

func (*MemoryLeg) Format

func (l *MemoryLeg) Format() Format

Format returns the pair's immutable media format.

func (*MemoryLeg) Read

func (l *MemoryLeg) Read(ctx context.Context) (Frame, error)

Read receives one media frame. Closure discards remaining queued frames.

func (*MemoryLeg) ReadState

func (l *MemoryLeg) ReadState(ctx context.Context) (CallState, error)

ReadState receives the next early/answered notification from the peer.

func (*MemoryLeg) Write

func (l *MemoryLeg) Write(ctx context.Context, f Frame) error

Write copies and sends one frame, applying backpressure when the queue is full. Digit frames carry native DTMF; audio must use the pair's negotiated format.

func (*MemoryLeg) WriteState

func (l *MemoryLeg) WriteState(ctx context.Context, state CallState) error

WriteState sends a monotonic call-state transition. Duplicates are ignored; returning from answered to early is an error.

type NATMapping

type NATMapping struct {
	Local  string `hcl:"local"`
	Public string `hcl:"public"`
}

NATMapping rewrites a local WebRTC host candidate to a configured public IP.

type Node

type Node struct {
	// InProcess creates one leg per call for an inproc endpoint. It is Go-only
	// and must be attached before validation. Sources use Engine.Accept instead.
	InProcess EndpointFunc

	Name            string              `hcl:"name,label"`
	Type            string              `hcl:"type"`
	Bind            string              `hcl:"bind,optional"`
	Path            string              `hcl:"path,optional"`
	URL             string              `hcl:"url,optional"`
	URI             string              `hcl:"uri,optional"`
	OutboundProxy   string              `hcl:"outbound_proxy,optional"`
	Address         string              `hcl:"address,optional"`
	Source          string              `hcl:"source,optional"`
	Transport       string              `hcl:"transport,optional"`
	Transports      []string            `hcl:"transports,optional"`
	UUID            string              `hcl:"uuid,optional"`
	Extended        bool                `hcl:"extended,optional"`
	EarlyMedia      string              `hcl:"early_media,optional"`
	Codecs          []string            `hcl:"codecs,optional"`
	Command         []string            `hcl:"command,optional"`
	PassEnvironment []string            `hcl:"pass_environment,optional"`
	Environment     map[string]string   `hcl:"environment,optional"`
	IO              string              `hcl:"io,optional"`
	Control         string              `hcl:"control,optional"`
	Origins         []string            `hcl:"origins,optional"`
	Auth            *AuthConfig         `hcl:"auth,block"`
	Transcode       *TranscodeConfig    `hcl:"transcode,block"`
	DTMF            *DTMFConfig         `hcl:"dtmf,block"`
	TLS             *TLSConfig          `hcl:"tls,block"`
	Advertise       *AdvertiseConfig    `hcl:"advertise,block"`
	RTP             *RTPConfig          `hcl:"rtp,block"`
	Opus            *OpusConfig         `hcl:"opus,block"`
	ICE             *ICEConfig          `hcl:"ice,block"`
	Registration    *RegistrationConfig `hcl:"registration,block"`
	Timeouts        *TimeoutConfig      `hcl:"timeouts,block"`
	Limits          *LimitConfig        `hcl:"limits,block"`
}

Node configures either a call source or an endpoint. Type determines which protocol-specific fields apply. Sources accept calls; endpoints create call legs. EarlyMedia selects disabled, native signaling, or answer-and-stream behavior. Defaults are native for SIP, answer for AudioSocket, and disabled for WebRTC. Native AudioSocket signaling requires Extended and explicit peer agreement. UUID optionally fixes the connection identity on TCP/WS AudioSocket endpoints. Exec endpoints inherit a minimal environment; PassEnvironment adds inherited names and Environment adds explicit values without exposing all daemon secrets.

type OpusConfig

type OpusConfig struct {
	Bitrate  int `hcl:"bitrate,optional"`
	Channels int `hcl:"channels,optional"`
}

OpusConfig controls locally encoded Opus. Bitrate defaults to 32000 bits/s. Channels defaults to one; two enables stereo. Encoding uses 48 kHz PCM and 20 ms packets. It does not enable FEC or DTX.

type RTPConfig

type RTPConfig struct {
	AllowPrivateDestinations bool             `hcl:"allow_private_destinations,optional"`
	Bind                     string           `hcl:"bind,optional"`
	Symmetric                *bool            `hcl:"symmetric,optional"`
	Keepalive                string           `hcl:"keepalive,optional"`
	STUNServer               string           `hcl:"stun_server,optional"`
	PortRange                []int            `hcl:"port_range,optional"`
	Advertise                *AdvertiseConfig `hcl:"advertise,block"`
}

RTPConfig controls SIP media sockets, NAT learning, keepalives, and advertisement. A nil Symmetric defaults to true; an explicit false enforces the SDP source. AllowPrivateDestinations permits unsolicited local-network media even when signaling comes from a public IP. Enable it only for trusted media topologies.

type RegistrationConfig

type RegistrationConfig struct {
	Registrar  string `hcl:"registrar"`
	AOR        string `hcl:"aor"`
	Credential string `hcl:"credential"`
	Expires    string `hcl:"expires,optional"`
}

RegistrationConfig maintains a SIP registration for a source. Registrar is the server URI; AOR is the account address of record.

type Reject

type Reject struct {
	Code   int    `hcl:"code,optional"`
	Reason string `hcl:"reason,optional"`
}

Reject terminates routing with a status code and reason.

type Request

type Request struct {
	ID       string
	Source   string
	Remote   string
	Identity any
	SIP      map[string]any
	HTTP     map[string]any
	Auth     *AuthIdentity
	// contains filtered or unexported fields
}

Request contains protocol metadata used to match routes and build call legs. Its HCL representation excludes reusable credentials and authorization headers.

type Route

type Route struct {
	Name    string   `hcl:"name,label"`
	Match   *Match   `hcl:"match,block"`
	Connect *Connect `hcl:"connect,block"`
	Reject  *Reject  `hcl:"reject,block"`
}

Route matches a request and either connects an endpoint or rejects the call. Routes are evaluated in declaration order; the first match wins.

type RuntimeConfig

type RuntimeConfig struct {
	Timeouts *TimeoutConfig `hcl:"timeouts,block"`
	Limits   *LimitConfig   `hcl:"limits,block"`
}

RuntimeConfig supplies default timeouts and resource limits for all nodes.

type StatefulLeg

type StatefulLeg interface {
	Leg
	ReadState(context.Context) (CallState, error)
	WriteState(context.Context, CallState) error
}

StatefulLeg adds native early/answered signaling to a Leg. State operations must honor context cancellation and Close, independently of media I/O.

type TLSConfig

type TLSConfig struct {
	CertificateFile string `hcl:"certificate_file,optional"`
	PrivateKeyFile  string `hcl:"private_key_file,optional"`
	CAFile          string `hcl:"ca_file,optional"`
	ServerName      string `hcl:"server_name,optional"`
	MinVersion      string `hcl:"min_version,optional"`
	ClientCAFile    string `hcl:"client_ca_file,optional"`
}

TLSConfig describes PEM identities, trust roots, and TLS policy.

type TimeoutConfig

type TimeoutConfig struct {
	Connect         string `hcl:"connect,optional"`
	Handshake       string `hcl:"handshake,optional"`
	Identity        string `hcl:"identity,optional"`
	Dial            string `hcl:"dial,optional"`
	MediaIdle       string `hcl:"media_idle,optional"`
	MaxCallDuration string `hcl:"max_call_duration,optional"`
	Shutdown        string `hcl:"shutdown,optional"`
}

TimeoutConfig contains quoted Go duration strings. Empty fields inherit runtime defaults. Only MediaIdle and MaxCallDuration may disable their limit with a zero duration.

type TranscodeConfig

type TranscodeConfig struct {
	Mode       string `hcl:"mode,optional"`
	Codec      string `hcl:"codec,optional"`
	SampleRate int    `hcl:"sample_rate,optional"`
	Channels   int    `hcl:"channels,optional"`
}

TranscodeConfig selects automatic conversion, a forced output format, or rejection of incompatible formats when Mode is never.

Jump to

Keyboard shortcuts

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