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 ¶
- Constants
- func AudioKind(rate int) (byte, error)
- func AudioRate(kind byte) (int, bool)
- func Handler(accept func(*Conn, *http.Request), opts ...Option) http.Handler
- func PCMFormat(kind byte) (rate, channels int, ok bool)
- func PCMKind(rate, channels int) (byte, error)
- func WritePacket(w io.Writer, p Packet) error
- type BasicAuth
- type CallState
- type Conn
- func (c *Conn) Close() error
- func (c *Conn) ReadPacket() (Packet, error)
- func (c *Conn) SetDeadline(t time.Time) error
- func (c *Conn) WriteAudio(rate int, pcm []byte) error
- func (c *Conn) WriteDTMF(d byte) error
- func (c *Conn) WriteIdentity(id Identity) error
- func (c *Conn) WritePCM(rate, channels int, pcm []byte) error
- func (c *Conn) WritePacket(p Packet) error
- func (c *Conn) WriteState(state CallState) error
- type Identity
- type Listener
- type MessageConn
- type Option
- type Packet
Examples ¶
Constants ¶
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 AudioRate ¶
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 ¶
Handler mounts AudioSocket on an existing HTTP server. The callback owns conn. Authenticate requests in middleware before calling this handler if desired.
func PCMFormat ¶
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 ¶
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 ¶
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 ¶
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.
func ParseState ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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) WriteIdentity ¶
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 ¶
WritePCM sends interleaved signed 16-bit little-endian PCM. Stereo requires WithExtended(true); mono uses standard AudioSocket packets.
func (*Conn) WritePacket ¶
WritePacket serializes a frame and enforces payload limits and identity validation. Use WriteAudio and WriteDTMF to validate those payload types.
func (*Conn) WriteState ¶
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 ¶
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"}
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 ¶
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 ¶
Accept waits for a connection, context cancellation, or listener closure. It does not consume the peer's identity packet. Concurrent calls are supported.
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 ¶
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 ¶
WithExtended enables JSON identities alongside standard UUIDs. It is off by default and does not change the three-byte AudioSocket frame header.
func WithHTTPClient ¶
WithHTTPClient selects the HTTP client for outgoing WebSocket handshakes. It has no effect on TCP connections or listeners.
func WithHTTPHeader ¶
WithHTTPHeader sets headers on an outgoing WebSocket handshake. Headers are cloned when the option is applied; servers ignore this option.
func WithMaxPayload ¶
WithMaxPayload bounds received and written frame payloads. Values outside 1 through MaxPayload select the protocol maximum.