Server SDK (Go) API reference
This page lists the primary public APIs used by a custom RTC service. Source under tirtc-service-sdk/pkg is authoritative. See the tirtcxauth authentication specification for the signing algorithm.
API list
| Package | API | Purpose |
|---|---|---|
tirtcx | Init / Start | Initialize and start the process-wide TiRTC engine |
tirtcx | Stop / Uninit | Stop and release the process-wide TiRTC engine |
tirtcx | SetNativeLogLevel | Set the TiRTC C library log level |
tirtcx | GetVersion | Return the TiRTC C library version |
tirtcxauth | NewEd25519TokenIssuer | Create a token issuer |
tirtcxauth | NewEd25519TokenVerifier | Create a token verifier |
tirtcxauth | BearerInterceptor | Create HTTP bearer authentication |
tirtcxauth | ClaimsFromContext | Read verified claims from a request |
tirtcx | NewWhipAcceptor | Create an authentication-independent acceptor |
tirtcx | WhipAcceptor.WhipAccept | Accept an SDP Offer and create a WHIP Session |
tirtcx | WhipSession | Own a pending or connected session |
tirtcx | Conn | An established TiRTC connection object. Handles media exchange, commands, and connection events. |
whipecho | NewHTTPAdapter | Create an embeddable Echo adapter |
SDK lifecycle
func Init() error
func Start(ctx context.Context) error
func Stop()
func Uninit()
func SetNativeLogLevel(level int)
func GetVersion() stringInitialize one TiRTC engine per process:
- If needed, call
SetNativeLogLevelbefore initialization. - Call
Initsuccessfully before using othertirtcxAPIs. - Call
Start(ctx)and wait for the system-started event.ctxmust not benil; a timeout or cancellation returns the corresponding context error. - During shutdown, close business sessions, then call
Stopfollowed byUninit.
GetVersion returns the loaded TiRTC C library version for startup logs and diagnostics.
Token and HTTP authentication
BearerInterceptor
func BearerInterceptor(
service string,
verifier TokenVerifier,
observers ...AuthObserver,
) HTTPInterceptorBearerInterceptor verifies the bearer token against the complete raw query. It returns 401 for a missing token, 403 for an invalid token, and 500 for invalid configuration. On success it places a copy of TokenClaims in the request context.
Read the verified identity with:
claims, ok := tirtcxauth.ClaimsFromContext(r.Context())TokenClaims field | Meaning |
|---|---|
Subject | Delegated device ID |
Scope | Access scope bound to the service and canonical query |
Issuer | Custom RTC Key ID that issued the token |
IssuedAt / ExpiresAt | Issue and expiry time in Unix seconds |
The token can be reused until exp, and tirtcxauth does not perform replay checks. The device SDK automatically protects the complete TiRtcWhipConnect call against replay. To reject direct replay of requests to the custom RTC service, add a one-time business parameter to the peer_id query and have the custom RTC service consume it on first use.
Use this interceptor for the resource-creation POST, not for DELETE <Location>.
Token issuing
Issue tokens with:
issuer, err := tirtcxauth.NewEd25519TokenIssuer(privateKeys)
token, err := issuer.Issue(service, customRtcKeyID, deviceID, rawQuery, ttl)The SDK canonicalizes the peer_id query for signing.
WHIP accept
NewWhipAcceptor
acceptor := tirtcx.NewWhipAcceptor(candidate)An empty candidate uses the SDK default address. Set it only when the service must advertise another reachable public address.
WhipAcceptor.WhipAccept
session, err := acceptor.WhipAccept(ctx, offer, eventOptions)The context passed to WhipAccept controls only the synchronous SDP Answer phase. Authentication must happen before this call.
Applications own resource IDs, Location, registries, and DELETE policy.
Session lifecycle
| Method | Behavior |
|---|---|
AnswerSDP() | Return a copy of the SDP Answer for the HTTP 201 response |
WaitConn(ctx) | Wait for the final connection result; safe for concurrent and repeated calls |
Close() | Idempotently terminate a pending or connected session |
Each WaitConn caller has an independent context. Canceling one waiter does not close the session.
Connection API
| Method | Purpose |
|---|---|
Events() | Return enabled event channels |
Done() | Close on normal disconnect or terminal error |
Err() | Return the terminal error after Done; normal disconnect returns nil |
EventStats() | Return cumulative event-drop counts |
SendAudio, SendVideo, SendMessage, SendCommand | Send data |
| Subscription and key-frame methods | Control media streams |
Close() | Disconnect |
FrameInfo and media types
type FrameInfo struct {
StreamID uint8
Media MediaType
Flags uint8
Ts uint32
Length uint32
}| Field | Meaning |
|---|---|
StreamID | 0–15; globally unique within a connection, so audio and video cannot reuse an ID |
Media | Frame encoding listed below |
Flags | For audio: 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 |
Ts | A 32-bit millisecond timestamp; keep it monotonic within a stream and allow natural wraparound |
Length | Received payload length. Send methods derive it from data; callers need not set it |
| Constant | Payload |
|---|---|
MediaMessage | In-stream message |
AudioPCM / AudioALaw / AudioAAC / AudioOpus / AudioAMR | Audio frame in the named encoding |
VideoJPEG / VideoH264 / VideoH265 | Video frame in the named encoding |
SendAudio, SendVideo, and SendMessage copy the payload before returning, so the input slice may be reused afterward. Received event payloads are Go-owned and remain readable after the native callback returns. Agree on exact codec parameters with the device implementation.
ConnEventOptions
ConnEventOptions configures the buffer capacity of each connection event channel and the synchronous handlers for remote subscription requests.
| Field | Configuration |
|---|---|
AudioBuffer / VideoBuffer / MessageBuffer / CommandBuffer | Buffer capacity of the corresponding data event channel |
ErrorBuffer / DisconnectedBuffer | Buffer capacity of the connection error and disconnect event channels |
RequestKeyFrameBuffer | Buffer capacity of the key-frame request event channel |
UnsubscribeVideoBuffer / UnsubscribeAudioBuffer | Buffer capacity of the unsubscribe event channels |
SubscribeVideoHandler / SubscribeAudioHandler | Synchronous handlers for remote subscription requests |
Each *Buffer value is the maximum number of events that the corresponding event channel can buffer. A non-positive value disables the event. A positive value below MinEventBufferSize is raised to that minimum. A subscription handler returns 0 to accept and a non-zero value to reject. It runs in a native callback and must return quickly; a missing handler or panic defaults to 0.
Echo HTTP API
echo, err := whipecho.NewHTTPAdapter(
acceptor,
"/whip/echo/resource",
whipecho.HTTPOptions{},
)The location prefix must be a canonical absolute path without a trailing slash.
HTTPOptions configures the SDP size limit, connection timeout, logger, and observer.
| Method | Purpose |
|---|---|
Wrap(business) | Add Echo selection before a business handler |
PostHandler() | Return a dedicated Echo POST handler |
TryHandlePOST(w, r) | Framework-neutral Echo selection |
DeleteHandler() | Return a standard-library DELETE handler |
ServeDelete(w, r, id) | Delete using an ID extracted by another router |
Stats() | Return a thread-safe statistics snapshot |
Shutdown(ctx) | Reject new sessions, close active sessions, and wait |