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 ¶
- func DialCommand(ctx context.Context, config *Config, name, to string, rate int, ...) error
- func NewLegPair(ctx context.Context, format Format, capacity int) (*MemoryLeg, *MemoryLeg, error)
- type AdvertiseConfig
- type AuthConfig
- type AuthIdentity
- type Call
- type CallState
- type Capture
- type Config
- type Connect
- type Credential
- type CredentialSet
- type DTMFConfig
- type DigestConfig
- type EndpointFunc
- type EndpointRequest
- type Engine
- type Format
- type Frame
- type ICEConfig
- type ICEServer
- type Leg
- type LimitConfig
- type Match
- type MemoryLeg
- func (l *MemoryLeg) Close() error
- func (l *MemoryLeg) Done() <-chan struct{}
- func (l *MemoryLeg) Format() Format
- func (l *MemoryLeg) Read(ctx context.Context) (Frame, error)
- func (l *MemoryLeg) ReadState(ctx context.Context) (CallState, error)
- func (l *MemoryLeg) Write(ctx context.Context, f Frame) error
- func (l *MemoryLeg) WriteState(ctx context.Context, state CallState) error
- type NATMapping
- type Node
- type OpusConfig
- type RTPConfig
- type RegistrationConfig
- type Reject
- type Request
- type Route
- type RuntimeConfig
- type StatefulLeg
- type TLSConfig
- type TimeoutConfig
- type TranscodeConfig
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 ¶
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 ¶
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.
type CallState ¶
type CallState uint8
CallState distinguishes provisional media from an answered call.
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.
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 ¶
NewEngine creates an idle engine from a validated configuration. It opens no listeners until Start.
func (*Engine) Accept ¶
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 ¶
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 ¶
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.
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 ¶
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) Done ¶
func (l *MemoryLeg) Done() <-chan struct{}
Done closes when either peer closes or the pair's context is canceled.
func (*MemoryLeg) ReadState ¶
ReadState receives the next early/answered notification from the peer.
type NATMapping ¶
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 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.