# `WebRTC` API Manual

## Overview

`libpeer` is a lightweight WebRTC library implemented in pure C. It provides PeerConnection management, SDP signaling exchange, ICE connectivity, DataChannel communication, and audio and video data transmission and reception. The APIs documented in this guide are C-language interfaces that can be called from C or C++ applications, compiled into executables, and run on the `k230` development board.

> Note:
>
> 1、The currently supported video codecs are H.264 and H.265; VP8 and MJPEG are not yet implemented;
> 2、The currently supported audio codecs are G711A (PCMA), G711U (PCMU), and OPUS;
> 3、`peer_init` must be called to initialize libsrtp and SCTP before calling `peer_connection_create`;
> 4、Signaling exchange requires the `peer_signaling` module or a custom signaling service;
> 5、When sending video data, complete NAL units must be provided; when sending audio data, G711 or OPUS encoded frames must be provided.

### Supported Media Codecs

| Type | Codec Format | Remarks             |
| ---- | ----------- | ------------------- |
| Video | H.264       |                     |
| Video | H.265       |                     |
| Video | VP8         | Not yet implemented |
| Video | MJPEG       | Not yet implemented |
| Audio | G711A       | PCMA                |
| Audio | G711U       | PCMU                |
| Audio | OPUS        |                     |

## Parameter Type Introduction

### SdpType

【Description】

SdpType is used to identify the type of SDP (Session Description Protocol), which is divided into Offer and Answer.

【Definition】

```c
typedef enum SdpType {
  SDP_TYPE_OFFER = 0,
  SDP_TYPE_ANSWER,
} SdpType;
```

【Description】

| Enumeration Value | Description                    |
| --------------- | ------------------------ |
| SDP_TYPE_OFFER  | SDP Offer, created by the caller  |
| SDP_TYPE_ANSWER | SDP Answer, created by the responder |

### PeerConnectionState

【Description】

PeerConnectionState is used to represent the ICE connection state of a PeerConnection.

【Definition】

```c
typedef enum PeerConnectionState {
  PEER_CONNECTION_CLOSED = 0,
  PEER_CONNECTION_NEW,
  PEER_CONNECTION_CHECKING,
  PEER_CONNECTION_CONNECTED,
  PEER_CONNECTION_COMPLETED,
  PEER_CONNECTION_FAILED,
  PEER_CONNECTION_DISCONNECTED,
} PeerConnectionState;
```

【Description】

| Enumeration Value                  | Description                       |
| ------------------------------ | -------------------------- |
| PEER_CONNECTION_CLOSED         | The connection has been closed                 |
| PEER_CONNECTION_NEW            | New connection; the ICE agent is gathering candidates |
| PEER_CONNECTION_CHECKING       | The ICE agent is checking candidate pairs   |
| PEER_CONNECTION_CONNECTED      | At least one candidate pair has connected successfully   |
| PEER_CONNECTION_COMPLETED      | The ICE agent has completed checking           |
| PEER_CONNECTION_FAILED         | The ICE connection failed               |
| PEER_CONNECTION_DISCONNECTED   | The connection has been disconnected                 |

### DataChannelType

【Description】

DataChannelType is used to identify the type of data transmitted by a DataChannel.

【Definition】

```c
typedef enum DataChannelType {
  DATA_CHANNEL_NONE = 0,
  DATA_CHANNEL_STRING,
  DATA_CHANNEL_BINARY,
} DataChannelType;
```

【Description】

| Enumeration Value      | Description               |
| -------------------- | ------------------ |
| DATA_CHANNEL_NONE    | No DataChannel     |
| DATA_CHANNEL_STRING  | String data     |
| DATA_CHANNEL_BINARY  | Binary data     |

### DecpChannelType

【Description】

DecpChannelType is used to configure the reliability and ordering policies of a DataChannel, corresponding to the channel types in DCEP (Data Channel Establishment Protocol).

【Definition】

```c
typedef enum DecpChannelType {
  DATA_CHANNEL_RELIABLE = 0x00,
  DATA_CHANNEL_RELIABLE_UNORDERED = 0x80,
  DATA_CHANNEL_PARTIAL_RELIABLE_REXMIT = 0x01,
  DATA_CHANNEL_PARTIAL_RELIABLE_REXMIT_UNORDERED = 0x81,
  DATA_CHANNEL_PARTIAL_RELIABLE_TIMED = 0x02,
  DATA_CHANNEL_PARTIAL_RELIABLE_TIMED_UNORDERED = 0x82,
} DecpChannelType;
```

【Description】

| Enumeration Value                                         | Description                         |
| --------------------------------------------------- | ---------------------------- |
| DATA_CHANNEL_RELIABLE                               | Reliable, ordered transmission                 |
| DATA_CHANNEL_RELIABLE_UNORDERED                     | Reliable, unordered transmission                 |
| DATA_CHANNEL_PARTIAL_RELIABLE_REXMIT                | Partially reliable, guaranteed based on the number of retransmissions     |
| DATA_CHANNEL_PARTIAL_RELIABLE_REXMIT_UNORDERED      | Partially reliable and unordered, guaranteed based on the number of retransmissions |
| DATA_CHANNEL_PARTIAL_RELIABLE_TIMED                 | Partially reliable, guaranteed based on the timeout duration     |
| DATA_CHANNEL_PARTIAL_RELIABLE_TIMED_UNORDERED       | Partially reliable and unordered, guaranteed based on the timeout duration |

### MediaCodec

【Description】

MediaCodec is used to configure the audio and video encoding formats.

【Definition】

```c
typedef enum MediaCodec {
  CODEC_NONE = 0,

  /* Video */
  CODEC_H264,
  CODEC_H265,
  CODEC_VP8,    // not implemented yet
  CODEC_MJPEG,  // not implemented yet

  /* Audio */
  CODEC_OPUS,
  CODEC_PCMA,
  CODEC_PCMU,
} MediaCodec;
```

【Description】

| Enumeration Value | Description                   |
| ----------- | ---------------------- |
| CODEC_NONE  | No encoding                 |
| CODEC_H264  | H.264 video encoding         |
| CODEC_H265  | H.265 video encoding         |
| CODEC_VP8   | VP8 video encoding (not implemented) |
| CODEC_MJPEG | MJPEG video encoding (not implemented) |
| CODEC_OPUS  | OPUS audio encoding          |
| CODEC_PCMA  | G711A audio encoding         |
| CODEC_PCMU  | G711U audio encoding         |

### IceServer

【Description】

IceServer is used to configure ICE (Interactive Connectivity Establishment) server information for NAT traversal.

【Definition】

```c
typedef struct IceServer {
  const char* urls;
  const char* username;
  const char* credential;
} IceServer;
```

【Parameters】

| Name       | Type         | Description                          |
| ---------- | ------------ | ----------------------------- |
| urls       | const char*  | ICE server URL, such as "stun:stun.l.google.com:19302" |
| username   | const char*  | TURN server username; may be NULL for STUN servers |
| credential | const char*  | TURN server credential; may be NULL for STUN servers |

【Example】

```c
IceServer server = {
    .urls = "stun:stun.l.google.com:19302",
    .username = NULL,
    .credential = NULL
};
```

### PeerConfiguration

【Description】

PeerConfiguration is used to configure PeerConnection parameters, including the ICE server list, audio and video encoding formats, DataChannel type, and audio and video data callbacks.

【Definition】

```c
typedef struct PeerConfiguration {
  IceServer ice_servers[5];

  MediaCodec audio_codec;
  MediaCodec video_codec;
  DataChannelType datachannel;

  void (*onaudiotrack)(uint8_t* data, size_t size, void* userdata);
  void (*onvideotrack)(uint8_t* data, size_t size, void* userdata);
  void (*on_request_keyframe)(void* userdata);
  void* user_data;
} PeerConfiguration;
```

【Parameters】

| Name                | Type       | Description                                          |
| ----------------- | ---------- | --------------------------------------------- |
| ice_servers       | IceServer[5] | ICE server list, with a maximum of 5                    |
| audio_codec       | MediaCodec | Audio encoding format                                  |
| video_codec       | MediaCodec | Video encoding format                                  |
| datachannel       | DataChannelType | DataChannel data type                     |
| onaudiotrack      | Function pointer   | Callback function for receiving remote audio data                    |
| onvideotrack      | Function pointer   | Callback function for receiving remote video data                    |
| on_request_keyframe | Function pointer | Callback function for requesting a keyframe                          |
| user_data         | void*      | User data pointer passed to the callback function                  |

【Example】

```c
PeerConfiguration config = {0};
config.ice_servers[0] = (IceServer){ "stun:stun.l.google.com:19302", NULL, NULL };
config.audio_codec = CODEC_PCMU;
config.video_codec = CODEC_H264;
config.datachannel = DATA_CHANNEL_NONE;
config.onaudiotrack = NULL;
config.onvideotrack = NULL;
config.on_request_keyframe = NULL;
config.user_data = NULL;
```

## API Introduction

### peer_init

【Description】

Initializes the WebRTC library, including the libsrtp and SCTP protocol stacks. This function must be called before using any PeerConnection-related APIs.

【Definition】

```c
int peer_init();
```

【Parameters】

None.

【Return Value】

| Return Value | Description                         |
| ------------ | ----------------------------------- |
| 0            | Success                             |
| -1           | Failure, libsrtp initialization failed |

【Example】

```c
if (peer_init() != 0) {
    printf("WebRTC init failed\n");
    return -1;
}
```

### peer_deinit

【Description】

Deinitializes the WebRTC library and releases resources related to the libsrtp and SCTP protocol stacks.

【Definition】

```c
void peer_deinit();
```

【Parameters】

None.

【Return Value】

None.

【Example】

```c
peer_deinit();
```

### peer_connection_create

【Description】

Creates a PeerConnection instance.

【Definition】

```c
PeerConnection* peer_connection_create(PeerConfiguration* config);
```

【Parameters】

| Name   | Type               | Description               |
| ------ | ------------------ | ------------------------- |
| config | PeerConfiguration* | PeerConnection configuration |

【Return Value】

| Return Value   | Description                    |
| --------------- | ------------------------------ |
| PeerConnection* | Success, returns the instance pointer |
| NULL            | Failure                        |

【Example】

```c
PeerConnection* pc = peer_connection_create(&config);
if (!pc) {
    printf("Create peer connection failed\n");
    return -1;
}
```

### peer_connection_destroy

【Description】

Destroys a PeerConnection instance and releases related resources.

【Definition】

```c
void peer_connection_destroy(PeerConnection* pc);
```

【Parameters】

| Name | Type             | Description               |
| ---- | ---------------- | ------------------------- |
| pc   | PeerConnection*  | PeerConnection instance   |

【Return Value】

None.

【Example】

```c
peer_connection_destroy(pc);
```

### peer_connection_close

【Description】

Closes the PeerConnection connection without releasing resources. To release resources, call `peer_connection_destroy`.

【Definition】

```c
void peer_connection_close(PeerConnection* pc);
```

【Parameters】

| Name | Type             | Description               |
| ---- | ---------------- | ------------------------- |
| pc   | PeerConnection*  | PeerConnection instance   |

【Return Value】

None.

### peer_connection_get_state

【Description】

Gets the current connection state of the PeerConnection.

【Definition】

```c
PeerConnectionState peer_connection_get_state(PeerConnection* pc);
```

【Parameters】

| Name | Type             | Description               |
| ---- | ---------------- | ------------------------- |
| pc   | PeerConnection*  | PeerConnection instance   |

【Return Value】

| Return Value          | Description              |
| --------------------- | ------------------------ |
| PeerConnectionState   | Current connection state |

【Example】

```c
PeerConnectionState state = peer_connection_get_state(pc);
printf("Connection state: %s\n", peer_connection_state_to_string(state));
```

### peer_connection_state_to_string

【Description】

Converts a PeerConnectionState enum value into a readable string.

【Definition】

```c
const char* peer_connection_state_to_string(PeerConnectionState state);
```

【Parameters】

| Name  | Type                | Description         |
| ----- | ------------------- | ------------------- |
| state | PeerConnectionState | Connection state enum |

【Return Value】

| Return Value | Description                 |
| ------------- | --------------------------- |
| const char*   | String description corresponding to the state |

### peer_connection_create_offer

【Description】

Creates an SDP Offer for initiating a WebRTC connection. Typically called by the caller.

【Definition】

```c
const char* peer_connection_create_offer(PeerConnection* pc);
```

【Parameters】

| Name | Type             | Description               |
| ---- | ---------------- | ------------------------- |
| pc   | PeerConnection*  | PeerConnection instance   |

【Return Value】

| Return Value | Description                 |
| ------------- | --------------------------- |
| const char*   | SDP Offer string            |
| NULL          | Failure                     |

【Example】

```c
const char* offer = peer_connection_create_offer(pc);
if (offer) {
    printf("SDP Offer:\n%s\n", offer);
}
```

### peer_connection_create_answer

【Description】

Creates an SDP Answer for responding to a WebRTC connection. Typically called by the answerer after receiving an Offer.

【Definition】

```c
const char* peer_connection_create_answer(PeerConnection* pc);
```

【Parameters】

| Name | Type             | Description               |
| ---- | ---------------- | ------------------------- |
| pc   | PeerConnection*  | PeerConnection instance   |

【Return Value】

| Return Value | Description                 |
| ------------- | --------------------------- |
| const char*   | SDP Answer string           |
| NULL          | Failure                     |

### peer_connection_set_local_description

【Description】

Sets the local SDP description.

【Definition】

```c
void peer_connection_set_local_description(PeerConnection* pc, const char* sdp, SdpType sdp_type);
```

【Parameters】

| Name     | Type            | Description                           |
| -------- | --------------- | ------------------------------------- |
| pc       | PeerConnection* | PeerConnection instance               |
| sdp      | const char*     | SDP string                            |
| sdp_type | SdpType         | SDP type (Offer or Answer)            |

【Return Value】

None.

### peer_connection_set_remote_description

【Description】

Sets the remote SDP description.

【Definition】

```c
void peer_connection_set_remote_description(PeerConnection* pc, const char* sdp, SdpType sdp_type);
```

【Parameters】

| Name     | Type            | Description                           |
| -------- | --------------- | ------------------------------------- |
| pc       | PeerConnection* | PeerConnection instance               |
| sdp      | const char*     | Remote SDP string                     |
| sdp_type | SdpType         | SDP type (Offer or Answer)            |

【Return Value】

None.

【Example】

```c
// The answerer sets the remote description after receiving the Offer
peer_connection_set_remote_description(pc, remote_offer_sdp, SDP_TYPE_OFFER);
// Create the Answer
const char* answer = peer_connection_create_answer(pc);
// Set the local description
peer_connection_set_local_description(pc, answer, SDP_TYPE_ANSWER);
```

### peer_connection_add_ice_candidate

【Description】

Adds a remote ICE candidate to the PeerConnection.

【Definition】

```c
int peer_connection_add_ice_candidate(PeerConnection* pc, char* ice_candidate);
```

【Parameters】

| Name          | Type             | Description                |
| ------------- | ---------------- | -------------------------- |
| pc            | PeerConnection*  | PeerConnection instance    |
| ice_candidate | char*            | ICE candidate string       |

【Return Value】

| Return Value | Description |
| ------------ | ----------- |
| 0            | Success     |
| -1           | Failure     |

### peer_connection_onicecandidate

【Description】

Registers an ICE candidate event callback function. This callback is triggered when a local ICE candidate is discovered. The callback parameters contain the complete SDP text.

【Definition】

```c
void peer_connection_onicecandidate(PeerConnection* pc, void (*onicecandidate)(char* sdp_text, void* userdata));
```

【Parameters】

| Name             | Type            | Description                       |
| ---------------- | --------------- | --------------------------------- |
| pc               | PeerConnection* | PeerConnection instance            |
| onicecandidate   | Function pointer | ICE candidate callback function   |

Callback function parameters:

| Parameter | Type  | Description                              |
| --------- | ----- | ---------------------------------------- |
| sdp_text  | char* | SDP text containing the ICE candidate   |

### peer_connection_oniceconnectionstatechange

【Description】

Registers an ICE connection state change event callback function. This callback is triggered when the ICE connection state changes.

【Definition】

```c
void peer_connection_oniceconnectionstatechange(PeerConnection* pc,
    void (*oniceconnectionstatechange)(PeerConnectionState state, void* userdata));
```

【Parameters】

| Name                         | Type             | Description                                      |
| ---------------------------- | ---------------- | ------------------------------------------------ |
| pc                           | PeerConnection*  | PeerConnection instance                           |
| oniceconnectionstatechange   | Function pointer | ICE connection state change callback function    |

Callback function parameters:

| Parameter | Type                | Description              |
| --------- | ------------------- | ------------------------ |
| state     | PeerConnectionState | Current connection state |

【Example】

```c
void on_ice_state_change(PeerConnectionState state, void* userdata) {
    printf("ICE state: %s\n", peer_connection_state_to_string(state));
}

peer_connection_oniceconnectionstatechange(pc, on_ice_state_change);
```

### peer_connection_on_receiver_packet_loss

【Description】

Registers an RTCP receiver packet loss rate callback function. This callback is triggered when an RTCP receiver report is received.

【Definition】

```c
void peer_connection_on_receiver_packet_loss(PeerConnection* pc,
    void (*on_receiver_packet_loss)(float fraction_loss, uint32_t total_loss, void* userdata));
```

【Parameters】

| Name                    | Type             | Description                                      |
| ----------------------- | ---------------- | ------------------------------------------------ |
| pc                      | PeerConnection*  | PeerConnection instance                           |
| on_receiver_packet_loss | Function pointer | Packet loss rate callback function                |

Callback function parameters:

| Parameter      | Type     | Description                 |
| -------------- | -------- | --------------------------- |
| fraction_loss  | float    | Packet loss rate (0.0~1.0)  |
| total_loss     | uint32_t | Cumulative number of lost packets |

### peer_connection_send_video

【Description】

Sends video frame data through the PeerConnection.

【Definition】

```c
int peer_connection_send_video(PeerConnection* pc, const uint8_t* packet, size_t bytes, uint64_t timestamp_us);
```

【Parameters】

| Name         | Type            | Description                           |
| ------------ | --------------- | ------------------------------------- |
| pc           | PeerConnection* | PeerConnection instance               |
| packet       | const uint8_t*  | Video frame data pointer (NAL unit)    |
| bytes        | size_t          | Video frame data size (bytes)         |
| timestamp_us | uint64_t        | Timestamp (microseconds)              |

【Return Value】

| Return Value | Description |
| ------------ | ----------- |
| 0            | Success     |
| -1           | Failure     |

【Example】

```c
peer_connection_send_video(pc, nal_data, nal_size, timestamp_us);
```

### peer_connection_send_audio

【Description】

Sends audio frame data through the PeerConnection.

【Definition】

```c
int peer_connection_send_audio(PeerConnection* pc, const uint8_t* packet, size_t bytes, uint64_t timestamp_us);
```

【Parameters】

| Name         | Type            | Description                               |
| ------------ | --------------- | ----------------------------------------- |
| pc           | PeerConnection* | PeerConnection instance                   |
| packet       | const uint8_t*  | Audio frame data pointer (G711 or OPUS encoded frame) |
| bytes        | size_t          | Audio frame data size (bytes)            |
| timestamp_us | uint64_t        | Timestamp (microseconds)                 |

【Return Value】

| Return Value | Description |
| ------------ | ----------- |
| 0            | Success     |
| -1           | Failure     |

【Example】

```c
peer_connection_send_audio(pc, g711_frame, frame_size, timestamp_us);
```

### peer_connection_create_datachannel

【Description】

Creates a DataChannel channel.

【Definition】

```c
int peer_connection_create_datachannel(PeerConnection* pc, DecpChannelType channel_type,
    uint16_t priority, uint32_t reliability_parameter, char* label, char* protocol);
```

【Parameters】

| Name                  | Type             | Description                                               |
| --------------------- | ---------------- | --------------------------------------------------------- |
| pc                    | PeerConnection*  | PeerConnection instance                                    |
| channel_type          | DecpChannelType  | Channel reliability and ordering policy                    |
| priority              | uint16_t         | Channel priority                                           |
| reliability_parameter | uint32_t         | Reliability parameter (retransmission count or timeout, depending on channel_type) |
| label                 | char*            | Channel label name                                        |
| protocol              | char*            | Subprotocol name; may be an empty string                   |

【Return Value】

| Return Value | Description |
| ------------ | ----------- |
| 0            | Success     |
| -1           | Failure     |

【Example】

```c
// Create a reliable, ordered DataChannel
peer_connection_create_datachannel(pc, DATA_CHANNEL_RELIABLE, 0, 0, "my_channel", "");
```

### peer_connection_create_datachannel_sid

【Description】

Creates a DataChannel channel with the specified Stream ID.

【Definition】

```c
int peer_connection_create_datachannel_sid(PeerConnection* pc, DecpChannelType channel_type,
    uint16_t priority, uint32_t reliability_parameter, char* label, char* protocol, uint16_t sid);
```

【Parameters】

| Name                  | Type             | Description                                               |
| --------------------- | ---------------- | --------------------------------------------------------- |
| pc                    | PeerConnection*  | PeerConnection instance                                    |
| channel_type          | DecpChannelType  | Channel reliability and ordering policy                    |
| priority              | uint16_t         | Channel priority                                           |
| reliability_parameter | uint32_t         | Reliability parameter                                      |
| label                 | char*            | Channel label name                                        |
| protocol              | char*            | Subprotocol name                                          |
| sid                   | uint16_t         | Specified Stream ID                                       |

【Return Value】

| Return Value | Description |
| ------------ | ----------- |
| 0            | Success     |
| -1           | Failure     |

### peer_connection_datachannel_send

【Description】

Sends a text message through the DataChannel.

【Definition】

```c
int peer_connection_datachannel_send(PeerConnection* pc, char* message, size_t len);
```

【Parameters】

| Name    | Type             | Description               |
| ------- | ---------------- | ------------------------- |
| pc      | PeerConnection*  | PeerConnection instance   |
| message | char*            | Message content           |
| len     | size_t           | Message length            |

【Return Value】

| Return Value | Description |
| ------------ | ----------- |
| 0            | Success     |
| -1           | Failure     |

### peer_connection_datachannel_send_sid

【Description】

Sends a text message through the DataChannel with the specified Stream ID.

【Definition】

```c
int peer_connection_datachannel_send_sid(PeerConnection* pc, char* message, size_t len, uint16_t sid);
```

【Parameters】

| Name    | Type             | Description                    |
| ------- | ---------------- | ------------------------------ |
| pc      | PeerConnection*  | PeerConnection instance        |
| message | char*            | Message content                |
| len     | size_t           | Message length                 |
| sid     | uint16_t         | Stream ID                      |

【Return Value】

| Return Value | Description |
| ------------ | ----------- |
| 0            | Success     |
| -1           | Failure     |

### peer_connection_datachannel_send_binary

【Description】

Sends binary data through the DataChannel (PPID=53).

【Definition】

```c
int peer_connection_datachannel_send_binary(PeerConnection* pc, const char* data, size_t len);
```

【Parameters】

| Name | Type             | Description                |
| ---- | ---------------- | -------------------------- |
| pc   | PeerConnection*  | PeerConnection instance    |
| data | const char*      | Binary data pointer        |
| len  | size_t           | Data length                |

【Return Value】

| Return Value | Description |
| ------------ | ----------- |
| 0            | Success     |
| -1           | Failure     |

### peer_connection_datachannel_send_binary_sid

【Description】

Sends binary data through the DataChannel with the specified Stream ID (PPID=53).

【Definition】

```c
int peer_connection_datachannel_send_binary_sid(PeerConnection* pc, const char* data, size_t len, uint16_t sid);
```

【Parameters】

| Name | Type             | Description                    |
| ---- | ---------------- | ------------------------------ |
| pc   | PeerConnection*  | PeerConnection instance        |
| data | const char*      | Binary data pointer            |
| len  | size_t           | Data length                    |
| sid  | uint16_t         | Stream ID                      |

【Return Value】

| Return Value | Description |
| ------------ | ----------- |
| 0            | Success     |
| -1           | Failure     |

### peer_connection_ondatachannel

【Description】

Registers DataChannel event callback functions, including message reception, channel opening, and channel closing events.

【Definition】

```c
void peer_connection_ondatachannel(PeerConnection* pc,
    void (*onmessage)(char* msg, size_t len, void* userdata, uint16_t sid),
    void (*onopen)(void* userdata),
    void (*onclose)(void* userdata));
```

【Parameters】

| Name      | Type             | Description                       |
| --------- | ---------------- | --------------------------------- |
| pc        | PeerConnection*  | PeerConnection instance            |
| onmessage | Function pointer | Message reception callback function |
| onopen    | Function pointer | Channel opening callback function  |
| onclose   | Function pointer | Channel closing callback function  |

onmessage callback parameters:

| Parameter | Type     | Description     |
| --------- | -------- | --------------- |
| msg       | char*    | Message content |
| len       | size_t   | Message length  |
| sid       | uint16_t | Stream ID       |

【Example】

```c
void on_dc_message(char* msg, size_t len, void* userdata, uint16_t sid) {
    printf("DataChannel message (sid=%u): %.*s\n", sid, (int)len, msg);
}

void on_dc_open(void* userdata) {
    printf("DataChannel opened\n");
}

void on_dc_close(void* userdata) {
    printf("DataChannel closed\n");
}

peer_connection_ondatachannel(pc, on_dc_message, on_dc_open, on_dc_close);
```

### peer_connection_lookup_sid

【Description】

Looks up the corresponding Stream ID by channel label name.

【Definition】

```c
int peer_connection_lookup_sid(PeerConnection* pc, const char* label, uint16_t* sid);
```

【Parameters】

| Name  | Type             | Description                       |
| ----- | ---------------- | --------------------------------- |
| pc    | PeerConnection*  | PeerConnection instance            |
| label | const char*      | Channel label name                |
| sid   | uint16_t*        | Output: the found Stream ID       |

【Return Value】

| Return Value | Description         |
| ------------ | ------------------- |
| 0            | Successfully found  |
| -1           | Not found           |

### peer_connection_lookup_sid_label

【Description】

Looks up the corresponding channel label name by Stream ID.

【Definition】

```c
char* peer_connection_lookup_sid_label(PeerConnection* pc, uint16_t sid);
```

【Parameters】

| Name | Type             | Description               |
| ---- | ---------------- | ------------------------- |
| pc   | PeerConnection*  | PeerConnection instance   |
| sid  | uint16_t         | Stream ID                 |

【Return Value】

| Return Value | Description                    |
| ------------ | ------------------------------ |
| char*        | Channel label name string      |
| NULL         | Not found                      |

### peer_connection_loop

【Description】

Runs the PeerConnection event loop to process underlying events such as ICE and DTLS. Typically called repeatedly in a separate thread.

【Definition】

```c
int peer_connection_loop(PeerConnection* pc);
```

【Parameters】

| Name | Type             | Description               |
| ---- | ---------------- | ------------------------- |
| pc   | PeerConnection*  | PeerConnection instance   |

【Return Value】

| Return Value | Description       |
| ------------ | ----------------- |
| 0            | Normal exit       |
| -1           | Error             |

### peer_connection_get_sctp

【Description】

Gets the pointer to the SCTP instance associated with the PeerConnection.

【Definition】

```c
void* peer_connection_get_sctp(PeerConnection* pc);
```

【Parameters】

| Name | Type             | Description               |
| ---- | ---------------- | ------------------------- |
| pc   | PeerConnection*  | PeerConnection instance   |

【Return Value】

| Return Value | Description               |
| ------------ | ------------------------- |
| void*        | SCTP instance pointer     |
| NULL         | No SCTP instance          |

## Signaling API Overview

### peer_signaling_connect

【Description】

Connects to the signaling server and establishes a signaling channel. Supports HTTP and MQTT signaling protocols.

【Definition】

```c
int peer_signaling_connect(const char* url, const char* token, PeerConnection* pc);
```

【Parameters】

| Name   | Type            | Description                                      |
| ----- | ----------------- | ----------------------------------------- |
| url   | const char*       | Signaling server URL                            |
| token | const char*       | Authentication token; may be NULL             |
| pc    | PeerConnection*   | Associated PeerConnection instance               |

【Return Value】

| Return Value | Description   |
| ------ | ------ |
| 0      | Success   |
| -1     | Failure   |

【Example】

```c
int ret = peer_signaling_connect("http://192.168.1.100:8080", NULL, pc);
if (ret != 0) {
    printf("Signaling connect failed\n");
}
```

### peer_signaling_disconnect

【Description】

Disconnects from the signaling server.

【Definition】

```c
void peer_signaling_disconnect();
```

【Parameters】

None.

【Return Value】

None.

### peer_signaling_loop

【Description】

Runs the signaling event loop and processes signaling messages. Usually called repeatedly in a separate thread.

【Definition】

```c
int peer_signaling_loop();
```

【Parameters】

None.

【Return Value】

| Return Value | Description     |
| ------ | -------- |
| 0      | Normal exit |
| -1     | Error     |

### peer_signaling_set_custom_rpc_handler

【Description】

Registers a custom RPC method callback for handling application-layer RPC methods not recognized by the signaling layer. Must be called after `peer_signaling_connect`. Only one handler can be registered at a time; subsequent calls replace the previous handler.

【Definition】

```c
void peer_signaling_set_custom_rpc_handler(peer_signaling_custom_rpc_cb cb, void* userdata);
```

【Parameters】

| Name       | Type                        | Description                                |
| -------- | --------------------------- | ----------------------------------- |
| cb       | peer_signaling_custom_rpc_cb | Callback function for custom RPC method handling       |
| userdata | void*                       | User data pointer passed to the callback function        |

Callback function signature:

```c
typedef int (*peer_signaling_custom_rpc_cb)(const char* method, cJSON* params, int id,
                                            cJSON** result, cJSON** error, void* userdata);
```

Callback parameter descriptions:

| Parameter | Type        | Description                                            |
| -------- | ----------- | ----------------------------------------------- |
| method   | const char* | RPC method name                                    |
| params   | cJSON*      | Request parameter JSON object; may be NULL                 |
| id       | int         | JSON-RPC request ID                                |
| result   | cJSON**     | Output: set the result JSON object (caller takes ownership)    |
| error    | cJSON**     | Output: set the error JSON object (caller takes ownership)    |
| userdata | void*       | User data pointer                                    |

Callback return value:

| Return Value | Description                                      |
| ------ | ----------------------------------------- |
| 0      | Method handled (result or error must be set)    |
| -1     | Method not handled (the signaling layer will return METHOD_NOT_FOUND) |

### peer_signaling_publish

【Description】

Publishes a message to the specified topic through the signaling layer's MQTT connection. Effective only in MQTT mode (proto == 0); returns -1 in HTTP mode or when the MQTT connection has not been established.

【Definition】

```c
int peer_signaling_publish(const char* topic, const char* message);
```

【Parameters】

| Name      | Type        | Description                           |
| ------- | ----------- | ------------------------------ |
| topic   | const char* | MQTT topic, e.g. "/devices/heartbeat" |
| message | const char* | Message content (JSON string)        |

【Return Value】

| Return Value | Description               |
| ------ | ------------------ |
| 0      | Success               |
| -1     | Failure; HTTP mode or MQTT connection not established |

## Example

The following example is written in C++ and demonstrates typical usage of the libpeer C API in a C++ project. The event loop uses `std::thread` to run in a separate thread.

```cpp
#include "peer.h"
#include "peer_connection.h"
#include "peer_signaling.h"
#include <stdio.h>
#include <string.h>
#include <thread>

static int running = 1;

void on_ice_candidate(char* sdp_text, void* userdata) {
    printf("ICE candidate found\n");
}

void on_ice_state_change(PeerConnectionState state, void* userdata) {
    printf("ICE state: %s\n", peer_connection_state_to_string(state));
}

void on_dc_message(char* msg, size_t len, void* userdata, uint16_t sid) {
    printf("DataChannel message: %.*s\n", (int)len, msg);
}

void on_dc_open(void* userdata) {
    printf("DataChannel opened\n");
}

void on_dc_close(void* userdata) {
    printf("DataChannel closed\n");
}

int main()
{
    // Initialize the WebRTC library
    if (peer_init() != 0) {
        printf("WebRTC init failed\n");
        return -1;
    }

    // Configure PeerConnection
    PeerConfiguration config = {0};
    config.ice_servers[0] = (IceServer){ "stun:stun.l.google.com:19302", NULL, NULL };
    config.audio_codec = CODEC_PCMU;
    config.video_codec = CODEC_H264;
    config.datachannel = DATA_CHANNEL_STRING;

    // Create PeerConnection
    PeerConnection* pc = peer_connection_create(&config);
    if (!pc) {
        printf("Create peer connection failed\n");
        peer_deinit();
        return -1;
    }

    // Register callbacks
    peer_connection_onicecandidate(pc, on_ice_candidate);
    peer_connection_oniceconnectionstatechange(pc, on_ice_state_change);
    peer_connection_ondatachannel(pc, on_dc_message, on_dc_open, on_dc_close);

    // Create DataChannel
    peer_connection_create_datachannel(pc, DATA_CHANNEL_RELIABLE, 0, 0, "chat", "");

    // Connect to the signaling server
    peer_signaling_connect("http://192.168.1.100:8080", NULL, pc);

    // Run the event loop in a separate thread
    std::thread loop_thread([&]() {
        while (running) {
            peer_connection_loop(pc);
            peer_signaling_loop();
        }
    });

    // Streaming loop
    while (running) {
        // Get video frame data video_data, video_size, video_timestamp
        peer_connection_send_video(pc, video_data, video_size, video_timestamp_us);

        // Get audio frame data audio_data, audio_size, audio_timestamp
        peer_connection_send_audio(pc, audio_data, audio_size, audio_timestamp_us);
    }

    // Clean up
    running = 0;
    loop_thread.join();
    peer_signaling_disconnect();
    peer_connection_destroy(pc);
    peer_deinit();

    return 0;
}
```

The above code needs to be compiled into an `elf` executable file using the build tools in the `k230 linux sdk` environment, and then copied to the development board for execution.
