Skip to content

Server Go SDK API reference ​

The TiRTC server Go SDK is used to build custom RTC services. This page lists the commonly used public Go APIs. The complete definitions are in the source under tirtc-service-sdk/pkg; for the signing algorithm, see the tirtcxauth authentication specification.

Stream ID conventions ​

Every StreamID parameter on this page follows the same rules: the range is 0..15, and it identifies one stream in one sending direction of one connection. For the same stream in the same direction, the ID used by the sender must match the subscription or receive configuration on the receiver; within one sending direction, different audio and video streams use different IDs, and audio and video cannot share an ID. The opposite direction uses an independent ID space and may reuse the same value.

The companion client API Samples and DevTools CLI use 10 for device-side audio, 11 for device-side video, and 14 for client talkback audio. These are only example values for direct integration testing, not IDs reserved or fixed by the SDK. Real projects may use other valid values, but must change the sender and receiver in the corresponding direction together.

API list ​

PackageAPIDescription
tirtcxInit / StartInitialize and start the process-wide TiRTC engine
tirtcxStop / UninitStop and release the process-wide TiRTC engine
tirtcxSetNativeLogLevelSet the log level of the TiRTC C library
tirtcxSetAudioRedundancyLossThresholdSet the global audio redundancy packet-loss threshold
tirtcxGetVersionGet the TiRTC C library version
tirtcxauthNewEd25519TokenIssuerCreate a token issuer
tirtcxauthNewEd25519TokenVerifierCreate a token verifier
tirtcxauthBearerInterceptorCreate an HTTP bearer authentication interceptor
tirtcxauthClaimsFromContextRead the verified Claims from a request
tirtcxNewWhipAcceptorCreate a WHIP Acceptor without an authentication policy
tirtcxWhipAcceptor.WhipAcceptAccept an SDP Offer and create a WHIP Session
tirtcxWhipSessionManage a pending or connected session
tirtcxConnAn established TiRTC connection object. Handles media, command, and connection events.
whipechoNewHTTPAdapterCreate an embeddable Echo HTTP adapter

SDK lifecycle ​

go
func Init() error
func Start(ctx context.Context) error
func Stop()
func Uninit()
func SetNativeLogLevel(level int)
func GetVersion() string

A process initializes only one TiRTC engine. The call order is:

  1. If you need to adjust the native library log level, call SetNativeLogLevel before initialization.
  2. Call Init, then use other tirtcx APIs only after it succeeds.
  3. Call Start(ctx) and wait for the system to finish starting. ctx must not be nil; a timeout or cancellation returns the corresponding Context error.
  4. On exit, close the business sessions first, then call Stop and Uninit in order.

GetVersion returns the version of the TiRTC C library currently loaded, which is useful for startup logs and troubleshooting.

Redundant transmission settings ​

SetAudioRedundancyLossThreshold ​

go
func SetAudioRedundancyLossThreshold(percent int) int

When the service sends real-time audio, the SDK can include earlier frames in the current packet to help the peer recover lost audio. This increases outgoing traffic. In v2.6.3, the default packet-loss threshold is 10%. The SDK clamps inputs below 0 to 0 and above 100 to 100.

Effective thresholdSender behavior
0%Always attempt to include redundant audio.
1–99%Attempt redundancy only when the peer's loss report is valid, has not expired, and reports loss strictly above the threshold. At the default setting, exactly 10% loss does not trigger redundancy.
100%Disable audio redundancy.

Whether a packet carries redundant audio also depends on peer protocol support, available audio history, and the packet size limit (MTU).

This setting applies to all TGTRP connections in the process. The function has no internal locking. To change the threshold, call it serially after tirtcx.Init() succeeds and before tirtcx.Start(), so it cannot run concurrently with connection setup or audio I/O.

The return value is the effective percentage (0–100), including 0 for an applied threshold of 0%. Check for a negative value first. A return value of -1 means the setting did not take effect. Check that the build uses -tags tirtc_clib (omitting it selects the stub) and that the native libraries match and support this function. The following example sets the threshold to 20%:

go
applied := tirtcx.SetAudioRedundancyLossThreshold(20)
if applied < 0 {
    return fmt.Errorf("audio redundancy threshold unavailable")
}

Token and HTTP authentication ​

BearerInterceptor ​

go
func BearerInterceptor(
    service string,
    verifier TokenVerifier,
    observers ...AuthObserver,
) HTTPInterceptor

The interceptor reads the token from Authorization: Bearer <token> and verifies the signature and Scope with the full raw Query of the request.

  • Missing token: returns 401 Unauthorized.
  • Invalid token: returns 403 Forbidden.
  • Invalid configuration: returns 500 Internal Server Error.
  • Successful verification: puts a copy of TokenClaims into the request Context, then calls the next Handler.

A business Handler can read the verified identity:

go
claims, ok := tirtcxauth.ClaimsFromContext(r.Context())

TokenClaims fields:

FieldMeaning
SubjectThe delegated device ID
ScopeThe access scope bound to the service name and normalized Query
IssuerThe Custom RTC Key ID that issued the token
IssuedAt / ExpiresAtIssue time and expiry time in Unix seconds

A token can be reused until exp expires, and tirtcxauth itself performs no anti-replay check. The device SDK protects the whole TiRtcWhipConnect call automatically, so that call cannot be replayed. To prevent direct replay of requests to a custom RTC service, it is recommended to add a one-time business parameter to the peer_id Query and have the custom RTC service redeem it after first use.

Use this interceptor for the POST that creates a session, not for DELETE <Location>.

Token issuing ​

go
issuer, err := tirtcxauth.NewEd25519TokenIssuer(privateKeys)
token, err := issuer.Issue(
    service,
    customRtcKeyID,
    deviceID,
    rawQuery,
    ttl,
)

rawQuery is the query string of peer_id. The SDK normalizes the Query as specified.

WHIP integration ​

NewWhipAcceptor ​

go
func NewWhipAcceptor(candidate string) *WhipAcceptor

Creates an Acceptor without an authentication policy. When candidate is empty, the SDK default address is used; set it only when you need to announce a different public address.

WhipAcceptor.WhipAccept ​

go
func (a *WhipAcceptor) WhipAccept(
    ctx context.Context,
    offer []byte,
    eventOptions ConnEventOptions,
) (*WhipSession, error)

ctx controls only the stage that waits synchronously for the SDP Answer. Cancelling the request Context after the HTTP Handler returns the Answer does not cancel the subsequent connection establishment.

Authentication must be completed before calling this method. The application is responsible for the session ID, Location, the registry, and the DELETE policy.

Session lifecycle ​

WhipSession.AnswerSDP ​

go
func (s *WhipSession) AnswerSDP() []byte

Returns a copy of the SDP Answer for the HTTP 201 Created response.

WhipSession.WaitConn ​

go
func (s *WhipSession) WaitConn(ctx context.Context) (*Conn, error)

Can be called concurrently and repeatedly; every waiter gets the same final result. Each waiter has its own Context, and one waiter timing out or being cancelled does not close the session.

WhipSession.Close ​

go
func (s *WhipSession) Close() error

Closes a pending or connected session. This method can be called repeatedly.

Connection API ​

MethodDescription
Events()Returns the enabled event channels
Done()Closed after the connection disconnects normally or fails
Err()Returns the termination error after Done() is closed; returns nil for a normal disconnect
EventStats()Returns the cumulative number of dropped events
SendAudio / SendVideo / SendMessageSends media or message frames
SendCommandSends a command
RequestKeyFrameRequests a key frame
SubscribeAudio / SubscribeVideoSubscribes to media streams
UnsubscribeAudio / UnsubscribeVideoCancels a media stream subscription
Close()Disconnects

FrameInfo and media types ​

go
type FrameInfo struct {
    StreamID uint8
    Media    MediaType
    Flags    uint8
    Ts       uint32
    Length   uint32
}
FieldDescription
StreamIDValue 0 to 15; within one connection and one sending direction, different audio and video streams use different IDs, and audio and video cannot reuse the same ID
MediaFrame codec, with the values in the table below
FlagsFor audio, the sample specification: 0=8 kHz/16 bit/mono, 1=16 kHz/16 bit/mono, 2=8 kHz/16 bit/stereo, 3=16 kHz/16 bit/stereo; for video, bit 0 marks a key frame
TsA 32-bit timestamp in milliseconds; it should increase monotonically within the same media stream and may wrap naturally
LengthThe number of Payload bytes of a received frame; when sending, the SDK fills it in from the data length, so the caller does not set it
ConstantContent
MediaMessageA message inside a media stream
AudioPCM / AudioALaw / AudioOpus / AudioAMRAudio frames of the corresponding codec
AudioAACAAC-LC audio; each frame Payload contains one complete ADTS frame
VideoJPEG / VideoH264 / VideoH265Video frames of the corresponding codec

SendAudio, SendVideo, and SendMessage copy the Payload before returning, so the caller can reuse the input slice after the call returns. Received event frames are also owned by the Go side, so a consumer can read them after the callback returns. The specific codec parameters must match what the device side agreed on.

When calling SendAudio to send AudioAAC, pass one AAC-LC encoded frame including the complete ADTS header each time. Keep the ADTS header, do not split one frame or concatenate several frames; the sample rate and channel count declared in the ADTS header must match the actual audio and FrameInfo.Flags, and the frame length declared by ADTS must match the byte count of this Payload.

ConnEventOptions ​

ConnEventOptions configures the buffer capacity of each connection event channel and the synchronous Handlers that process subscription requests from the peer.

FieldWhat it configures
AudioBuffer / VideoBuffer / MessageBuffer / CommandBufferSets the buffer capacity of the corresponding data event channel
ErrorBuffer / DisconnectedBufferSets the buffer capacity of the connection error and disconnect event channels
RequestKeyFrameBufferSets the buffer capacity of the key frame request event channel
UnsubscribeVideoBuffer / UnsubscribeAudioBufferSets the buffer capacity of the unsubscribe event channels
SubscribeVideoHandler / SubscribeAudioHandlerSets the synchronous handler for subscription requests from the peer

The value of each *Buffer field is the maximum number of events the corresponding event channel can buffer. A value of 0 or less disables that event; a positive value below MinEventBufferSize creates the channel at the minimum size. A subscription Handler returning 0 means accept, and a non-zero value means reject. Handlers run in a native callback and must return quickly; when a Handler is not configured or panics it is treated as 0.

Echo HTTP API ​

NewHTTPAdapter ​

go
func NewHTTPAdapter(
    acceptor Acceptor,
    locationPrefix string,
    opts HTTPOptions,
) (*HTTPAdapter, error)

locationPrefix must be a canonical absolute path without a trailing /. HTTPOptions can configure the SDP size, the connection establishment timeout, the Logger, and the Observer.

MethodDescription
Wrap(business)Adds Echo selection in front of an ordinary business Handler
PostHandler()Returns a dedicated Echo POST Handler
TryHandlePOST(w, r)A framework-independent Echo selection entry point
DeleteHandler()Returns the DELETE Handler used by the standard library router
ServeDelete(w, r, id)Deletes a resource with a session ID extracted by an external router
Stats()Returns a thread-safe statistics snapshot
Shutdown(ctx)Stops accepting, closes sessions, and waits for exit

TiRTC