spatiussdkgo

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 13, 2026 License: MIT Imports: 18 Imported by: 0

README

Spatius Golang SDK

codecov Go Report Card Go Reference

Go SDK for Spatius avatar sessions.

Install

go get github.com/spatius-ai/spatius-sdk-go

Quick Start

package main

import (
	"context"
	"log"
	"time"

	spatius "github.com/spatius-ai/spatius-sdk-go"
)

func main() {
	ctx := context.Background()

	session := spatius.NewAvatarSession(
		spatius.WithAPIKey("your-api-key"),
		spatius.WithAppID("your-app-id"),
		spatius.WithAvatarID("your-avatar-id"),
		spatius.WithExpireAt(time.Now().Add(5*time.Minute).UTC()),
		spatius.WithTransportFrames(func(data []byte, last bool) {
			// Handle animation frame bytes.
		}),
	)

	if err := session.Init(ctx); err != nil {
		log.Fatal(err)
	}
	defer session.Close()

	if _, err := session.Start(ctx); err != nil {
		log.Fatal(err)
	}

	audioBytes := []byte{} // Replace with mono PCM audio bytes.
	reqID, err := session.SendAudio(audioBytes, true)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("sent request %s", reqID)
}

Documentation

Detailed usage lives in Spatius docs.

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GenerateLogID

func GenerateLogID() (string, error)

GenerateLogID returns a log identifier in the format "YYYYMMDDHHMMSS_<nanoid>". The timestamp is generated in UTC and the nanoid suffix contains 12 characters.

Types

type AgoraEgressConfig

type AgoraEgressConfig struct {
	// ChannelName is the Agora channel name to join
	ChannelName string
	// Token is the Agora token for authentication (optional for testing)
	Token string
	// UID is the publisher UID in the channel (0 for auto-assign)
	UID uint32
	// PublisherID is the publisher identity/name
	PublisherID string
}

AgoraEgressConfig contains configuration for streaming to an Agora channel.

type AudioFormat

type AudioFormat string

AudioFormat identifies the audio encoding negotiated for a session.

const (
	// DefaultRegion is used when no region is provided.
	DefaultRegion = "us-west"

	// AudioFormatPCMS16LE sends mono 16-bit PCM bytes.
	AudioFormatPCMS16LE AudioFormat = "pcm_s16le"
	// AudioFormatOggOpus sends one continuous Ogg Opus stream per request ID.
	AudioFormatOggOpus AudioFormat = "ogg_opus"
)

type AvatarSDKError

type AvatarSDKError struct {
	Code         AvatarSDKErrorCode
	Message      string
	Phase        string
	ServerCode   string
	ConnectionID string
	ReqID        string
}

AvatarSDKError is an SDK error with a stable error code.

func NewAvatarSDKError

func NewAvatarSDKError(code AvatarSDKErrorCode, message string) *AvatarSDKError

NewAvatarSDKError creates a new AvatarSDKError.

func (*AvatarSDKError) Error

func (e *AvatarSDKError) Error() string

Error implements the error interface.

type AvatarSDKErrorCode

type AvatarSDKErrorCode string

AvatarSDKErrorCode represents stable error codes surfaced by the SDK. These codes are referenced by the v2 websocket API documentation.

const (
	// ErrorCodeSessionTokenExpired indicates the session token has expired.
	ErrorCodeSessionTokenExpired AvatarSDKErrorCode = "sessionTokenExpired"
	// ErrorCodeSessionTokenInvalid indicates the session token is invalid.
	ErrorCodeSessionTokenInvalid AvatarSDKErrorCode = "sessionTokenInvalid"
	// ErrorCodeAppIDUnrecognized indicates the app ID is not recognized.
	ErrorCodeAppIDUnrecognized AvatarSDKErrorCode = "appIDUnrecognized"
	// ErrorCodeInvalidRequest indicates the request payload is invalid.
	ErrorCodeInvalidRequest AvatarSDKErrorCode = "invalidRequest"
	// ErrorCodeInvalidEgressConfig indicates the egress configuration is invalid.
	ErrorCodeInvalidEgressConfig AvatarSDKErrorCode = "invalidEgressConfig"
	// ErrorCodeEgressUnavailable indicates the egress service is unavailable.
	ErrorCodeEgressUnavailable AvatarSDKErrorCode = "egressUnavailable"
	// ErrorCodeProtocolError indicates the websocket protocol exchange was invalid.
	ErrorCodeProtocolError AvatarSDKErrorCode = "protocolError"
	// ErrorCodeUnknown indicates an unknown error.
	ErrorCodeUnknown AvatarSDKErrorCode = "unknown"
)

type AvatarSession

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

AvatarSession represents an active avatar session configured via SessionOptions.

func NewAvatarSession

func NewAvatarSession(opts ...SessionOption) *AvatarSession

NewAvatarSession creates a new AvatarSession using the provided SessionOptions.

func (*AvatarSession) Close

func (s *AvatarSession) Close() error

Close closes the WebSocket connection and cleans up resources.

func (*AvatarSession) Config

func (s *AvatarSession) Config() SessionConfig

Config returns a copy of the session configuration.

func (*AvatarSession) Init

func (s *AvatarSession) Init(ctx context.Context) error

Init exchanges configuration credentials for a session token against the console API.

func (*AvatarSession) Interrupt

func (s *AvatarSession) Interrupt() (string, error)

Interrupt sends an interrupt signal to stop the current audio processing. Returns the request ID that was interrupted, or empty string if no request was active.

func (*AvatarSession) SendAudio

func (s *AvatarSession) SendAudio(audio []byte, end bool) (string, error)

SendAudio sends audio data to the server. Audio must match the session's negotiated format unless the internal Ogg Opus encoder is enabled.

func (*AvatarSession) Start

func (s *AvatarSession) Start(ctx context.Context) (string, error)

Start establishes WebSocket connection to the ingress endpoint and performs v2 handshake. Returns the connection ID for tracking this session.

type EncodedAudioChunk

type EncodedAudioChunk struct {
	Payload         []byte
	CompletedStream []byte
}

EncodedAudioChunk contains a newly encoded payload and the final stream bytes, when requested.

type LiveKitEgressConfig

type LiveKitEgressConfig struct {
	// URL is the LiveKit server URL (e.g., wss://livekit.example.com)
	URL string
	// APIKey is the deprecated LiveKit API key.
	APIKey string
	// APISecret is the deprecated LiveKit API secret.
	APISecret string
	// APIToken is the preferred pre-generated LiveKit access token.
	APIToken string
	// RoomName is the LiveKit room name to join
	RoomName string
	// PublisherID is the publisher identity in the room
	PublisherID string
	// ExtraAttributes are additional key-value attributes for the LiveKit participant.
	ExtraAttributes map[string]string
	// IdleTimeout is the egress connection idle timeout in seconds.
	IdleTimeout int32
}

LiveKitEgressConfig contains configuration for streaming to a LiveKit room.

type OggOpusApplication

type OggOpusApplication string

OggOpusApplication identifies the Opus encoder tuning profile.

const (
	// OggOpusApplicationAudio optimizes encoding for non-voice signals like music.
	OggOpusApplicationAudio OggOpusApplication = "audio"
	// OggOpusApplicationVoIP optimizes encoding for speech.
	OggOpusApplicationVoIP OggOpusApplication = "voip"
	// OggOpusApplicationRestrictedLowdelay optimizes encoding for low-latency use cases.
	OggOpusApplicationRestrictedLowdelay OggOpusApplication = "restricted_lowdelay"
)

type OggOpusEncoderConfig

type OggOpusEncoderConfig struct {
	FrameDurationMS int
	Application     OggOpusApplication
}

OggOpusEncoderConfig configures the optional client-side PCM to Ogg Opus encoder.

type OggOpusStreamEncoder

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

OggOpusStreamEncoder incrementally encodes mono PCM audio into a continuous Ogg Opus stream.

func NewOggOpusStreamEncoder

func NewOggOpusStreamEncoder(sampleRate int, bitrate int, config *OggOpusEncoderConfig, collectEncodedOutput bool) (*OggOpusStreamEncoder, error)

NewOggOpusStreamEncoder creates an encoder for PCM to Ogg Opus conversion.

func (*OggOpusStreamEncoder) Encode

func (e *OggOpusStreamEncoder) Encode(pcmData []byte, end bool) (EncodedAudioChunk, error)

Encode consumes PCM bytes and returns the next Ogg Opus payload fragment.

type SessionConfig

type SessionConfig struct {
	AvatarID           string
	APIKey             string
	AppID              string
	UseQueryAuth       bool // If true, send app/session credentials as URL query params (web-style auth). If false (default), send them as headers (mobile-style auth).
	ExpireAt           time.Time
	SampleRate         int
	Bitrate            int
	AudioFormat        AudioFormat
	OggOpusEncoder     *OggOpusEncoderConfig
	OnEncodedAudio     func(string, []byte)
	TransportFrames    func([]byte, bool)
	OnError            func(error)
	OnClose            func()
	Region             string
	ConsoleEndpointURL string
	IngressEndpointURL string
	LiveKitEgress      *LiveKitEgressConfig // If set, enables LiveKit egress mode - audio and animation are streamed to a LiveKit room via the egress service
	AgoraEgress        *AgoraEgressConfig   // If set, enables Agora egress mode - audio and animation are streamed to an Agora channel via the egress service
}

SessionConfig captures the configuration used to build an AvatarSession.

type SessionOption

type SessionOption func(*SessionConfig)

SessionOption applies a configuration change to SessionConfig.

func WithAPIKey

func WithAPIKey(apiKey string) SessionOption

WithAPIKey sets the API key used for authenticating the session.

func WithAgoraEgress

func WithAgoraEgress(config *AgoraEgressConfig) SessionOption

WithAgoraEgress enables Agora egress mode for the session. When set, audio and animation data are streamed to an Agora channel via the egress service instead of being returned through the WebSocket connection.

func WithAppID

func WithAppID(appID string) SessionOption

WithAppID sets the application identifier associated with the session.

func WithAudioFormat

func WithAudioFormat(audioFormat AudioFormat) SessionOption

WithAudioFormat sets the negotiated audio input format.

func WithAvatarID

func WithAvatarID(avatarID string) SessionOption

WithAvatarID sets the avatar identifier used for the session.

func WithBitrate

func WithBitrate(bitrate int) SessionOption

WithBitrate sets the audio bitrate (if applicable to the selected audio format).

func WithConsoleEndpointURL

func WithConsoleEndpointURL(endpointURL string) SessionOption

WithConsoleEndpointURL overrides the default console endpoint URL used by the session.

func WithExpireAt

func WithExpireAt(expireAt time.Time) SessionOption

WithExpireAt sets the expiration time of the session.

func WithIngressEndpointURL

func WithIngressEndpointURL(endpointURL string) SessionOption

WithIngressEndpointURL overrides the default ingress endpoint URL used by the session.

func WithLiveKitEgress

func WithLiveKitEgress(config *LiveKitEgressConfig) SessionOption

WithLiveKitEgress enables LiveKit egress mode for the session. When set, audio and animation data are streamed to a LiveKit room via the egress service instead of being returned through the WebSocket connection.

func WithOggOpusEncoder

func WithOggOpusEncoder(config *OggOpusEncoderConfig) SessionOption

WithOggOpusEncoder enables client-side PCM to Ogg Opus encoding for OGG_OPUS sessions.

func WithOnClose

func WithOnClose(handler func()) SessionOption

WithOnClose registers a handler that is called when the session closes.

func WithOnEncodedAudio

func WithOnEncodedAudio(handler func(string, []byte)) SessionOption

WithOnEncodedAudio registers a handler invoked when internal Ogg Opus encoding completes.

func WithOnError

func WithOnError(handler func(error)) SessionOption

WithOnError registers a handler that receives errors emitted by the session.

func WithRegion

func WithRegion(region string) SessionOption

WithRegion sets the Spatius region used to compose endpoint URLs. Explicit console or ingress endpoint URLs override the region-derived defaults.

func WithSampleRate

func WithSampleRate(sampleRate int) SessionOption

WithSampleRate sets the audio sample rate in Hz.

func WithTransportFrames

func WithTransportFrames(handler func([]byte, bool)) SessionOption

WithTransportFrames registers a handler invoked when transport frames are emitted.

func WithUseQueryAuth

func WithUseQueryAuth(useQueryAuth bool) SessionOption

WithUseQueryAuth chooses whether websocket auth is sent via URL query params (web) or headers (mobile).

Directories

Path Synopsis
examples
connection-pool command
http-service command
proto

Jump to

Keyboard shortcuts

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