Go

Updated

Agora Server Gateway SDK API reference for Go.

Server Gateway SDK API reference for Go.

Overview

agoraservice package

The agoraservice package serves as the entry point for the SDK, allowing you to create media tracks and establish connections.

Initialize

Initialize the agoraservice package:

func Initialize(cfg *AgoraServiceConfig) int

Parameters

ParameterDescription
cfgInitialization configuration. See AgoraServiceConfig for details.

Returns

  • 0: Success.
  • < 0: Failure.

Release

Release the resources occupied by the agoraservice package:

func Release() int

RtcConnection

The RtcConnection class is used to manage the connection between the SDK and the RTC channel. Once the connection is established, you can use the LocalUser object to send and receive media streams in the RTC channel. Connecting to the channel is an asynchronous operation, and you can monitor connection state changes and events through the RtcConnectionObserver object. RtcConnection can also monitor whether a remote user joins or leaves the channel.

NewRtcConnection

Creates an RTC connection object.

func NewRtcConnection(cfg *RtcConnectionConfig) *RtcConnection

Parameters

ParameterDescription
cfgRTC connection configuration. See RtcConnectionConfig for details.

Returns

  • RtcConnection object, if the method call succeeds.
  • nil, if the method call fails.

Connect

Connects to the RTC channel.

func (conn *RtcConnection) Connect(token string, channel string, uid string) int

When the method succeeds, the connection state changes from true to 2.

Depending on whether the connection is successful, the connection state will change to 3 or 5. The SDK will trigger OnConnected or OnDisconnected to notify the connection state change.

Parameters

ParameterDescription
tokenRTC Token. See Use tokens for details.
channelChannel name. Must be a string with a length of no more than 64 bytes. Supported character types include: - All lowercase letters: a to z; - All uppercase letters: A to Z; - All Arabic numerals: 0 to 9; - Space; - Punctuation and other special symbols: !, #, $, %, &, (, ), +, -, :, ;, <, =, ., >, ?, @, [, ], ^, _, {, }, |, ~, ,
uidLocal user ID. No more than 64 bytes in length. If you do not set a user ID or set it to nil, the SDK will automatically return a user ID in the OnConnected callback. You must save and manage this ID yourself. Depending on the user ID type you choose in the Initialize method, the supported character sets for this parameter are different: - For int type user ID, the supported character set includes 10 digits 0-9 - For String type user ID, the supported character set includes: - 26 lowercase English letters a-z; - 26 uppercase English letters A-Z; - 10 digits 0-9; - Space; - !, #, $, %, &, (, ), +, -, :, ;, <, =, ., >, ?, @, [, ], ^, _, {, }, |, ~, ,

Returns

  • 0: Success.
  • < 0: Failure.
    • -2: Invalid parameter.
    • -8: The current connection state is not true.

Disconnect

Disconnects from the RTC channel. When the SDK disconnects from the channel, the connection state changes to true. You can also be notified through the OnDisconnected callback.

func (conn *RtcConnection) Disconnect() int

Returns

  • 0: Success.
  • < 0: Failure.

RenewToken

Renews the Token. The Token will expire after a certain period. When you receive the OnTokenPrivilegeWillExpire callback, you must generate a new token from your server and use this method to update the token. Otherwise, the SDK will disconnect from the channel.

func (conn *RtcConnection) RenewToken(token string) int

Parameters

ParameterDescription
tokenThe new Token.

Returns

  • 0: Success.
  • < 0: Failure.

RegisterObserver

Registers an RTC connection observer.

func (conn *RtcConnection) RegisterObserver(handler *RtcConnectionObserver) int

Parameters

ParameterDescription
handlerRtcConnectionObserver object.

Returns

  • 0: Success.
  • < 0: Failure.

UnregisterObserver

Unregisters the RTC connection observer.

func (conn *RtcConnection) UnregisterObserver() int

Returns

  • 0: Success.
  • < 0: Failure.

CreateDataStream

Creates a data stream.

func (conn *RtcConnection) CreateDataStream(reliable bool, ordered bool) (int, int)

Each user can create up to 5 data streams per channel.

Note

  • Agora does not support setting reliable to true and ordered to false.
  • When immediate data packet delivery is required, do not set the ordered parameter to true.

Parameters

ParameterDescription
reliableIndicates whether the data stream is reliable: - true: The receiver will receive the data sent by the sender within 5 seconds. - false: The receiver is not guaranteed to receive the data, and no error will be reported if data is lost.
orderedIndicates whether the data stream is ordered: - true: The receiver will receive data packets in the order sent by the sender. - false: The receiver is not guaranteed to receive data packets in the order sent by the sender.

Returns

  • stream_id: The stream ID, if the method call succeeds.
  • nil, if the method call fails.

SendStreamMessage

Sends a data stream message.

func (conn *RtcConnection) SendStreamMessage(streamId int, msg []byte) int

This method sends a data stream message to all users in the channel. The SDK imposes the following restrictions on this method:

  • A maximum of 30 packets can be sent per second within the channel, with each packet being up to 1 KB in size.
  • Each client can send up to 6 KB of data per second.
  • Each user in the channel can have up to 5 data channels simultaneously.

Upon successfully calling this method, the remote end will trigger the OnStreamMessage callback, where the remote user can receive the stream message.

Note

  • Ensure that you have called CreateDataStream to create a data channel before using this method.
  • In a live broadcast use-case, this method is only applicable to host users.

Parameters

ParameterDescription
stream_idThe data stream ID. It can be obtained through CreateDataStream.
dataThe data to be sent.

Returns

  • 0: Success.
  • < 0: Failure.

GetAgoraParameter

Get AgoraParameter object.

func (conn *RtcConnection) GetAgoraParameter() *AgoraParameter

Returns

  • AgoraParameter object, if the method call was succeeds.
  • nil, if the method call fails.

GetLocalUser

Get LocalUser Object. Each connection corresponds to only one local user.

func (conn *RtcConnection) GetLocalUser() *LocalUser

Returns

  • LocalUser object, if the method call succeeds.
  • nil, if the method call fails.

Release

Releases the RTC connection.

func (conn *RtcConnection) Release()

EnableEncryption

func (conn *RtcConnection) EnableEncryption(enable int, config *EncryptionConfig) int

Enables encryption.

Since

v2.2.4.

This method needs to be called before Connect. You need to set the encryption mode and encryption configuration in this method.

Parameters

enable

Whether to enable encryption functionality.

  • 1: Enable
  • 0: Disable

config

The encryption configuration: EncryptionConfig.

Return Values

  • 0: Success.
  • < 0: Failure.

RtcConnectionObserver

The RtcConnectionObserver class is used to monitor the SDK connection state.

OnConnected

Triggered when the SDK's connection state to the channel changes to 3.

OnConnected func(con *RtcConnection, conInfo *RtcConnectionInfo, reason int)

Parameters

con

The RTC connection object. See RtcConnection for details.

conInfo

Connection information. See RtcConnectionInfo for details.

reason

Connection state change reason:

  • 0: Establishing a network connection.

  • 1: Successfully joined the channel.

  • 2: Network connection interrupted.

  • 3: Network connection forbidden by the server.

  • 4: Failed to join the channel.

  • 5: Left the channel.

  • 6: Invalid App ID. Please change to a valid App ID and try again.

  • 7: Invalid channel name. Please change to a valid channel name and try again.

  • 8: The generated token is invalid. Generally, the following reasons:

    • App Certificate is enabled on the console, but the Token is not used when joining the channel. When App Certificate is enabled, you must use a Token.
    • The uid specified in connect when joining the channel does not match the uid used when generating the Token.
  • 9: The generated Token is invalid.

  • 10: This user is banned by the server.

  • 11: SDK attempts to reconnect due to setting a proxy server.

  • 12: The network connection state changes due to updating the Token.

  • 13: The client IP address changes, possibly due to changes in network type or the IP or port of the network operator.

  • 14: SDK connection to the server times out, enters the automatic reconnection state.

  • 15: Rejoined the channel successfully.

  • 16: SDK and the server lose connection.

  • 17: The connection state changes due to the echo test.

  • 18: The user changed the local IP address.

OnDisconnected

Triggered when the SDK's connection state to the channel changes to 1.

OnDisconnected func(con *RtcConnection, conInfo *RtcConnectionInfo, reason int)

Parameters

con

RTC connection object. See RtcConnection for details.

conInfo

Connection information. See RtcConnectionInfo for details.

reason

Connection state change reason:

  • 0: Establishing a network connection.

  • 1: Successfully joined the channel.

  • 2: Network connection interrupted.

  • 3: Network connection forbidden by the server.

  • 4: Failed to join the channel.

  • 5: Left the channel.

  • 6: Invalid App ID. Please change to a valid App ID and try again.

  • 7: Invalid channel name. Please change to a valid channel name and try again.

  • 8: The generated token is invalid. Generally, the following reasons:

    • App Certificate is enabled on the console, but the Token is not used when joining the channel. When App Certificate is enabled, you must use a Token.
    • The uid specified in connect when joining the channel does not match the uid used when generating the Token.
  • 9: The generated Token is invalid.

  • 10: This user is banned by the server.

  • 11: SDK attempts to reconnect due to setting a proxy server.

  • 12: The network connection state changes due to updating the Token.

  • 13: The client IP address changes, possibly due to changes in network type or the IP or port of the network operator.

  • 14: SDK connection to the server times out, enters the automatic reconnection state.

  • 15: Rejoined the channel successfully.

  • 16: SDK and the server lose connection.

  • 17: The connection state changes due to the echo test.

  • 18: The user changed the local IP address.

OnTokenPrivilegeWillExpire

Triggered when the token is about to expire within 30 seconds.

OnTokenPrivilegeWillExpire func(con *RtcConnection, token string)

During a call, if the token is about to expire, the SDK will trigger this callback 30 seconds in advance to remind the app to update the token.

Upon receiving this callback, you need to generate a new token on your server and then call RenewToken to pass the newly generated token to the SDK.

Parameters

ParameterDescription
conRTC connection object. See RtcConnection for details.
tokenThe token that is about to expire.

OnTokenPrivilegeDidExpire

Triggered when the token has expired.

OnTokenPrivilegeDidExpire func(con *RtcConnection)

During a call, if the token has expired, the SDK will trigger this callback to remind the app to update the token.

Upon receiving this callback, you need to generate a new token on your server and then call Connect to reconnect to the channel.

Parameters

ParameterDescription
conRTC connection object. See RtcConnection for details.

OnUserJoined

Triggered when a remote user joins the channel. You can use this callback to get the ID of the remote user.

OnUserJoined func(con *RtcConnection, uid string)

Parameters

ParameterDescription
conRTC connection object. See RtcConnection for details.
uidUser ID of the remote user.

OnUserLeft

Triggered when a remote user leaves the channel. You can use the reason parameter to get the reason why the user left the channel.

OnUserLeft func(con *RtcConnection, uid string, reason int)

Parameters

con

RTC connection object. See RtcConnection for details.

uid

User ID of the remote user.

reason

Connection state change reason:

  • 0: Establishing a network connection.

  • 1: Successfully joined the channel.

  • 2: Network connection interrupted.

  • 3: Network connection forbidden by the server.

  • 4: Failed to join the channel.

  • 5: Left the channel.

  • 6: Invalid App ID. Please change to a valid App ID and try again.

  • 7: Invalid channel name. Please change to a valid channel name and try again.

  • 8: The generated token is invalid. Generally, the following reasons:

    • App Certificate is enabled on the console, but the Token is not used when joining the channel. When App Certificate is enabled, you must use a Token.
    • The uid specified in connect when joining the channel does not match the uid used when generating the Token.
  • 9: The generated Token is invalid.

  • 10: This user is banned by the server.

  • 11: SDK attempts to reconnect due to setting a proxy server.

  • 12: The network connection state changes due to updating the Token.

  • 13: The client IP address changes, possibly due to changes in network type or the IP or port of the network operator.

  • 14: SDK connection to the server times out, enters the automatic reconnection state.

  • 15: Rejoined the channel successfully.

  • 16: SDK and the server lose connection.

  • 17: The connection state changes due to the echo test.

  • 18: The user changed the local IP address.

OnStreamMessageError

Triggered when an error occurs in receiving stream messages. This callback indicates that the local user did not receive the stream message sent by the remote user using the send_stream_message method.

OnStreamMessageError func(con *RtcConnection, uid string, streamId int, errCode int, missed int, cached int)

Parameters

ParameterDescription
conRTC connection object. See RtcConnection for details.
uidUser ID of the sender.
streamIdStream ID of the received message.
errCodeError code of the occurred error.
missedNumber of missed messages.
cachedNumber of cached messages when the stream was interrupted.

OnError

Triggered when an error occurs. This callback method indicates that a network or media-related error occurred while the SDK was running. Generally, errors reported by the SDK mean that the SDK cannot automatically recover and requires intervention from the app or user notification.

OnError func(con *RtcConnection, err int, msg string)

Parameters

ParameterDescription
conRTC connection object. See RtcConnection for details.
errError code.
msgError description.

OnEncryptionError

OnEncryptionError func(con *RtcConnection, err int)

Occurs when encryption errors occur.

Since

v2.2.4.

Parameters

ParameterDescription
conRtcConnection object.
errError code.

LocalUser

The LocalUser class defines the behavior and state of the local user. Each RTC connection has its own user. You can get the local user through GetLocalUser. Each user has two roles: broadcaster (can send and receive audio and video streams) and audience (can only receive audio and video streams).

SetUserRole

Sets the user role. You can call this method before or after the user connects to the channel.

func (localUser *LocalUser) SetUserRole(role int) int

Note

If the role set in the token parameter of Connect is different from the role set here, the connection will fail.

Parameters

ParameterDescription
roleUser role. See ClientRole for details.

Returns

  • 0: Success.
  • < 0: Failure.

SetAudioEncoderConfiguration

Sets audio encoding. The SDK will apply the configuration to all sent audio tracks.

func (localUser *LocalUser) SetAudioEncoderConfiguration(config *AudioEncoderConfiguration) int

Parameters

ParameterDescription
configAudio encoding configuration. See AudioEncoderConfiguration for details.

Returns

  • 0: Success.
  • < 0: Failure.

PublishAudio

Sends the local audio track to the channel. By default, all published audio tracks are mixed.

func (localUser *LocalUser) PublishAudio(track *LocalAudioTrack) int

Parameters

ParameterDescription
trackThe local audio track to be published. See LocalAudioTrack for details.

Returns

  • 0: Success.
  • < 0: Failure.
    • -5: Returned if the local user's role is not a broadcaster.

UnpublishAudio

Stops sending the local audio track to the channel.

func (localUser *LocalUser) UnpublishAudio(track *LocalAudioTrack) int

Parameters

ParameterDescription
trackThe local audio track to stop publishing. See LocalAudioTrack for details.

Returns

  • 0: Success.
  • < 0: Failure.

PublishVideo

Sends the local video track to the channel.

func (localUser *LocalUser) PublishVideo(track *LocalVideoTrack) int

Parameters

ParameterDescription
trackThe local video track to be published. See LocalVideoTrack for details.

Returns

  • 0: Success.
  • < 0: Failure.

UnpublishVideo

Stops sending the local video track to the channel.

func (localUser *LocalUser) UnpublishVideo(track *LocalVideoTrack) int

Parameters

ParameterDescription
trackThe local video track to stop publishing. See LocalVideoTrack for details.

Returns

  • 0: Success.
  • < 0: Failure.

SubscribeAudio

Subscribes to the audio stream sent by a specific remote user in the channel.

func (localUser *LocalUser) SubscribeAudio(uid string) int

Parameters

ParameterDescription
uidThe user ID of the remote user.

Returns

  • 0: Success.
  • < 0: Failure.
    • -2: Error returned if the user does not exist or the uid is invalid.

SubscribeAllAudio

Subscribes to the audio streams sent by all remote users in the channel. This method will automatically subscribe to the audio streams of users who join the channel later.

func (localUser *LocalUser) SubscribeAllAudio() int

Returns

  • 0: Success.
  • < 0: Failure.

UnsubscribeAudio

Stops subscribing to the audio stream sent by a specific remote user in the channel.

func (localUser *LocalUser) UnsubscribeAudio(uid string) int

Parameters

ParameterDescription
uidThe user ID of the remote user.

Returns

  • 0: Success.
  • < 0: Failure.
    • -2: Error returned if the user does not exist or the uid is invalid.

UnsubscribeAllAudio

Stops subscribing to the audio streams sent by all remote users in the channel. This method will automatically unsubscribe from the audio streams of users who join the channel later. You must call SubscribeAudio or SubscribeAllAudio to resume subscribing to audio.

func (localUser *LocalUser) UnsubscribeAllAudio() int

Returns

  • 0: Success.
  • < 0: Failure.

SetPlaybackAudioFrameBeforeMixingParameters

Sets the playback audio format. This method sets the format of the data for the OnPlaybackAudioFrameBeforeMixing callback.

func (localUser *LocalUser) SetPlaybackAudioFrameBeforeMixingParameters(channels int, sampleRate int) int

Parameters

ParameterDescription
channelsThe number of audio channels. Can be set to 1 (mono) or 2 (stereo).
sampleRateThe sampling rate of the audio data. Can be set to 8000, 16000, 32000, 44100, or 48000.

Returns

  • 0: Success.
  • < 0: Failure.

RegisterAudioFrameObserver

Registers the audio frame observer. You must implement the AudioFrameObserver class and register the callbacks as needed.

func (localUser *LocalUser) RegisterAudioFrameObserver(observer *AudioFrameObserver, enableVad int, vadConfigure *AudioVadConfigV2) int

Parameters

observer

An instance of the AudioFrameObserver class.

enableVad

Whether to enable the built-in voice activity detection (VAD):

vadConfigure

The VAD configuration, an AudioVadConfigV2 object. The SDK uses this parameter only when enableVad is 1.

Returns

  • 0: Success.
  • < 0: Failure.

UnregisterAudioFrameObserver

Destroys the AudioFrameObserver object.

func (localUser *LocalUser) UnregisterAudioFrameObserver() int

Returns

  • 0: Success.
  • < 0: Failure.

SubscribeVideo

Subscribes to the video stream sent by a specified remote user in the channel.

func (localUser *LocalUser) SubscribeVideo(uid string, options *VideoSubscriptionOptions) int

Parameters

ParameterDescription
uidThe user ID of the remote user.
optionsSubscription options. See VideoSubscriptionOptions for details.

Returns

  • 0: Success.
  • < 0: Failure.
    • -2: Error returned if the user does not exist or the uid is invalid.

SubscribeAllVideo

Subscribes to the video streams sent by all remote users in the channel. This method automatically subscribes to the video streams of users who join the channel later.

func (localUser *LocalUser) SubscribeAllVideo(options *VideoSubscriptionOptions) int

Parameters

ParameterDescription
optionsSubscription options. See VideoSubscriptionOptions for details.

Returns

  • 0: Success.
  • < 0: Failure.

UnsubscribeVideo

Stops subscribing to the video stream sent by a specified remote user in the channel.

func (localUser *LocalUser) UnsubscribeVideo(uid string) int

Parameters

ParameterDescription
uidThe user ID of the remote user.

Returns

  • 0: Success.
  • < 0: Failure.
    • -2: Error returned if the user does not exist or the uid is invalid.

UnsubscribeAllVideo

Stops subscribing to the video streams sent by all remote users in the channel. This method automatically unsubscribes from the video streams of users who join the channel later. You must call SubscribeVideo or SubscribeAllVideo to resume the subscription.

func (localUser *LocalUser) UnsubscribeAllVideo() int

Returns

  • 0: Success.
  • < 0: Failure.

RegisterLocalUserObserver

Registers a local user observer.

func (localUser *LocalUser) RegisterLocalUserObserver(observer *LocalUserObserver) int

Parameters

ParameterDescription
observerThe LocalUserObserver class.

Returns

  • 0: Success.
  • < 0: Failure.

UnregisterLocalUserObserver

Destroys the local user observer.

func (localUser *LocalUser) UnregisterLocalUserObserver() int

Returns

  • 0: Success.
  • < 0: Failure.

RegisterVideoFrameObserver

Registers a VideoFrameObserver object.

func (localUser *LocalUser) RegisterVideoFrameObserver(observer *VideoFrameObserver) int

Parameters

ParameterDescription
observerThe VideoFrameObserver class.

Returns

  • 0: Success.
  • < 0: Failure.

UnregisterVideoFrameObserver

Destroys the VideoFrameObserver object.

func (localUser *LocalUser) UnregisterVideoFrameObserver() int

Returns

  • 0: Success.
  • < 0: Failure.

GetRtcConnection

Gets the RtcConnection object.

func (localUser *LocalUser) GetRtcConnection() *RtcConnection

Returns

  • RtcConnection object, if the method call succeeds.
  • nil, if the method call fails.

SendAudioMetaData

func (localUser *LocalUser) SendAudioMetaData(metaData []byte) int

Sends the audio metadata.

Since

v2.2.0.

A successful call triggers the OnAudioMetaDataReceived callback on the remote end. The remote user can get the audio metadata in this callback.

Parameters

ParameterDescription
metaDataThe audio metadata.

Returns

  • 0: Success.
  • < 0: Failure.

LocalUserObserver

The LocalUserObserver class.

OnUserAudioTrackStateChanged

Triggered when the state of a remote audio track changes.

OnUserAudioTrackStateChanged func(localUser *LocalUser, uid string, remoteAudioTrack *RemoteAudioTrack, state int, reason int, elapsed int)

Parameters

ParameterDescription
localUserLocalUserObserver class.
uidRemote user ID.
remoteAudioTrackRemote audio track.
stateCurrent state of the audio track.
reasonReason for the state change.
elapsedTime elapsed (in milliseconds) since the remote user joined the channel.

OnStreamMessage

Callback for receiving stream messages. This callback indicates that the local user has received a stream message sent by a remote user using the SendStreamMessage method.

OnStreamMessage func(localUser *LocalUser, uid string, streamId int, data []byte)

Parameters

ParameterDescription
localUserLocalUserObserver class.
uidUser ID of the sender.
streamIdStream ID of the received message.
dataReceived data.

OnUserInfoUpdated

Triggered when user media information is updated.

OnUserInfoUpdated func(localUser *LocalUser, uid string, userMediaInfo int, val int)

Parameters

ParameterDescription
localUserLocalUser class.
uidUser ID.
userMediaInfoUser media information. See UserMediaInfo for details.
valWhether the user has stopped sending streams. - 0: Not stopped. - 1: Stopped.

OnAudioMetaDataReceived

OnAudioMetaDataReceived func(localUser *LocalUser, uid string, metaData []byte)

Occurs when the remote audio metadata is received.

This callback indicates that the local user has received the audio metadata sent by the remote user using the SendAudioMetaData method.

Since

v2.2.0.

Parameters

ParameterDescription
localUserLocalUser class.
uidThe UID of the remote user.
metaDataThe audio metadata.

LocalAudioTrack

The LocalAudioTrack class is the base class for local audio tracks.

NewCustomAudioTrackPcm

Creates a custom PCM data track.

func NewCustomAudioTrackPcm(pcmSender *AudioPcmDataSender) *LocalAudioTrack

Parameters

ParameterDescription
pcmSenderAudioPcmDataSender object.

Returns

  • LocalAudioTrack object, if the method call succeeds.
  • nil, if the method call fails.

NewCustomAudioTrackEncoded

Creates a custom encoded data track.

func NewCustomAudioTrackEncoded(encodedAudioSender *AudioEncodedFrameSender, mixMode AudioTrackMixingState) *LocalAudioTrack

Parameters

ParameterDescription
encodedAudioSenderAudioEncodedFrameSender object.
mixModeAudio track mixing mode.

Returns

  • LocalAudioTrack object, if the method call succeeds.
  • nil, if the method call fails.

SetEnabled

Enables or disables the local audio track. Once enabled, the SDK can capture, process, and encode local audio.

func (track *LocalAudioTrack) SetEnabled(enable bool)

Parameters

ParameterDescription
enableWhether to enable the audio track: - true: Enable the audio track. - false: Disable the audio track.

AdjustPublishVolume

Adjusts the audio publish volume.

func (track *LocalAudioTrack) AdjustPublishVolume(volume int) int

Parameters

ParameterDescription
volumeAudio publish volume. The range is [0, 100], where 0 means mute, and 100 means the original volume.

Returns

  • 0: Success.
  • < 0: Failure.

SetMaxBufferedAudioFrameNumber

Sets the maximum capacity of the audio send buffer.

func (track *LocalAudioTrack) SetMaxBufferedAudioFrameNumber(frameNum int)

In applications like AI interaction, the frequency of sending audio frames from the sender may be irregular. For example, sometimes 1 frame is sent every 20 ms, and sometimes 3 frames are sent every 20 ms. If the SDK sends data to the Agora server based on the actual sending frequency, the receiver may experience stuttering or frame drops. To optimize audio transmission performance, the SDK sets an audio send buffer. Regardless of the actual frequency of sending audio frames, the SDK stores the data in the audio send buffer. Once the data in the audio send buffer reaches the minimum duration allowed to be sent, the SDK starts sending data to the receiver at a rate of 10 ms per frame.

The default maximum capacity of the audio send buffer in the SDK is 6000 frames, which means it can store up to 6000 frames of data, or 60 seconds of data. If you need a larger buffer capacity, you can call this method to adjust it. If you also need to set the minimum duration of data allowed to be sent in the audio send buffer, call the SetSendDelayMs method.

Caution

This method should be called before the PublishAudio method.

Parameters

ParameterDescription
frameNumThe maximum number of audio frames stored in the buffer. For example, setting it to 6000 means 6000 frames of audio data.

ClearSenderBuffer

Clears the current audio send buffer.

func (track *LocalAudioTrack) ClearSenderBuffer() int

If you no longer need the data in the current audio send buffer, you can call this method to clear the buffer. For example, if a user asks an AI a question and the AI is transmitting audio to the user through the SDK, the SDK's audio send buffer continuously has data in and out. When the user interrupts the AI's response and asks another question, you can call this method to let the SDK clear the current unsent buffered data to quickly buffer the AI's response to the new topic.

Returns

  • 0: Success.
  • < 0: Failure.

SetSendDelayMs

Sets the minimum duration of data allowed to be sent in the audio send buffer.

func (track *LocalAudioTrack) SetSendDelayMs(delayMs int) int

The SDK's default minimum duration of data allowed to be sent is 160 ms. This means the SDK will wait until the audio send buffer is filled with 160 ms of data before sending it to the receiver, which has the following effects:

  • If the sender sends data greater than or equal to 160 ms at a time, such as 800 ms, the SDK will immediately start sending data to the receiver at a rate of 10 ms per frame.
  • If the sender sends data less than 160 ms at a time, such as 100 ms, the SDK will wait until the buffer has 160 ms of data before sending it to the receiver at a rate of 10 ms per frame. This can cause a delay of up to 60 ms.

You can adjust the minimum duration of data allowed to be sent in the buffer according to your actual business needs by calling this method.

Parameters

ParameterDescription
delayMsThe minimum duration of data allowed to be sent in the buffer (ms). This parameter needs to be set to a multiple of 10, and the value range is greater than 0 and less than 10 times the value of the frameNum parameter in the SetMaxBufferedAudioFrameNumber method.

Release

Releases the local audio track resources.

func (track *LocalAudioTrack) Release()

LocalVideoTrack

The LocalVideoTrack class provides basic methods for local video tracks. You can publish one or more video tracks using the PublishVideo method.

NewCustomVideoTrackFrame

Creates a local video track object with a video source that sends YUV format video data. This track object can be used to send YUV format video data.

func NewCustomVideoTrackFrame(videoSender *VideoFrameSender) *LocalVideoTrack

Parameters

ParameterDescription
videoSenderYUV format video source object. See VideoFrameSender for details.

Returns

  • LocalVideoTrack object: If the method call succeeds.
  • nil: If the method call fails.

NewCustomVideoTrackEncoded

Creates a local video track object with a video source that sends encoded video data. This track object can be used to send encoded video data, such as H.264 or VP8 format encoded data.

func NewCustomVideoTrackEncoded(videoSender *VideoEncodedImageSender, senderOptions *VideoEncodedImageSenderOptions) *LocalVideoTrack

Parameters

ParameterDescription
videoSenderVideo source for sending encoded video data. See VideoEncodedImageSender for details.
senderOptionsVideo track settings. See VideoEncodedImageSenderOptions for details.

Returns

  • LocalVideoTrack object: If the method call succeeds.
  • nil: If the method call fails.

SetEnabled

Enables or disables the local video track. After the local video track is enabled, the SDK can capture, process, and encode local video.

func (track *LocalVideoTrack) SetEnabled(enable bool)

Parameters

ParameterDescription
enableEnable or disable the local video track: - false: Disable the local video track. - true: Enable the local video track.

SetVideoEncoderConfiguration

Sets the video encoding properties.

func (track *LocalVideoTrack) SetVideoEncoderConfiguration(cfg *VideoEncoderConfiguration) int

Parameters

ParameterDescription
cfgVideo encoding parameter configuration. See VideoEncoderConfiguration for details.

Returns

  • 0: If the method call succeeds.
  • < 0: If the method call fails.

MediaNodeFactory

The MediaNodeFactory class.

NewMediaNodeFactory

Creates a media node factory object.

func NewMediaNodeFactory() *MediaNodeFactory

Returns

  • MediaNodeFactory object, if the method call succeeds.
  • nil, if the method call fails.

Release

Releases the MediaNodeFactory object.

func (factory *MediaNodeFactory) Release()

AudioEncodedFrameSender

The AudioEncodedFrameSender class.

NewAudioEncodedFrameSender

Creates an encoded audio data sending module. This method creates an AudioEncodedFrameSender object, which can be used in the NewCustomAudioTrackEncoded method.

func (mediaNodeFactory *MediaNodeFactory) NewAudioEncodedFrameSender() *AudioEncodedFrameSender

Returns

  • AudioEncodedFrameSender object, if the method call succeeds.
  • nil, if the method call fails.

SendEncodedAudioFrame

Sends the encoded audio frame to the local audio track.

func (sender *AudioEncodedFrameSender) SendEncodedAudioFrame(payload []byte, frameInfo *EncodedAudioFrameInfo) int

Parameters

ParameterDescription
payloadThe encoded audio data to send.
frameInfoInformation about the audio frame, see EncodedAudioFrameInfo for details.

Returns

  • 0: Success.
  • < 0: Failure.

Release

Releases the AudioEncodedFrameSender object.

func (sender *AudioEncodedFrameSender) Release()

AudioPcmDataSender

The AudioPcmDataSender class.

NewAudioPcmDataSender

Creates a PCM data sender module. This method creates an AudioPcmDataSender object, which can be used in the NewCustomAudioTrackPcm method.

func (mediaNodeFactory *MediaNodeFactory) NewAudioPcmDataSender() *AudioPcmDataSender

Returns

  • AudioPcmDataSender object, if the method call succeeds.
  • nil, if the method call fails.

SendAudioPcmData

Sends PCM format audio data to the local audio track.

func (sender *AudioPcmDataSender) SendAudioPcmData(frame *AudioFrame) int

Parameters

ParameterDescription
frameAudioFrame object containing the PCM audio data to be sent.

Returns

  • 0: Success.
  • < 0: Failure.

Release

Releases the AudioPcmDataSender object.

func (sender *AudioPcmDataSender) Release()

AudioFrameObserver

The AudioFrameObserver class.

OnPlaybackAudioFrameBeforeMixing

Obtains the audio data before mixing for playback.

OnPlaybackAudioFrameBeforeMixing func(localUser *LocalUser, channelId string, uid string, frame *AudioFrame, vadResultStat VadState, vadResultFrame *AudioFrame) bool

Parameters

localUser

LocalUser class.

channelId

Channel name.

uid

User ID of the remote user.

frame

Raw audio data. See AudioFrame for details.

vadResultStat

The VAD state. Valid only when you enable VAD in RegisterAudioFrameObserver:

  • -1 (VadStateInvalid): VAD is not enabled.
  • 0 (VadStateNoSpeeking): Not speaking.
  • 1 (VadStateStartSpeeking): Started speaking.
  • 2 (VadStateSpeeking): Speaking.
  • 3 (VadStateStopSpeeking): Stopped speaking.

vadResultFrame

The audio data processed by VAD. When VAD is enabled, use this data instead of frame for downstream processing, such as speech recognition.

Returns

  • true: The audio frame data is valid and will be sent.
  • false: The audio frame data is invalid and will be discarded.

VideoEncodedImageSender

The VideoEncodedImageSender class.

NewVideoEncodedImageSender

Creates a video encoded data sender module. This method creates a VideoEncodedImageSender object, which can be used in the NewCustomVideoTrackEncoded method.

func (mediaNodeFactory *MediaNodeFactory) NewVideoEncodedImageSender() *VideoEncodedImageSender

Returns

  • VideoEncodedImageSender object, if the method call succeeds.
  • nil, if the method call fails.

SendEncodedVideoImage

Sends an encoded video frame to the video track.

func (sender *VideoEncodedImageSender) SendEncodedVideoImage(payload []byte, frameInfo *EncodedVideoFrameInfo) int

Parameters

ParameterDescription
payloadThe video buffer.
frameInfoThe encoded video frame information. See EncodedVideoFrameInfo for details.

Returns

  • 0: Success.
  • < 0: Failure.

VideoEncodedFrameObserver

The VideoEncodedFrameObserver class.

OnEncodedVideoFrame

Occurs when an encoded video frame is received.

OnEncodedVideoFrame func(uid string, imageBuffer []byte, frameInfo *EncodedVideoFrameInfo) bool

Parameters

ParameterDescription
uidThe user ID of the remote user.
imageBufferThe video frame buffer.
frameInfoThe encoded video frame information. See EncodedVideoFrameInfo for details.

Returns

Whether to accept the encoded video frame:

  • true: Accept.
  • false: Do not accept.

VideoFrameSender

The VideoFrameSender class.

NewVideoFrameSender

Creates a raw video data sender module. This method creates a VideoFrameSender object, which can be used in the NewCustomVideoTrackFrame method.

func (mediaNodeFactory *MediaNodeFactory) NewVideoFrameSender() *VideoFrameSender

Returns

  • VideoFrameSender object, if the method call succeeds.
  • nil, if the method call fails.

SendVideoFrame

Sends a YUV format video frame to the video track.

func (sender *VideoFrameSender) SendVideoFrame(frame *ExternalVideoFrame) int

Parameters

ParameterDescription
frameThe video frame to send. See ExternalVideoFrame for details.

Returns

  • 0: Success.
  • < 0: Failure.

VideoFrameObserver

The VideoFrameObserver class.

OnFrame

Triggered when a video frame is received.

OnFrame func(channelId string, userId string, frame *VideoFrame) bool

Parameters

ParameterDescription
channelIdThe channel name.
userIdThe user ID of the remote user.
frameThe video data. See VideoFrame for details.

Data type

Classes

AgoraServiceConfig

Global configuration for the AgoraServiceConfig class, set when calling the Initialize method.

type AgoraServiceConfig struct {
    EnableAudioProcessor bool
    EnableAudioDevice    bool
    EnableVideo          bool
    AppId                string
    AreaCode             AreaCode
    ChannelProfile       ChannelProfile
    AudioScenario        AudioScenario
    UseStringUid         bool
    LogPath              string
    LogSize              int
    DomainLimit          int
    ShouldCallbackWhenMuted int
    EnableSteroEncodeMode   int
}

EnableAudioProcessor

Whether to enable the audio processing module. - true: (Default) Enable the audio processing module. - false: Disable the audio processing module. You will not be able to create audio tracks.

EnableAudioDevice

Whether to enable the Audio Device Module (ADM). ADM is used to manage audio devices, such as recording and playing audio. - true: (Default) Enable the audio device module. You can record and play audio. - false: Disable the audio device module. You cannot record or play audio. Note: If you set EnableAudioDevice to false and EnableAudioProcessor to true, you will not be able to use audio devices, but you can push PCM audio data.

EnableVideo

Whether to enable video. - true: Enable video. - false: (Default) Disable video.

AppId

Your Agora project App ID. If your Agora project has token authentication enabled, you can also set this parameter to the RTC Token. See Get App ID for details.

AreaCode

Server access area. This feature is an advanced setting and is applicable to use-cases with access security restrictions. Area codes support bitwise operations. After specifying the access area, the SDK connects to the Agora servers within the specified area. See AreaCode for details.

ChannelProfile

Channel use-case. See ChannelProfile for details.

AudioScenario

Audio encoding properties. See AudioScenario for details.

UseStringUid

Whether to use String user ID. - true: Use. - false: Do not use.

LogPath

Log file path.

LogSize

Log file size (in bytes).

DomainLimit

Whether to enable domain limit:

  • 1: Yes. Only connects to domains that are parsed by DNS
  • 0: (Default) No. There is no limit when connecting to domains

ShouldCallbackWhenMuted

Whether the SDK still triggers the OnPlaybackAudioFrameBeforeMixing callback after a remote user mutes their audio:

  • 0: (Default) No. The SDK stops triggering the callback when the remote user mutes their audio.
  • Greater than 0: Yes. The SDK keeps triggering the callback when the remote user mutes their audio.

EnableSteroEncodeMode

Whether to enable stereo encoding mode:

  • 0: (Default) No.
  • Greater than 0: Yes. Each connection uses the AudioScenarioGameStreaming audio scenario and the AudioProfileMusicHighQualityStereo audio profile, with echo cancellation, noise suppression, and automatic gain control disabled. The encoding bitrate is 32 Kbps.

AudioEncoderConfiguration

Audio encoding settings.

type AudioEncoderConfiguration struct {
    AudioProfile int
}
ParameterDescription
AudioProfileAudio scenarios:- 0: Default audio scenario.- In communication scenario: 16 KHz sampling rate, voice encoding, mono, maximum encoding bitrate of 16 Kbps. - In live broadcast scenario: 48 KHz sampling rate, music encoding, mono, maximum encoding bitrate of 64 Kbps. - 1: Specifies 32 KHz sampling rate, voice encoding, mono, maximum encoding bitrate of 18 Kbps. - 2: Specifies 48 KHz sampling rate, music encoding, mono, maximum encoding bitrate of 64 Kbps. - 3: Specifies 48 KHz sampling rate, music encoding, stereo, maximum encoding bitrate of 80 Kbps. - 4: Specifies 48 KHz sampling rate, music encoding, mono, maximum encoding bitrate of 96 Kbps. - 5: Specifies 48 KHz sampling rate, music encoding, stereo, maximum encoding bitrate of 128 Kbps. - 6: Specifies 16 KHz sampling rate, voice encoding, mono, applies Acoustic Echo Cancellation (AEC) algorithm.

AudioFrame

PCM audio data.

type AudioFrame struct {
    Type              AudioFrameType
    SamplesPerChannel int
    BytesPerSample    int
    Channels          int
    SamplesPerSec     int
    Buffer            []byte
    RenderTimeMs      int64
    AvsyncType        int
    FarFieldFlag      int
    Rms               int
    VoiceProb         int
    MusicProb         int
    Pitch             int
}
ParameterDescription
TypeAudio frame type. See AudioFrameType.
SamplesPerChannelNumber of audio samples collected in 10 milliseconds for each channel.
BytesPerSampleNumber of bytes per sample.
ChannelsNumber of channels per sample.
SamplesPerSecSampling rate (Hz). Minimum value is 8000.
BufferPCM audio data to be sent.
RenderTimeMsTimestamp (in milliseconds) when the audio data was collected.
AvsyncTypeAudio-video synchronization type.
FarFieldFlagThe far-field flag of the audio frame. Only used in audio frame observer callbacks.
RmsThe root mean square (RMS) of the audio frame. Only used in audio frame observer callbacks.
VoiceProbThe probability that the audio frame contains voice. Only used in audio frame observer callbacks.
MusicProbThe probability that the audio frame contains music. Only used in audio frame observer callbacks.
PitchThe pitch of the audio frame. Only used in audio frame observer callbacks.

EncodedAudioFrameInfo

Encoded audio data.

type EncodedAudioFrameInfo struct {
    Speech bool
    Codec AudioCodecType
    SampleRateHz int
    SamplesPerChannel int
    SendEvenIfEmpty bool
    NumberOfChannels int
}
ParameterDescription
SpeechIndicates whether the audio source is speech: - 0: The audio source is not speech. - 1: (Default) The audio source is speech.
CodecAudio codec type. See AudioCodecType.
SampleRateHzSampling rate of the audio frame (Hz).
SamplesPerChannelNumber of samples per channel. Defaults to 1024 for AAC codec format and 960 for Opus codec format.
SendEvenIfEmptyIndicates whether to send an empty audio frame: - 0: Do not send an empty audio frame. - 1: (Default) Send an empty audio frame.
NumberOfChannelsNumber of channels in the audio frame.

EncodedVideoFrameInfo

Encoded video data.

type EncodedVideoFrameInfo struct {
    CodecType        VideoCodecType
    Width            int
    Height           int
    FramesPerSecond  int
    FrameType        VideoFrameType
    Rotation         VideoOrientation
    TrackId          int
    CaptureTimeMs    int64
    DecodeTimeMs     int64
    Uid              uint32
    StreamType       int
}
ParameterDescription
CodecTypeVideo codec type. See VideoCodecType.
WidthWidth of the video frame (pixels).
HeightHeight of the video frame (pixels).
FramesPerSecondNumber of video frames per second. Used to calculate the timestamp for the encoded video frame. If set to 0, the SDK uses the real timestamp.
FrameTypeType of encoded video frame. See VideoFrameType.
RotationRotation information of the encoded video frame. See VideoOrientation.
TrackIDTrack ID of the video frame.
CaptureTimeMsUnix timestamp (milliseconds) for capturing the external encoded video frame.
DecodeTimeMsTimestamp (milliseconds) for decoding the external encoded video frame.
UIDUser ID.
StreamTypeStream type of the video frame: - 0: High stream. Higher resolution and bitrate. - 1: Low stream. Lower resolution and bitrate.

EncryptionConfig

type EncryptionConfig struct {
	EncryptionMode int
	EncryptionKey string
	EncryptionKdfSalt []byte
}

EncryptionMode

Encryption mode:

  • 1: 128-bit AES encryption, XTS mode.
  • 2: 128-bit AES encryption, ECB mode.
  • 3: 256-bit AES encryption, XTS mode.
  • 4: 128-bit SM4 encryption, ECB mode.
  • 5: 128-bit AES encryption, GCM mode.
  • 6: 256-bit AES encryption, GCM mode.
  • 7: (Default) 128-bit AES encryption, GCM mode. This encryption mode requires setting a salt (EncryptionKdfSalt).
  • 8: 256-bit AES encryption, GCM mode. This encryption mode requires setting a salt (EncryptionKdfSalt).

EncryptionKey

Encryption key, string type, with no length limit. It is recommended to use a 32-byte key.

encryptionKdfSalt

Encryption salt, 32 bytes in length. It is recommended to generate the salt using OpenSSL on the server side.

ExternalVideoFrame

YUV format video data.

type ExternalVideoFrame struct {
    Type           VideoBufferType
    Format         VideoPixelFormat
    Buffer         []byte
    Stride         int
    Height         int
    CropLeft       int
    CropTop        int
    CropRight      int
    CropBottom     int
    Rotation       VideoOrientation
    Timestamp      int64
    EGLContext     unsafe.Pointer
    EGLType        int
    TextureID      int
    Matrix         [16]float32
    MetadataBuffer []byte
    AlphaBuffer    []byte
    FillAlphaBuffer bool
    AlphaMode      int
    ColorSpace     ColorSpaceType;
}

Type

Type of video data. See VideoBufferType.

Format

Pixel format. See VideoPixelFormat.

Buffer

Video buffer.

Stride

Stride of the incoming video frame, in pixels, not bytes. For Texture, this value indicates the width of the Texture.

Height

Height of the incoming video frame.

CropLeft

Field related to raw data. Specifies the number of pixels to crop from the left. Default is 0. This parameter is only applicable to raw video data.

CropTop

Field related to raw data. Specifies the number of pixels to crop from the top. Default is 0. This parameter is only applicable to raw video data.

CropRight

Field related to raw data. Specifies the number of pixels to crop from the right. Default is 0. This parameter is only applicable to raw video data.

CropBottom

Field related to raw data. Specifies the number of pixels to crop from the bottom. Default is 0. This parameter is only applicable to raw video data.

Rotation

Field related to raw data. Specifies whether to rotate the incoming video clockwise. Default is 0. See VideoOrientation.

Timestamp

Timestamp of the incoming video frame in milliseconds. Incorrect timestamps can cause frame drops or audio-video desynchronization.

EGLContext

This parameter is only applicable to video data in Texture format. - When using the Khronos-defined OpenGL interface (javax.microedition.khronos.egl.), set the eglContext to this field. - When using the Android-defined OpenGL interface (android.opengl.), set the eglContext to this field.

EGLType

This parameter is only applicable to video data in Texture format. Specifies the EGL context type.

TextureID

This parameter is only applicable to video data in Texture format. Specifies the Texture ID of the video frame.

Matrix

This parameter is only applicable to video data in Texture format. It is an input 4x4 transformation matrix, typically an identity matrix.

MetadataBuffer

The metadata buffer of the video frame. The default value is nil.

AlphaBuffer

Alpha channel data output by the portrait segmentation algorithm. This data matches the size of the video frame, with each pixel value ranging from [0,255], where 0 represents the background and 255 represents the foreground (portrait). By setting this parameter, you can render the video background with various effects, such as transparency, solid color, image, or video.

FillAlphaBuffer

[For BGRA or RGBA only] Whether to extract alphaBuffer from BGRA or RGBA data.

  • true: Yes. Set it to true if you do not explicitly specify the alphaBuffer.
  • false: (Default) No.

AlphaMode

The relative position between alphaBuffer and the frame.

  • 0: (Default) Normal frame.
  • 1: alphaBuffer is above the frame.
  • 2: alphaBuffer is below the frame.
  • 3: alphaBuffer is on the left of the frame.
  • 4: alphaBuffer is on the right of the frame.

ColorSpace

The color space of the video frame. See ColorSpaceType.

RtcConnectionConfig

RTC connection configuration.

type RtcConnectionConfig struct {
    AutoSubscribeAudio bool
    AutoSubscribeVideo bool
    EnableAudioRecordingOrPlayout bool
    MaxSendBitrate int
    MinPort int
    MaxPort int
    ClientRole     ClientRole
    ChannelProfile ChannelProfile
    AudioRecvMediaPacket bool
    VideoRecvMediaPacket bool
}
ParameterDescription
AutoSubscribeAudioWhether to automatically subscribe to all audio tracks. - 0: Do not automatically subscribe to all audio tracks. - 1: (Default) Automatically subscribe to all audio tracks.
AutoSubscribeVideoWhether to automatically subscribe to all video tracks. - 0: Do not automatically subscribe to all video tracks. - 1: (Default) Automatically subscribe to all video tracks.
EnableAudioRecordingOrPlayoutWhether to enable audio recording or playback. - false: Disable audio recording or playback. - true: Enable audio recording or playback.
MaxSendBitrateMaximum send bitrate.
MinPortMinimum port.
MaxPortMaximum port.
ClientRoleUser role. See ClientRole.
ChannelProfileChannel profile. See ChannelProfile.
AudioRecvMediaPacketWhether to receive audio media packets. - false: Do not receive. - true: Receive.
VideoRecvMediaPacketWhether to receive video media packets. - false: Do not receive. - true: Receive.

RtcConnectionInfo

RTC connection information.

type RtcConnectionInfo struct {
    ConnectionId uint
    ChannelId string
    State int
    LocalUserId string
    InternalUid uint
}
ParameterDescription
ConnectionIdID of the RTC connection.
ChannelIdRTC channel ID. If you have not called the connect method, this parameter returns nil.
StateConnection state: - 1: Network connection disconnected. - 2: Establishing network connection. - 3: Network connected. - 4: Re-establishing network connection. - 5: Network connection failed.
LocalUserIdLocal user ID.
InternalUidFor internal use only.

VideoEncodedImageSenderOptions

Configuration for the local video track object containing the video source that sends encoded video data.

type VideoEncodedImageSenderOptions struct {
    CcMode         VideoSendCcState
    CodecType      VideoCodecType
    TargetBitrate  int
}
ParameterDescription
CcModeCongestion control mode. See VideoSendCcState.
CodecTypeVideo codec type. See VideoCodecType.
TargetBitrateTarget encoding bitrate (Kbps) for the current encoder, which is an estimated value by the SDK based on the current network conditions.

VideoEncoderConfiguration

The video encoding properties.

type VideoEncoderConfiguration struct {
    CodecType          VideoCodecType
    Width              int
    Height             int
    Framerate          int
    Bitrate            int
    MinBitrate         int
    OrientationMode    OrientationMode
    DegradePreference  DegradationPreference
    MirrorMode         VideoMirrorModeType
    EncodeAlpha        bool
}
ParameterDescription
CodecTypeVideo codec type. See VideoCodecType.
WidthWidth of the video encoding (px).
HeightHeight of the video encoding (px).
FramerateFrame rate of the video encoding (fps), default is 15.
BitrateVideo encoding bitrate in Kbps.
MinBitrateMinimum encoding bitrate in Kbps. The SDK automatically adjusts the video encoding bitrate based on network conditions. Setting this parameter higher than the default value can force the video encoder to output higher quality images, but may cause packet loss and affect video playback smoothness under poor network conditions, resulting in stuttering. Therefore, unless there is a special requirement for image quality, it is recommended not to modify this parameter. Note: This parameter is only applicable in live broadcast scenarios.
OrientationModeVideo encoding orientation mode: - 0 (OrientationModeAdaptive): (Default) The output video follows the orientation of the captured video. The receiver rotates the video based on the rotation information it receives. - 1 (OrientationModeFixedLandscape): The SDK always outputs landscape video. If the captured video is in portrait mode, the video encoder crops it. - 2 (OrientationModeFixedPortrait): The SDK always outputs portrait video. If the captured video is in landscape mode, the video encoder crops it.
DegradePreferenceVideo encoding degrade preference when bandwidth is limited: - 0 (DegradeMaintainQuality): (Default) When bandwidth is limited, prioritize reducing video frame rate while maintaining video quality. This degrade preference is suitable for use-cases where image quality is prioritized. - 1 (DegradeMaintainFramerate): When bandwidth is limited, prioritize reducing video quality while maintaining video frame rate. This degrade preference is suitable for use-cases where smoothness is prioritized and quality reduction is acceptable. - 2 (DegradeMaintainBalanced): When bandwidth is limited, reduce both video frame rate and video quality. The reduction in 2 is less than in 0 and 1, suitable for use-cases with limited smoothness and quality. - 3 (DegradeMaintainResolution): When bandwidth is limited, reduce the video frame rate to maintain resolution. - 100 (DegradeDisabled): Disable video quality control adjustment.
MirrorModeWhether to enable mirror mode when encoding video. - 0 (VideoMirrorModeAuto): (Default) The SDK determines the mirror mode. - 1 (VideoMirrorModeEnabled): Enable mirror mode. The SDK mirrors the video frame before encoding. - 2 (VideoMirrorModeDisabled): Disable mirror mode.
EncodeAlphaWhether to encode and send the alpha data to the remote user when the video frame contains alpha data. - true: Encode and send the alpha data. - false: (Default) Do not encode or send the alpha data.

VideoFrame

Properties of the video frame. The video data format is YUV420. The buffer is given as a pointer to a pointer, and this interface cannot modify the buffer's pointer, only the content of the buffer.

type VideoFrame struct {
    Type            VideoBufferType
    Width           int
    Height          int
    YStride         int
    UStride         int
    VStride         int
    YBuffer         []byte
    UBuffer         []byte
    VBuffer         []byte
    Rotation        VideoOrientation
    RenderTimeMs    int64
    AVSyncType      int
    MetadataBuffer  []byte
    SharedContext   unsafe.Pointer
    TextureID       int
    Matrix          [16]float32
    AlphaBuffer     []byte
    AlphaMode       int
}
ParameterDescription
TypeVideo data type. See VideoBufferType.
WidthWidth of the video frame (pixels).
HeightHeight of the video frame (pixels).
YStrideStride of the Y buffer in YUV data.
UStrideStride of the U buffer in YUV data.
VStrideStride of the V buffer in YUV data.
YBufferPointer to the pointer of the Y buffer in YUV data.
UBufferPointer to the pointer of the U buffer in YUV data.
VBufferPointer to the pointer of the V buffer in YUV data.
RotationClockwise rotation angle of the frame before rendering the video. See VideoOrientation.
RenderTimeMsTimestamp of the external audio frame. This parameter is required. You can use this timestamp to restore the order of audio frames; in use-cases with video (including those using external video sources), this parameter helps achieve audio-video synchronization.
AVSyncTypeReserved parameter.
MetadataBufferThe metadata buffer of the video frame.
SharedContextThe EGL context. Only applicable to Texture format video data.
TextureIDThe Texture ID of the video frame. Only applicable to Texture format video data.
MatrixThe input 4x4 transformation matrix. Only applicable to Texture format video data.
AlphaBufferThe alpha channel data of the video frame. The data matches the size of the video frame.
AlphaModeThe relative position between AlphaBuffer and the frame. - 0: (Default) Normal frame. - 1: AlphaBuffer is above the frame. - 2: AlphaBuffer is below the frame. - 3: AlphaBuffer is on the left of the frame. - 4: AlphaBuffer is on the right of the frame.

VideoSubscriptionOptions

The video subscription options.

type VideoSubscriptionOptions struct {
    StreamType        VideoStreamType
    EncodedFrameOnly  bool
}
ParameterDescription
StreamTypeType of video to subscribe to. See VideoStreamType.
EncodedFrameOnlyWhether to subscribe only to encoded video data: - true: Subscribe only to encoded video data. - false: (Default) Subscribe only to decoded video data.

Enums

AreaCode

Server access regions. This function is an advanced setting suitable for use-cases with access security restrictions. The area code supports bitwise operations. After specifying the access region, the SDK will connect to the Agora servers within the specified region.

ParameterDescription
AreaCodeCN0x00000001: Mainland China.
AreaCodeNA0x00000002: North America.
AreaCodeEU0x00000004: Europe.
AreaCodeAS0x00000008: Asia, excluding Mainland China.
AreaCodeJP0x00000010: Japan.
AreaCodeIN0x00000020: India.
AreaCodeGlob0xFFFFFFFF: (Default) Global.

AudioCodecType

Audio codec types.

ParameterDescription
AudioCodecOpus1: OPUS
AudioCodecPcma3: PCMA
AudioCodecPcmu4: PCMU
AudioCodecG7225: G722
AudioCodecAacLc8: AAC LC
AudioCodecHeAac9: HE AAC
AudioCodecHeAac211: HEAAC2

AudioFrameType

Audio frame types.

ParameterDescription
AudioFrameTypePCM160: 16-bit PCM.

AudioScenario

Audio encoding properties.

ParameterDescription
AudioScenarioDefault0: (Default) Automatic scenario, automatically matches the appropriate sound quality based on user role and audio routing.
AudioScenarioGameStreaming3: High-quality audio scenario, suitable for music-centric situations.
AudioScenarioChatRoom5: Chat room scenario, suitable for situations where users frequently join and leave the microphone. In this scenario, audience members will receive a pop-up prompt to request microphone permissions.
AudioScenarioChorus7: Chorus scenario, suitable for real-time chorus with extremely low latency in good network conditions.
AudioScenarioMeeting8: Meeting scenario, suitable for multi-person meetings primarily focused on voice.

ChannelProfile

Channel use-case.

ParameterDescription
ChannelProfileCommunication0: (Default) Communication use-case. Recommended for channels with only two users.
ChannelProfileLiveBroadcasting1: Live broadcasting use-case. This use-case includes two user roles: host and audience. Hosts can publish and receive audio and video streams, while the audience can only receive streams. Suitable for voice chat rooms, video live streaming, interactive large classes, and similar applications.

ClientRole

User roles.

ParameterDescription
ClientRoleBroadcaster1: Broadcaster. The broadcaster can send and receive media streams simultaneously.
ClientRoleAudience2: Audience. The audience can only receive media streams.

UserMediaInfo

User media information.

ParameterDescription
UserMediaInfoMuteAudio0: The user has stopped publishing audio streams.
UserMediaInfoMuteVideo1: The user has stopped publishing video streams.
UserMediaInfoEnableVideo4: The user has enabled video functionality.

VideoBufferType

Video data types.

ParameterDescription
VideoBufferRawData1: Raw data.
VideoBufferArray2: Array data.
VideoBufferTexture3: Texture.

VideoCodecType

Video codec types.

ParameterDescription
VideoCodecTypeNone0: None
VideoCodecTypeVp81: VP8
VideoCodecTypeH2642: H.264
VideoCodecTypeH2653: H.265
VideoCodecTypeGeneric6: Generic
VideoCodecTypeGenericH2647: Generic H264
VideoCodecTypeAv112: AV1
VideoCodecTypeVp913: VP9
VideoCodecTypeGenericJpeg20: JPEG

VideoFrameType

Encoded video frame types.

ParameterDescription
VideoFrameTypeBlankFrame0: Blank frame.
VideoFrameTypeKeyFrame3: Key frame. For H.264 encoding, the SDK classifies I-frames with SPS and PPS information as key frames.
VideoFrameTypeDeltaFrame4: Delta frame. For H.264 encoding, the SDK classifies P-frames and I-frames without SPS and PPS information as delta frames.
VideoFrameTypeBFrame5: B frame.
VideoFrameTypeDroppableFrame6: Droppable frame.
VideoFrameTypeUnknown-1: Unknown.

VideoOrientation

Fields related to raw data. Specifies whether to rotate the incoming video clockwise.

ParameterDescription
VideoOrientation00: (Default) Rotate 0 degrees clockwise.
VideoOrientation9090: Rotate 90 degrees clockwise.
VideoOrientation180180: Rotate 180 degrees clockwise.
VideoOrientation270270: Rotate 270 degrees clockwise.

VideoPixelFormat

Pixel formats.

ParameterDescription
VideoPixelDefault0: Raw video pixel format.
VideoPixelI4201: I420 format.
VideoPixelRGBA4: RGBA format.
VideoPixelI42216: I422 format.
VideoTextureID3D11Texture2D17: ID3D11TEXTURE2D format. Supported types include DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_B8G8R8A8_TYPELESS, and DXGI_FORMAT_NV12.

Caution

The SDK does not currently support the Alpha channel. The incoming Alpha value will be discarded.

VideoSendCcState

Congestion control modes.

ParameterDescription
VideoSendCcEnabled0: Enable congestion control.
VideoSendCcDisabled1: Disable congestion control.

VideoStreamType

Video stream types.

ParameterDescription
VideoStreamHigh0: (Default) High stream. Higher resolution and bitrate.
VideoStreamLow1: Low stream. Lower resolution and bitrate.