audiosocket

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: 15 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

audiosocket

← Sippycup

A reusable Go implementation of Asterisk AudioSocket over TCP/TLS and WebSocket. It can wrap existing connections or dial and listen itself. It does not depend on the Sippycup engine or its HCL configuration.

Dialing

Import github.com/ronsor/sippycup/audiosocket independently of the engine. It provides Wrap for existing connections, Dial and Listen for TCP/TLS and WS/WSS, identity parsing, and audio/DTMF packet helpers. For example, in a function with a context ctx:

conn, err := audiosocket.Dial(ctx, "ws://127.0.0.1:8080/audio",
    audiosocket.WithExtended(true), audiosocket.WithContext(ctx))
if err != nil {
    return err
}
defer conn.Close()

err = conn.WriteIdentity(audiosocket.Identity{
    JSON: json.RawMessage(`{"uuid":"550e8400-e29b-41d4-a716-446655440000","destination":"+18005550100"}`),
})
if err != nil {
    return err
}

The snippet uses encoding/json and returns errors from its containing function. After sending the identity, use WriteAudio(rate, pcm) for mono signed 16-bit little-endian PCM, WriteDTMF(digit) for digits, and ReadPacket() for incoming frames. WritePacket can send a KindHangup packet to signal hangup before closing.

For standard AudioSocket, omit WithExtended(true) and provide the 16 UUID bytes in Identity.UUID. The library does not generate a UUID or add one to supplied JSON: callers supply the complete identity. ParseIdentity populates Identity.UUID for either format and preserves a copy of the JSON when present.

Listening and Wrapping

Listen accepts tcp://, tls://, ws://, and wss:// addresses. A WebSocket URL selects the request path. TLS listeners require a certificate through WithTLS. For example, inside a function with context ctx:

listener, err := audiosocket.Listen("tcp://127.0.0.1:9019",
    audiosocket.WithExtended(true), audiosocket.WithContext(ctx))
if err != nil {
    return err
}
defer listener.Close()

conn, err := listener.Accept(ctx)
if err != nil {
    return err
}
defer conn.Close()

packet, err := conn.ReadPacket()
if err != nil {
    return err
}
if packet.Kind != audiosocket.KindID {
    return fmt.Errorf("expected an AudioSocket identity")
}
identity, err := audiosocket.ParseIdentity(packet.Payload, true)
if err != nil {
    return err
}
fmt.Printf("connection UUID bytes: %x\n", identity.UUID)

This example uses fmt and accepts one connection. A server normally loops over Accept and handles each connection independently. Accepted connections remain open when the listener closes, unless their own context is canceled.

Use Wrap(net.Conn, ...) for an existing stream, WrapWebSocket(MessageConn, ...) for an existing WebSocket, or Handler(callback, ...) to mount AudioSocket on your HTTP server. The callback owns the connection. Apply authentication middleware before Handler; the library does not authenticate callers itself.

Connection Behavior

  • Wrapping transfers ownership: Close closes the underlying transport.
  • Connections support one reader and concurrent serialized writers.
  • The context passed to Dial bounds connection setup. Use WithContext to bind the connection lifetime; canceling that context interrupts I/O.
  • SetDeadline applies to stream connections. Use context cancellation for WebSockets.
  • WithMaxPayload bounds frame payloads; the wire maximum is 65535 bytes.
  • Wrap tries to enable TCP_NODELAY, including through TLS and wrappers exposing NetConn. Socket-option errors are ignored. Opaque WebSocket transports retain their HTTP stack's socket settings.
  • WithTLS, WithHTTPClient, and WithHTTPHeader configure outgoing TLS and HTTP handshakes. Do not mutate supplied TLS/client configuration during use.

Conn.ReadPacket and Conn.WritePacket validate known packet types. The package-level ReadPacket and WritePacket helpers provide low-level framing over readers/writers.

Extended Identities and WebSocket Framing

Standard AudioSocket starts with a KindID packet containing a 16-byte UUID. With extended = true, a JSON KindID must start with {, exceed 16 bytes, and contain a uuid string in standard hyphenated UUID format. Every 16-byte payload is treated as a binary UUID, even if its first byte is {. Other payloads are rejected.

Example JSON identity:

{
  "uuid": "550e8400-e29b-41d4-a716-446655440000",
  "destination": "+18005550100",
  "basic_auth": {"username": "alice", "password": "secret"}
}

JSON uses the normal three-byte AudioSocket frame header. The wire payload limit is 65535 bytes; the engine additionally applies its configured identity limit. Over WebSocket, each binary message contains exactly one complete AudioSocket packet, including its header; the subprotocol name is audiosocket.

The required uuid is a string in xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx format. Additional metadata is application-defined. Identity.BasicAuth() extracts the optional credentials without verifying or removing them; authentication and redaction are the application's responsibility.

AudioSocket over WebSocket uses the audiosocket subprotocol and is distinct from Asterisk's chan_websocket protocol.

Stereo PCM

Stereo PCM is a Sippycup extension requiring WithExtended(true) on both peers. The standard mono kinds 0x10–0x18 are unchanged. Stereo kinds 0x20–0x28 use the same rate order: 8000, 12000, 16000, 24000, 32000, 44100, 48000, 96000, and 192000 Hz. Each payload contains interleaved signed 16-bit little-endian samples in left/right order, with a length divisible by four. The three-byte header and WebSocket framing are unchanged; the length counts payload bytes.

Use conn.WritePCM(rate, 2, pcm) to send stereo and PCMFormat(packet.Kind) to read its rate and channel count. PCMKind(rate, channels) constructs either mono or stereo packet kinds. Existing WriteAudio, AudioKind, and AudioRate retain their mono semantics. Conn rejects stereo in standard mode and rejects incomplete PCM sample frames on reads and writes. The low-level free functions ReadPacket and WritePacket still only handle framing.

Extended mode permits stereo but does not negotiate it or require it. Configure stereo output explicitly on both applications as needed; mono packets are still accepted. An ordinary Asterisk AudioSocket peer does not support these kinds.

Native Early Media

Native early-media signaling adds KindState (0x02) with a one-byte payload: 0 means early and 1 means answered. Both peers must explicitly enable this profile. extended = true alone does not require state messages. These extensions are specific to Sippycup and are not part of standard Asterisk AudioSocket.

WriteState(StateEarly) and WriteState(StateAnswered) send these messages. Applications manage call-state transitions; the library does not automatically answer a connection or decide when early audio becomes answered audio.

Sippycup Engine Integration

The following behavior belongs to the engine, not the raw AudioSocket library:

The incoming JSON uuid field is required; other fields are optional. basic_auth is removed before metadata is exposed to routes. Outgoing extended identities automatically include uuid, even with a custom connect.identity. Set uuid = "550e8400-e29b-41d4-a716-446655440000" on an AudioSocket endpoint to use that fixed UUID on every connection; otherwise a fresh UUID is generated. The endpoint UUID overrides any uuid in the custom identity expression and applies to binary identities too.

The engine's default identity limit is 8192 bytes, configurable with limits.max_identity_bytes. See the metadata forwarding example, SIP dialing proxy, and early-media guide.

Tests and API Reference

From the repository root:

go test ./audiosocket
go doc ./audiosocket

Tests use Go and loopback sockets; no external server or executable is required. See the executable examples and API source.

Documentation

Overview

Package audiosocket implements Asterisk AudioSocket over TCP and WebSocket. Each WebSocket binary message contains exactly one complete AudioSocket packet. Extended mode permits a JSON object in KindID when the payload starts with '{', exceeds 16 bytes, and contains a uuid string. All 16-byte identities are binary UUIDs. KindState is an opt-in extension for peers that distinguish early and answered audio. WithExtended permits it but does not automatically send state messages. Extended mode also permits stereo PCM kinds 0x20–0x28; see PCMKind and WritePCM.

Index

Examples

Constants

View Source
const (
	// KindHangup ends a session and has an empty payload.
	KindHangup byte = 0x00
	// KindID carries a binary UUID, or JSON in extended mode.
	KindID byte = 0x01
	// KindState carries one CallState byte in the opt-in extended signaling profile.
	// It is a sippycup extension, not part of the Asterisk AudioSocket protocol.
	KindState byte = 0x02
	// KindDTMF carries one ASCII digit.
	KindDTMF byte = 0x03
	// KindError carries a peer-defined error payload.
	KindError byte = 0xff
	// MaxPayload is the largest payload representable by the wire length field.
	MaxPayload = 65535
	// Subprotocol is the AudioSocket WebSocket subprotocol name.
	Subprotocol = "audiosocket"
)

Variables

This section is empty.

Functions

func AudioKind

func AudioKind(rate int) (byte, error)

AudioKind returns the packet kind for a supported mono PCM sample rate.

func AudioRate

func AudioRate(kind byte) (int, bool)

AudioRate returns the PCM sample rate for an audio packet kind. The boolean is false for identity, DTMF, control, and unknown packet kinds.

func Handler

func Handler(accept func(*Conn, *http.Request), opts ...Option) http.Handler

Handler mounts AudioSocket on an existing HTTP server. The callback owns conn. Authenticate requests in middleware before calling this handler if desired.

func PCMFormat

func PCMFormat(kind byte) (rate, channels int, ok bool)

PCMFormat returns the sample rate and channel count for a PCM packet kind. The boolean is false for non-audio and unknown packet kinds.

func PCMKind

func PCMKind(rate, channels int) (byte, error)

PCMKind returns the packet kind for mono or stereo signed 16-bit PCM. Stereo uses the extended protocol's 0x20–0x28 range at the same rates as mono.

func WritePacket

func WritePacket(w io.Writer, p Packet) error

WritePacket writes one complete frame, handling short writes. It validates the wire length only; use Conn methods for identity and media validation.

Example
package main

import (
	"bytes"
	"fmt"
	"log"

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

func main() {
	var wire bytes.Buffer
	err := audiosocket.WritePacket(&wire, audiosocket.Packet{
		Kind:    audiosocket.KindDTMF,
		Payload: []byte{'5'},
	})
	if err != nil {
		log.Fatal(err)
	}

	packet, err := audiosocket.ReadPacket(&wire, audiosocket.MaxPayload)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("kind=%#x digit=%s\n", packet.Kind, packet.Payload)
}
Output:
kind=0x3 digit=5

Types

type BasicAuth

type BasicAuth struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

BasicAuth carries credentials in an extended identity's basic_auth field. The password is plaintext; use a protected transport when sending credentials.

type CallState

type CallState byte

CallState distinguishes pre-answer audio from an answered call. Peers must explicitly agree to state signaling; enabling JSON identities alone does not require them to send these messages.

const (
	// StateEarly starts early media while the downstream call remains pending.
	StateEarly CallState = 0
	// StateAnswered ends early media, or answers directly without an early phase.
	StateAnswered CallState = 1
)

func ParseState

func ParseState(p Packet) (CallState, error)

ParseState validates and decodes a KindState packet.

type Conn

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

Conn permits one reader and concurrent serialized writers. Close interrupts I/O. Wrapping a connection transfers ownership: Close closes the underlying transport.

func Dial

func Dial(ctx context.Context, address string, opts ...Option) (*Conn, error)

Dial establishes tcp://, tls://, ws://, or wss:// connections. The address must include a host and appropriate port; WebSocket addresses may have paths. The context bounds dialing, not the returned connection lifetime; use WithContext for that. Call WriteIdentity after dialing.

func Wrap

func Wrap(c net.Conn, opts ...Option) *Conn

Wrap takes ownership of a stream connection and adds AudioSocket framing. It attempts to enable TCP_NODELAY, including through TLS and wrappers exposing NetConn. Unsupported transports and socket-option errors are ignored. It does not read or write an identity automatically.

func WrapWebSocket

func WrapWebSocket(c MessageConn, opts ...Option) *Conn

WrapWebSocket takes ownership of a message connection. Each binary message must contain exactly one AudioSocket frame. It sets the read limit when wrapping a coder/websocket connection.

func (*Conn) Close

func (c *Conn) Close() error

Close interrupts I/O and closes the underlying transport. It is safe to call concurrently and repeatedly. It does not send an AudioSocket hangup frame.

func (*Conn) ReadPacket

func (c *Conn) ReadPacket() (Packet, error)

ReadPacket reads and validates one frame. It validates known identity, DTMF, audio, and hangup payloads; unknown packet kinds are returned unchanged. Only one goroutine may read at a time.

func (*Conn) SetDeadline

func (c *Conn) SetDeadline(t time.Time) error

SetDeadline sets stream read and write deadlines. A zero time clears them. WebSocket connections return an error; configure their lifetime with WithContext instead.

func (*Conn) WriteAudio

func (c *Conn) WriteAudio(rate int, pcm []byte) error

WriteAudio sends mono signed 16-bit little-endian PCM at the given rate. The payload must contain whole samples and fit in a single frame.

func (*Conn) WriteDTMF

func (c *Conn) WriteDTMF(d byte) error

WriteDTMF sends one digit: 0-9, *, #, or A-D.

func (*Conn) WriteIdentity

func (c *Conn) WriteIdentity(id Identity) error

WriteIdentity sends JSON when present, otherwise the 16-byte UUID. Sending JSON requires WithExtended(true), a leading brace, more than 16 bytes, and a valid uuid string. Protocol users should send identity first.

func (*Conn) WritePCM

func (c *Conn) WritePCM(rate, channels int, pcm []byte) error

WritePCM sends interleaved signed 16-bit little-endian PCM. Stereo requires WithExtended(true); mono uses standard AudioSocket packets.

func (*Conn) WritePacket

func (c *Conn) WritePacket(p Packet) error

WritePacket serializes a frame and enforces payload limits and identity validation. Use WriteAudio and WriteDTMF to validate those payload types.

func (*Conn) WriteState

func (c *Conn) WriteState(state CallState) error

WriteState sends an extended call-state message. Native-signaling servers send StateEarly before early audio and StateAnswered before answered audio. Sending StateAnswered directly is valid; transitioning back to early is not.

type Identity

type Identity struct {
	UUID [16]byte
	JSON json.RawMessage
}

Identity holds either a standard binary UUID or an extended JSON object. When JSON is nonempty, WriteIdentity sends it instead of UUID.

func ParseIdentity

func ParseIdentity(b []byte, extended bool) (Identity, error)

ParseIdentity decodes a 16-byte binary UUID or, when extended is true, a JSON object longer than 16 bytes starting with '{' and containing a canonical UUID string in uuid. JSON data is copied and UUID is populated for either format.

Example
package main

import (
	"fmt"
	"log"

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

func main() {
	identity, err := audiosocket.ParseIdentity(
		[]byte(`{"uuid":"550e8400-e29b-41d4-a716-446655440000","destination":"1234"}`),
		true,
	)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(string(identity.JSON))
}
Output:
{"uuid":"550e8400-e29b-41d4-a716-446655440000","destination":"1234"}

func (Identity) BasicAuth

func (id Identity) BasicAuth() (*BasicAuth, error)

BasicAuth returns credentials from a JSON identity, or nil when absent. It does not verify the credentials.

type Listener

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

Listener accepts framed AudioSocket connections over TCP, TLS, or WebSocket. Accepted connections belong to the caller and survive listener closure.

func Listen

func Listen(address string, opts ...Option) (*Listener, error)

Listen binds a tcp://, tls://, ws://, or wss:// address. Port zero selects an available port. TLS listeners require WithTLS with a server certificate. WebSocket addresses select a path, defaulting to /. Close releases the listener.

func (*Listener) Accept

func (l *Listener) Accept(ctx context.Context) (*Conn, error)

Accept waits for a connection, context cancellation, or listener closure. It does not consume the peer's identity packet. Concurrent calls are supported.

func (*Listener) Addr

func (l *Listener) Addr() net.Addr

Addr returns the actual bound address, including an automatically chosen port.

func (*Listener) Close

func (l *Listener) Close() error

Close stops accepting connections and releases the listening socket. It is safe to call repeatedly; accepted connections must be closed separately.

type MessageConn

type MessageConn interface {
	Read(context.Context) (websocket.MessageType, []byte, error)
	Write(context.Context, websocket.MessageType, []byte) error
	Close(websocket.StatusCode, string) error
}

MessageConn is satisfied by *websocket.Conn. Reads must yield complete messages.

type Option

type Option func(*options)

Option configures an AudioSocket connection or listener.

func WithContext

func WithContext(ctx context.Context) Option

WithContext sets the lifetime context for connections and listener accepts. Without it, connections use context.Background. Dial's context controls connection establishment separately. Call Close to release owned resources, including listener sockets, even after cancellation.

func WithExtended

func WithExtended(v bool) Option

WithExtended enables JSON identities alongside standard UUIDs. It is off by default and does not change the three-byte AudioSocket frame header.

func WithHTTPClient

func WithHTTPClient(c *http.Client) Option

WithHTTPClient selects the HTTP client for outgoing WebSocket handshakes. It has no effect on TCP connections or listeners.

func WithHTTPHeader

func WithHTTPHeader(h http.Header) Option

WithHTTPHeader sets headers on an outgoing WebSocket handshake. Headers are cloned when the option is applied; servers ignore this option.

func WithMaxPayload

func WithMaxPayload(n int) Option

WithMaxPayload bounds received and written frame payloads. Values outside 1 through MaxPayload select the protocol maximum.

func WithTLS

func WithTLS(c *tls.Config) Option

WithTLS supplies TLS settings for tls and wss transports. For outgoing WebSockets, an explicit WithHTTPClient takes precedence. The configuration is not cloned and must not be mutated while in use.

type Packet

type Packet struct {
	Kind    byte
	Payload []byte
}

Packet is an AudioSocket frame. Payload excludes the three-byte wire header. Read operations return payload storage owned by the caller.

func ReadPacket

func ReadPacket(r io.Reader, max int) (Packet, error)

ReadPacket reads a single bounded, length-prefixed packet. The returned payload belongs to the caller. max <= 0 means the protocol maximum.

Jump to

Keyboard shortcuts

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