> ## Documentation Index
> Fetch the complete documentation index at: https://docs.stmlink.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> 对外开放的服务端接口有两组前缀，都用同一套鉴权：`/server/v1/...`（SRTC 与 SMeeting 的主接口）和 `/stm/srvapi/v1/...`（SMeeting 的用户体系，服务端极简对接会用到）。鉴权是 app_id + nonce + timestamp + signature 四个请求头，用 app_key 做 HMAC-SHA256 签名，只能从业务方自己的后端调用。除这两组前缀外的接口均为内部接口，不要建议客户调用。 Public server APIs use two path prefixes with the same authentication: `/server/v1/...` (the main APIs of both SRTC and SMeeting) and `/stm/srvapi/v1/...` (the SMeeting user system, used by server-side low-code integration). Authenticate with four request headers, app_id + nonce + timestamp + signature, where signature is HMAC-SHA256 keyed with app_key; call these APIs only from the customer's own backend. Any other path is internal: never suggest calling it.
> app_key 是服务端密钥，绝不能出现在客户端代码、前端配置或移动 App 里。客户端加入频道用的 token 必须由业务方后端签发后下发（SRTC 走 `/server/v1/channel/grant`，SMeeting 走 `/stm/srvapi/v1/member/grant`）。 app_key is a server-side secret and must never appear in client code, frontend config, or a mobile app. The token a client uses to join must be issued by the customer's backend and passed down to the client (SRTC: `/server/v1/channel/grant`; SMeeting: `/stm/srvapi/v1/member/grant`).
> SRTC 与 SMeeting 是上下两层不同的产品，术语不通用：SRTC 是音视频底座，说「频道 channel」「加入 / 退出」；SMeeting 建在 SRTC 之上，说「房间 room」「会议 meeting」「进入 / 退出」。回答时按用户所在的层用对应术语，不要把「房间」「会议」安到 SRTC 的接口上，也不要用「频道」「加入 / 离开」描述 SMeeting 的概念（接口标识符原样保留）。 SRTC and SMeeting are two separate layers with different terminology. SRTC is the audio/video foundation: it has channels, and users join and leave a channel. SMeeting is built on top of SRTC: it has rooms and meetings, and members enter and exit a meeting. Answer in the terms of the layer the user is working with: never apply "room" or "meeting" to SRTC APIs, and never describe SMeeting concepts in prose with "channel", "join", or "leave" (API identifiers such as `force_join` keep their literal names).
> 同一能力在各端 SDK 里的包名、类名、方法名并不相同。写示例代码时请使用文档中该端自己的 API，不要把一个端的写法套到另一个端上。苹果平台每个产品都有两套 SDK（Swift 原生与 Objective-C），两套 API 不能混用。 Package, class, and method names differ between platform SDKs for the same capability. In sample code, use the API documented for that platform; never carry one platform's code over to another. On Apple platforms each product ships two SDKs (native Swift and Objective-C) whose APIs must not be mixed.

# Event callbacks

> The ChannelHandler event list of the SRTC Python SDK: connection state, disconnect reasons, users joining and leaving, tracks added and removed, audio and video frames, active speakers, network quality, and custom messages, with when each fires, its parameters, and ordering guarantees.

Subclass `srtc.ChannelHandler`, override the methods you need, and pass it in with `Channel.join(token, handler=...)`. Events you don't override are ignored.

```python theme={null}
class MyHandler(srtc.ChannelHandler):
    def on_user_join(self, user: srtc.UserInfo):          # A regular function
        print("Joined:", user.uid)

    async def on_disconnected(self, reason, error):       # It can also be an async function
        await notify_ops(reason)
```

* All methods are called on the **asyncio event loop thread**, so no locking is needed
* `async` methods are scheduled as Tasks and don't block subsequent events
* Exceptions raised in the methods are logged to the `srtc` logger and don't interrupt the SDK

***

## Event list

| Method | Parameters | When it fires |
| - | - | - |
| `on_connection_state` | `state: ConnectionState` | Connection state changed: `CONNECTED` (connected / reconnected), `RECONNECTING` (network interrupted, the SDK is reconnecting automatically), `DISCONNECTED` (disconnected) |
| `on_disconnected` | `reason: DisconnectReason`, `error: SdkError \| None` | Fully left the channel and won't reconnect automatically. For `reason`, see [DisconnectReason](/en/rtc/python/types#disconnectreason) |
| `on_user_join` | `user: UserInfo` | A remote user joined |
| `on_user_leave` | `uid: str` | A remote user left |
| `on_track_added` | `track: TrackInfo` | A remote user published a new track. When auto-subscribe is off, decide here whether to subscribe |
| `on_track_updated` | `track: TrackInfo` | A remote track's info changed |
| `on_track_removed` | `track: TrackInfo` | A remote user unpublished a track |
| `on_audio_frame` | `frame: AudioFrame` | A decoded frame of remote audio was received (about once every 20 ms per track) |
| `on_video_frame` | `frame: VideoFrame` | A frame of remote video was received |
| `on_active_speakers` | `speakers: list[ActiveSpeaker]` | Active speakers changed; a full snapshot sorted by volume in descending order; an empty list means nobody is speaking |
| `on_connection_quality` | `quality: ConnectionQuality` | Uplink and downlink network quality, about once per second |
| `on_layer_switched` | `event: LayerSwitched` | A layer switch of subscribed multi-layer video completed |
| `on_custom_msg` | `msg: CustomMsg` | An in-channel custom message was received (sent by your backend) |

<Note>
  `on_active_speakers`, `on_connection_quality`, and `on_layer_switched` depend on the channel's media streaming engine and don't fire in some deployments. Don't make your business logic rely on them always arriving.
</Note>

***

## Ordering and timing

<Warning>
  **There's no ordering guarantee between user events and track events.** For example, a user's `on_track_added` may arrive before their `on_user_join`. Just handle them idempotently by `uid`, and don't assume "join first, publish later".
</Warning>

* **Users and tracks already in the channel before you joined don't trigger `on_user_join` / `on_track_added`**; read `ch.users` after joining
* `on_audio_frame` / `on_video_frame` for the same track arrive strictly in order
* `on_audio_frame` is a high-frequency event, so use a regular function and return as quickly as possible; for time-consuming processing, we recommend consuming with `async for` over `ch.audio_frames()` instead

***

## Handling disconnects

Distinguish three cases:

| Case | What you receive | Recommendation |
| - | - | - |
| Brief network interruption | `on_connection_state(RECONNECTING)`, then `CONNECTED` after recovery | Do nothing; the SDK reconnects automatically |
| Removed from the channel / replaced by another session with the same uid / channel destroyed | `on_disconnected(KICKED / REPLACE / DESTROY, ...)` | End the session; **don't rejoin automatically** |
| Reconnection failed, heartbeat timed out | `on_disconnected(ERROR / TIMEOUT, error)` | If needed, `join` again with a **newly issued token** |
