Channel Management and Data Transfer

int Create(int serverStoreID, const std::string& channelType, int iUdpHostPort, int iUdpServerConnectionPort, int iTcpPort);
Creates a channel and returns the channel ID. The channel type can be configured and may be set to force certain protocols or connectivity checks.
This function must be called before any network activity or connectivity checks can be made.

If positive values are specified for iUdpHostPort, iUdpServerConnectionPort and iTcpPort, AFE will try to bind to those ports. If the first two parameters are zero or negative, AFE will try to use any available port.

In IETF mode, If client application sets specific port value then make sure that next port value of iUdpServerConnectionPort is also available for AFE use. As per RFC, TURN client must use separate set of 5 tuple to gather IPv6 relay candidate. So AFE uses (iUdpServerConnectionPort + 1) port value to gather IPv6 relay candidates.

The parameter iTcpPort is for TCP candidate port. For RTP/RTCP channel, giving zero in this parameter will not gather TCP candidates. Specifying -1 will try to bind to any available ports.

For a fixed TCP port, a positive integer value (> 1023) can be provided to iTcpPort. In Microsoft® Lync™ mode, TCP candidates are multiplexed for RTP and RTCP components. So the same port can be used for both RTP and RTCP channels of a media stream. In IETF mode different ports must be used for both RTP and RTCP channels to gather TCP candidates. For channels with type AF_CHANNEL_DATA, no UDP candidates will be gathered and for channels with type AF_CHANNEL_UDP, no TCP candidates will be gathered. If the binding fails, the function will return a negative value.


The two UDP port parameters should not be specified the same positive value when operating in Microsoft® Lync™ mode (AF_MODE_MSOCS).
While AFE provides a way of specifying the exact ports to be used in a channel with parameters  iUdpHostPort, iUdpServerConnectionPort and iTcpPort, it is strongly recommended that the user does not specify fixed ports like this. Instead, the user may consider specifying a range of ports to be used by AFE with the SetPortRange function.


Parameters:

int serverStoreIDA unique server store id for individual server settings.
const std::string&channelType This string describes the type of the channel. Currently, the following channel types are available and defined in the header file supplied with the library:
AF_CHANNEL_TCP
AF_CHANNEL_UDP
AF_CHANNEL_RTP
AF_CHANNEL_RTCP
AF_CHANNEL_DATA
AF_CHANNEL_TLS
AF_CHANNEL_MTLS
AF_CHANNEL_LOOPBACK
AF_CHANNEL_EVENT
AF_CHANNEL_DNS
The channel types and their meaning are described in detail in 6.1. Channels.
int iUdpHostPortThe port to be used as host candidate in ICE checks.
int iUdpServerConnectionPortThe port to be used for connecting to the TURN server. This should be different from iUdpHostPort when operating in Microsoft® Lync™ mode (AF_MODE_MSOCS).
int iTcpPortThe port to be used for TCP connections. The same port will be used for host, relay connection, active and passive types.

Return value:

intThe function returns the channel ID of the created channel, or a negative value to indicate an error.


bool Connect(int iChannel, const std::string& sHost);
The function initializes the local channel endpoint and obtains its transport information. Then it connects the channel to an endpoint specified in the host description list sHost. This is a host description of the host to connect to.

By default, this function first tries to connect directly with the host. If no data is received within 5 seconds, it assumes that direct connection is not possible, and automatically retries through relay. This behavior can be modified with the help of channel option EAfOptionRelayFallbackTimeout (see 6.6. Channel Options).


DetectConnectivity should be complete before calling Connect (please see  WaitForDetectConnectivity (see 6.6. Channel Options)).

Parameters:

int iChannelThe ID of the channel (created by Create) to connect.
const std::string& sHostThe description of the host to connect to. This is a string with the format as described in detail in 6.3. Host Types.

Return value:

bool The function returns whether it succeeded (true) or failed (false). If false, call GetLastError for the error code.


bool StartListening(int serverStoreID, int port);
Starts listening for incoming connections on the specified port. AFE will create MTLS channel for each accepted connection.
Client must call SetCertificate API before calling this.

Parameters:

int serverStoreIDThe ID of the server store. All MTLS channels created for accepted connections will belong to this server store.
int portPort number where to listen for incoming connection.


Related EventsDescription
EAfEventNewConnectionAcceptedFired when a new connection is accepted on any listened port. "uChannel" of AfEvent structure will provide the MTLS channel number of the channel created implicitly by AFE for the newly accepted connection. Client should use this channel number as a reference to set channel options and for data transfer on this connection. Also "data" of AfEvent will provide the listened port number for which this connection is accepted. Please cast "data" to unsigned int pointer to retrieve the value.
EAfEventListenAbortedThis event is fired when the listening process is aborted by AFE for some specific port due to some underlying error (e.g continuous channel creation or bind failure). "data" of AfEvent will provide the port number for which listening process is aborted. Cast data as unsigned in pointer. Note that, for this event "uChannel" will be set to 0 (zero). To listen on this port user should call StartListening() again.


bool StopListening(int port);
Stops listening on the specified port for incoming connections


Parameters:

int portPort number to stop listening for incoming connections.


bool Close(int iChannel);
Closes a channel. All allocations made by this channel will be removed. Not recommended to invoke this API for a channel associated with a session.


Parameters:

int iChannel/td>The ID of the channel (created by Create) to close.


Return value:

bool/td>The function returns whether it succeeded (true) or failed (false).


int Send(int iChannel, const char pData[], int iLen, int iTimeoutMillisec);
Sends data on a channel. It is necessary to call Connect/CreateSession (depending on the destination, whether it is a server or a peer) before sending data. The function will return after the data is sent. If the whole amount of bytes (iLen) can not be sent, the function will return after iTimeoutMillisec milliseconds. The function will read at most iLen bytes from the buffer.

Please note that, when using channel type as AF_CHANNEL_DATA, it is recommended to use TCP segment size less than or equal to 64KB. It is also suggested to keep the data size less than 1500 bytes to get better performance.
However AFE supports large (more than 64KB) amount of data sending, but it can be reason for lots of TCP zero window errors as well as performance degrade.
Note: AFE does not fragment user data according to network MTU value. This should be maintained by client application.
Data should be sent by following some standards protocol instead of sending raw data through AFE. In this case, the raw packet could be recognized as a STUN packet from RFC-5245 and AFE could discard these packets. For ICE over TCP raw data should not be any problem.


Parameters:

int iChannelThe ID of the channel (created by Create) to be closed.
const char pData[]The source buffer that contains the data to be sent.
int iLenThe size in bytes of the data in the buffer.
int iTimeoutMillisecA timeout in milliseconds. Predefined values are AF_BLOCKING or AF_NON_BLOCKING.


Return value:

intThe function returns the number of bytes sent or -1 if an error occurred or the channel is already closed.s


int Recv(int iChannel, char pBuff[], int iLen, int iTimeoutMillisec);
Receives data from a channel. It is necessary to call Connect/CreateSession (depending on the destination, whether it is a server or a peer), before data can be received. The function will return if no data could be read after iTimeoutMillisec  milliseconds. The function will write at most iLen bytes to the buffer. It is the developer’s responsibility to allocate and free the buffer.

Parameters:

int iChannelThe ID of the channel (created by Create) to close.
char pBuff[]The buffer that will contain the data to be sent.
int iLenThe size in bytes of the data in the buffer.
int iTimeoutMillisecA timeout in milliseconds. If omitted, this parameter will be set to AF_TIMEOUT_INFINITE.

Return value:

intThe function returns the number of bytes written to the buffer or -1 if an error occurred or the channel is already closed.


int Select(int iNumChannels, int aChannels[], int aInputEvents[], int aOutputEvents[], int iTimeoutMillisec);
Waits until data on any of the channels given in input_events and output_events is available for sending or receiving. This function operates similar to the socket function select.

Parameters:

int iNumChannelsThe number of channels given in the parameters aChannels.
int aChannels[]The array of channel IDs to monitor for incoming or outgoing data.
int aInputEvents[]An array defining the input events of interest for each channel. Possible input events are AF_SELECT_READ, AF_SELECT_WRITE, AF_SELECT_NO_EVENT and AF_SELECT_ERROR.
int aOutputEvents[]An array defining the output events of interest for each channel. Possible output events are AF_SELECT_READ, AF_SELECT_WRITE, AF_SELECT_NO_EVENT and AF_SELECT_ERROR.
int iTimeoutMillisecA timeout in milliseconds. Predefined values are AF_BLOCKING or AF_NON_BLOCKING.

Return value:

intThe function returns the number of channels with an event signaled. It returns 0 on timeout and negative value on error.


While callback mechanism is used for data receive instead of select, user shall receive event on event channel indicating error for cases when AFE would signal AF_SELECT_ERROR through select API.


bool SetCallbackHandler(int iChannel, IAfCallbackHandler* pHandler);
This function allows specifying a callback function that handles received packets. The callback function will be called when data is received on the given channel.

Parameters:

int iChannelThe channel for which the callback is installed.
IAfCallbackHandler* pHandlerSpecifies the callback. IAfCallbackHandler is an abstract base class:
class IAfCallbackHandler
{
 public:
      virtual void _cdecl HandleCallback(
        int iChannel, char *pData, int iLen,
        const CAfStdString& sSrcAddress, int iSrcPort,
        const void *pContext) = 0;
};

An implementation of this base class and the function HandleCallback must be provided by the application developer. HandleCallback is called by AnyFirewall Engine and gets the actual channel number, a pointer to the data, the length of the data, the source address, the source port and the context pointer associated with the session.

Return value:

boolThe function returns true on success, false otherwise.


User should not do any time consuming processing inside the callback function and try to return as quickly possible. Otherwise it may degrade data transfer performance.
std::string GetLocalAddress(int iChannel);
Returns the host description of the local party when a channel is connected. This represents the local endpoint of the channel which has been finally selected, which can be on the host machine, on the firewall, or on the TURN server. This information is available after Connect was called (for channels not used in a session) or after ICE check completes (for channels used in a session).

Parameters:

int iChannelThe ID of the channel (created by Create).

Return value:

std::string The function returns the host description of the local channel in the form of "<host-type><IP address><port><transport>". The different parts of the host descriptions and their meanings are described in detail in 6.3. Host Types. This address will be used by the host, specified in Connect call, to send data to this channel.


std::string GetLocalAddressBase(int iChannel);
Returns a host description string with the actual host address and port being used by a channel. This address and port represents the actual address and port on the client machine. If the finally selected candidate is relay, this contains the address and port being used for the TURN server connection. This information is available after Connect was called (for channels not used in a session) or after ICE check completes (for channels used in a session).

Parameters:

int iChannelThe ID of the channel (created by Create).

Return value:

std::string The function returns the host description of the local endpoint in the form of "<host-type><IP address><port><transport>". The different parts of the host descriptions and their meanings are described in detail in Host Types.


bool IsClosed(int iChannel);
Returns whether a channel was closed or not. In contrast to ChannelExists, this function also checks whether the channel was closed by the remote end.

Parameters:

int iChannelThe ID of the channel to check.

Return value:

boolThe function returns whether the channel was closed (true) or not (false).


std::string GetRemoteAddress(int iChannel);
Returns the host description of the remote party. It returns the host which was specified in Connect() (if called). Once ICE check is completed, it returns the confirmed remote candidate.

Parameters:

int iChannelThe ID of the channel (created by Create).

Return value:

std::string The function returns the host description of the remote candidate in the form of "<host-type><IP address><port><transport>". The different parts of the host descriptions and their meanings are described in detail in 6.3. Host Types. This address will be used by the channel to send data to.


bool ChannelExists(int iChannel)
Returns whether a channel was created or not.

Parameters:

int iChannelThe ID of the channel to check.

Return value:

boolThe function returns whether the channel exists (true) or not (false).


EAfDetectedFirewallType GetFirewallType(const int serverStoreID)

Parameters:

int serverStoreIDA unique server store id for individual server settings.
Returns the detected firewall type.

The firewall type is in the form of enumeration as listed in the following table:

Firewall Type Description
EAfFirewallTypeUnknown Firewall type is not known yet
EAfFirewallTypeNone Firewall type is unknown
EAfFirewallTypeNAT Firewall type is NAT
EAfFirewallTypeTCPOnly Firewall blocks UDP traffic. However, it allows TCP connection.
EAfFirewallTypeProxy Firewall only allows traffic through proxy
EAfFirewallTypeBlocked Firewall blocks both UDP and TCP traffic


Return value:

EAfDetectedFirewallTypeThe type of the detected firewall.


bool SetChannelOption(int iChannel, EAfOptionName eOptionName, void *vpOptionValue)

Sets the channel option eOptionName, for the channel iChannel, to the value vpOptionValue. The possible options are discussed in 6.6. Channel Options.

If 0 is specified in place of iChannel, this option will be in effect for all channels that will be created in future. Otherwise, the option will be specific to that channel only.

Parameters:

int iChannelThe ID of the channel to check.

Return value:

boolThe function returns whether the channel exists (true) or not (false).


int CreateSession(int serverStoreID, const std::string& sMediaDescription, const void *pContext)
Creates a session with the channels specified in the string sMediaDescription. The media description is a list of strings having the format <Media type><Channel list>< Media label> and separated by ';'. Here, label is optional and only usable for video media. Currently AFE supports two types of media label as listed in the following table. Therefore, "AF_MEDIA_STREAM_AUDIO 1 2; AF_MEDIA_STREAM_VIDEO 3 4" will create a session with two streams. The audio stream with channel 1 and 2, and the video stream with channel 3 and 4. If we use label then media description will look like "AF_MEDIA_STREAM_AUDIO 1 2; AF_MEDIA_STREAM_VIDEO 3 4 AF_VIDEO_MEDIA_LABEL_MAIN". The function returns the ID representing the session.


Media TypeDescription
AF_MEDIA_STREAM_AUDIORepresents audio stream
AF_MEDIA_STREAM_VIDEORepresents video stream
AF_MEDIA_STREAM_DATARepresents data
AF_MEDIA_STREAM_APPLICATIONRepresents application data
AF_MEDIA_STREAM_APPLICATION_SHARINGRepresents application sharing media


Media LabelDescription
AF_VIDEO_MEDIA_LABEL_MAINRepresents main video stream
AF_VIDEO_MEDIA_LABEL_PANORAMICRepresents panoramic video stream


Parameters:

int serverStoreIDA unique server store id for individual server settings.
const std::string& sMediaDescriptionThe media specification in the format described above
const void *pContextThe context pointer associated to the session

Return value:

intAn unique session ID representing the session

The session ID can also be used as a channel ID where all the session level events, fired from the AFE, can be received. The following table summarizes the session level events:


Session Level Event TypeDescription
EAfEventOfferSDPAvailableFired when non-blocking call to MakeOffer() returns and offer SDP becomes available for AFE client to retrieve.
EAfEventAnswerSDPAvailableFired when non-blocking call to MakeAnswer() returns and Answer SDP becomes available for AFE client to retrieve.
EAfEventICECheckStartedFired when ICE check is started.
EAfEventICECheckCompletedFired when ICE check is completed.
EAfEventCallCompletionStatusAvailableFired when determination of call completion type for the whole session is complete and BW commit (Microsoft® Lync™ mode) is complete. IceCheckCompleted event is always followed by CallCompletionStatusAvailable.
EAfEventICENeedUpdatedOfferFired when the candidate pairs confirmed by ICE check is different from the candidate pairs that was used in the m/c line of the most recent offer/answer messages. reINVITE should be sent to the peer when this event is received.
EAfEventICECheckFailedIndicates the failure of ICE check.


A context pointer can be associated with a session, when creating the session. AFE will return this context pointer as a parameter of the callback function pertaining to the session.
bool ModifySession(int iSessionID, const std::string& sMediaDescription)
Modifies the session iSessionID with the new media specification described in sMediaDescription. This function can be used to add or remove audio/video streams to the current session. Please see Flow Diagram for an illustration of this. To remove a media from a session don't call Close(iChannel) for channels, provide new media description as sMediaDescription, AFE will close channels associated with that media implicitly.


Parameters:

int serverStoreIDA unique server store id for individual server settings.
const std::string& sMediaDescriptionThe media specification in the format described above

Return value:

boolTrue in case of success, and false in case of failure


bool CloseSession(int iSessionID)
Closes the session iSessionID. Closes all channels in that session along with all the resources that were allocated to that session.

Parameters:

int iSessionIDThe session ID

Return value:

boolTrue in case of success, and false in case of failure


const struct AfSessionInfo *MakeOffer(int iSessionID)
Initializes all the channels in the session iSessionID, gathers candidates for the channels, and returns the candidate list in the form of a SDP structure.
DetectConnectivity should be complete before calling MakeOffer (please see WaitForDetectConnectivity).


Parameters:

int iSessionIDThe session ID

Return value:

const struct AfSessionInfo*The offer SDP in a structured format


const struct AfSessionInfo *MakeAnswer(int iSessionID, const std::string& sOfferSDP, const std::string& sPeerID)
Initializes all the channels in the session iSessionID, gathers candidates for the channels, and returns the candidate list in the form of a SDP structure. Moreover, it parses the SDP received from its peer and starts ICE checking.
DetectConnectivity should be complete before calling MakeAnswer (please see WaitForDetectConnectivity).


Parameters:

int iSessionIDThe session ID
const std::string& sOfferSDPThe SDP received from it's peer
const std::string& sPeerID Unique string to identify it's remote peer

Return value:

const struct AfSessionInfo*The answer SDP in a structured format


bool SetSipIdentifier(const int sessionID, const std::string& callIdentifier, const std::string& dialogIdentifier)
Applicable only for MS-Lync mode and when CAC policy is enabled in callee end. Invoke this API before calling MakeAnswer() API. Length of Sip Call Identifier and Sip Dialog Identifier must not exceed 256 bytes.

Note: This API is only applicable for Microsoft Lync mode. For others mode the API will return false.

Parameters:

int sessionIDThe session ID
const std::string& callIdentifierSip Call Identifier value.
const std::string& dialogIdentifierSip Dialog Identifier value.

Return value:

boolReturns true if succeeded and false if fails.


bool SetLocationProfile(int sessionID, EAfLocation peerLocation, EAfLocation selfLocation, EAfFederation federationType)
Applicable only for MS-Lync mode and when CAC policy is enabled in callee end. Invoke this API before calling MakeAnswer() API. If not invoked then AFE will use default values like Intranet for self and peer location with no federation.

Note: This API is only applicable for Microsoft Lync mode. For others mode the API will return false.

Note: This API is only applicable for Microsoft Lync mode. For others mode the API will return false.

Parameters:

int sessionIDThe session ID
EAfLocation peerLocationThe Peer Location.
EAfLocation selfLocationThe Self Location.
EAfFederation federationTypeFederation Type.

Return value:

boolReturns true if succeeded and false if fails.


Local & Peer location values(enum EAfLocation):
    EAfLocationUnknown,
    EAfLocationInternet,
    EAfLocationIntranet
Federation type values(enum EAfFederation):
    EAfNoFederation,
    EAfEnterprizeFederation,
    EAfPublicCloudFederation


void MarkSuccessAnswerSent(int sessionId)
Start the ICE check timer by signaling the AFE. It's used only after calling MakeAnswer(). For example, if an application needs to wait for an arbitrary period of time to accept a call, then it must call this API after sending 200 Ok INVITE response, not after sending any provisional response like 183 session progress.

Parameter:

int iSessionIDSession ID for whom success answer sent event to be marked.


std::string GetSessionDescription(int iSessionID)
Returns the session description string of the given session.

Parameter:

int iSessionIDThe session ID of the session.

Return:

std::stringOn success, returns the session description string, otherwise it returns empty string.


int GetSessionProperty(int iSessionID, EAfSessionProperty eSessionProperty)
Returns the value for the given property for the given session.

Parameters:

int iSessionIDID of the session whose property to get.
EAfSessionProperty eSessionPropertyThe property whose value to get.

Return:

intReturns the property value as an integer.


const struct AfSessionInfo *GetSessionSDP(int iSessionID)
Returns the SDP structure of the session iSessionID. This function is mainly useful in the case of non-blocking calls of MakeOffer and MakeAnswer. This function should be called after the event  EAfEventOfferSDPAvailable  or  EAfEventAnswerSDPAvailable.


Parameters:

int iSessionIDThe session ID

Return value:

iconst struct AfSessionInfo*The SDP in a structured format


bool ProcessAnswer(int iSessionID, const std::string& sAnswerSDP, bool successAnswerReceived, const std::string& sPeerID)
Parses the SDP received from its peer and starts ICE checking.

Parameters:

int iSessionIDThe session ID
const std::string& sAnswerSDPThe SDP received from its peer
bool successAnswerReceivedSet as true if the answer SDP is retrieved from a 200 OK INVITE response. Set false for 1xx responses. For non-Microsoft® Lync™ mode this value should be always true.
const std::string sPeerIDA unique string to identify it's remote peer

Return value:

booltrue on success, and false on failure