7. Calls

Calls are represented by Call class.

Subclassing the Call Class

To use the Call class, normally application SHOULD create its own subclass, such as:

class MyCall : public Call
{
public:
    MyCall(Account &acc, int call_id = PJSUA_INVALID_ID)
    : Call(acc, call_id)
    { }

    ~MyCall()
    { }

    // Notification when call's state has changed.
    virtual void onCallState(OnCallStateParam &prm);

    // Notification when call's media state has changed.
    virtual void onCallMediaState(OnCallMediaStateParam &prm);
};

In its subclass, application can implement the call callbacks, which is basically used to process events related to the call, such as call state change or incoming call transfer request.

Making Outgoing Calls

Making outgoing call is simple, just invoke makeCall() method of the Call object. Assuming you have the Account object as acc variable and destination URI string in dest_uri, you can initiate outgoing call with the snippet below:

Call *call = new MyCall(*acc);
CallOpParam prm(true); // Use default call settings
try {
    call->makeCall(dest_uri, prm);
} catch(Error& err) {
    cout << err.info() << endl;
}

The snippet above creates a Call object and initiates outgoing call to dest_uri using the default call settings. Subsequent operations to the call can use the method in the call instance, and events to the call will be reported to the callback. More on the callback will be explained a bit later.

Receiving Incoming Calls

Incoming calls are reported as onIncomingCall() of the Account class. You must derive a class from the Account class to handle incoming calls.

Below is a sample code of the callback implementation:

void MyAccount::onIncomingCall(OnIncomingCallParam &iprm)
{
    Call *call = new MyCall(*this, iprm.callId);
    CallOpParam prm;
    prm.statusCode = PJSIP_SC_OK;
    call->answer(prm);
}

For incoming calls, the call instance is created in the callback function as shown above. Application should make sure to store the call instance during the lifetime of the call (that is until the call is disconnected).

Call Properties

All call properties such as state, media state, remote peer information, etc. are stored as CallInfo class, which can be retrieved from the call object with using getInfo() method of the Call.

Call Disconnection

Call disconnection event is a special event since once the callback that reports this event returns, the call is no longer valid and any operations invoked to the call object will raise error exception. Thus, it is recommended to delete the call object inside the callback.

The call disconnection is reported in onCallState() method of Call and it can be detected as follows:

void MyCall::onCallState(OnCallStateParam &prm)
{
    CallInfo ci = getInfo();
    if (ci.state == PJSIP_INV_STATE_DISCONNECTED) {
        /* Delete the call */
        delete this;
    }
}

Working with Call’s Audio Media

You can only operate with the call’s audio media (e.g. connecting the call to the sound device in the conference bridge) when the call’s audio media is ready (or active). The changes to the call’s media state is reported in onCallMediaState() callback, and if the calls audio media is ready (or active) the function Call.getMedia() will return a valid audio media.

Below is a sample code to connect the call to the sound device when the media is active:

void MyCall::onCallMediaState(OnCallMediaStateParam &prm)
{
    CallInfo ci = getInfo();
    // Iterate all the call medias
    for (unsigned i = 0; i < ci.media.size(); i++) {
        if (ci.media[i].type==PJMEDIA_TYPE_AUDIO && getMedia(i)) {
            AudioMedia *aud_med = (AudioMedia *)getMedia(i);

            // Connect the call audio media to sound device
            AudDevManager& mgr = Endpoint::instance().audDevManager();
            aud_med->startTransmit(mgr.getPlaybackDevMedia());
            mgr.getCaptureDevMedia().startTransmit(*aud_med);
        }
    }
}

When the audio media becomes inactive (for example when the call is put on hold), there is no need to stop the audio media’s transmission to/from the sound device since the call’s audio media will be removed automatically from the conference bridge when it’s no longer valid, and this will automatically remove all connections to/from the call.

Call Operations

You can invoke operations to the Call object, such as hanging up, putting the call on hold, sending re-INVITE, etc. Please see the reference documentation of Call for more info.

Instant Messaging(IM)

You can send IM within a call using Call.sendInstantMessage(). The transmission status of outgoing instant messages is reported in Call.onInstantMessageStatus() callback method.

In addition to sending instant messages, you can also send typing indication using Call.sendTypingIndication().

Incoming IM and typing indication received within a call will be reported in the callback functions Call.onInstantMessage() and Call.onTypingIndication().

Alternatively, you can send IM and typing indication outside a call by using Buddy.sendInstantMessage() and Buddy.sendTypingIndication(). For more information, please see Presence documentation.

Class Reference

Call

class pj::Call

Call.

Public Functions
Call(Account & acc, int call_id = PJSUA_INVALID_ID)

Constructor.

virtual ~Call()

Destructor.

CallInfo getInfo() const

Obtain detail information about this call.

Return
Call info.

bool isActive() const

Check if this call has active INVITE session and the INVITE session has not been disconnected.

Return
True if call is active.

int getId() const

Get PJSUA-LIB call ID or index associated with this call.

Return
Integer greater than or equal to zero.

bool hasMedia() const

Check if call has an active media session.

Return
True if yes.

Media * getMedia(unsigned med_idx) const

Get media for the specified media index.

Return
The media or NULL if invalid or inactive.
Parameters

pjsip_dialog_cap_status remoteHasCap(int htype, const string & hname, const string & token) const

Check if remote peer support the specified capability.

Return
PJSIP_DIALOG_CAP_SUPPORTED if the specified capability is explicitly supported, see pjsip_dialog_cap_status for more info.
Parameters
  • htype -

    The header type (pjsip_hdr_e) to be checked, which value may be:

    • PJSIP_H_ACCEPT
    • PJSIP_H_ALLOW
    • PJSIP_H_SUPPORTED

  • hname -

    If htype specifies PJSIP_H_OTHER, then the header name must be supplied in this argument. Otherwise the value must be set to empty string (“”).

  • token -

    The capability token to check. For example, if htype is PJSIP_H_ALLOW, then token specifies the method names; if htype is PJSIP_H_SUPPORTED, then token specifies the extension names such as “100rel”.

void setUserData(Token user_data)

Attach application specific data to the call.

Application can then inspect this data by calling getUserData().

Parameters
  • user_data -

    Arbitrary data to be attached to the call.

Token getUserData() const

Get user data attached to the call, which has been previously set with setUserData().

Return
The user data.

pj_stun_nat_type getRemNatType()

Get the NAT type of remote’s endpoint.

This is a proprietary feature of PJSUA-LIB which sends its NAT type in the SDP when natTypeInSdp is set in UaConfig.

This function can only be called after SDP has been received from remote, which means for incoming call, this function can be called as soon as call is received as long as incoming call contains SDP, and for outgoing call, this function can be called only after SDP is received (normally in 200/OK response to INVITE). As a general case, application should call this function after or in onCallMediaState() callback.

Return
The NAT type.
See
Endpoint::natGetType(), natTypeInSdp

void makeCall(const string & dst_uri, const CallOpParam & prm)

Make outgoing call to the specified URI.

Parameters
  • dst_uri -

    URI to be put in the To header (normally is the same as the target URI).

  • prm.opt -

    Optional call setting.

  • prm.txOption -

    Optional headers etc to be added to outgoing INVITE request.

void answer(const CallOpParam & prm)

Send response to incoming INVITE request with call setting param.

Depending on the status code specified as parameter, this function may send provisional response, establish the call, or terminate the call. Notes about call setting:

  • if call setting is changed in the subsequent call to this function, only the first call setting supplied will applied. So normally application will not supply call setting before getting confirmation from the user.
  • if no call setting is supplied when SDP has to be sent, i.e: answer with status code 183 or 2xx, the default call setting will be used, check CallSetting for its default values.

Parameters
  • prm.opt -

    Optional call setting.

  • prm.statusCode -

    Status code, (100-699).

  • prm.reason -

    Optional reason phrase. If empty, default text will be used.

  • prm.txOption -

    Optional list of headers etc to be added to outgoing response message. Note that this message data will be persistent in all next answers/responses for this INVITE request.

void hangup(const CallOpParam & prm)

Hangup call by using method that is appropriate according to the call state.

This function is different than answering the call with 3xx-6xx response (with answer()), in that this function will hangup the call regardless of the state and role of the call, while answer() only works with incoming calls on EARLY state.

Parameters
  • prm.statusCode -

    Optional status code to be sent when we’re rejecting incoming call. If the value is zero, “603/Decline” will be sent.

  • prm.reason -

    Optional reason phrase to be sent when we’re rejecting incoming call. If empty, default text will be used.

  • prm.txOption -

    Optional list of headers etc to be added to outgoing request/response message.

void setHold(const CallOpParam & prm)

Put the specified call on hold.

This will send re-INVITE with the appropriate SDP to inform remote that the call is being put on hold. The final status of the request itself will be reported on the onCallMediaState() callback, which inform the application that the media state of the call has changed.

Parameters
  • prm.options -

    Bitmask of pjsua_call_flag constants. Currently, only the flag PJSUA_CALL_UPDATE_CONTACT can be used.

  • prm.txOption -

    Optional message components to be sent with the request.

void reinvite(const CallOpParam & prm)

Send re-INVITE.

The final status of the request itself will be reported on the onCallMediaState() callback, which inform the application that the media state of the call has changed.

Parameters
  • prm.opt -

    Optional call setting, if empty, the current call setting will remain unchanged.

  • prm.opt.flag -

    Bitmask of pjsua_call_flag constants. Specifying PJSUA_CALL_UNHOLD here will release call hold.

  • prm.txOption -

    Optional message components to be sent with the request.

void update(const CallOpParam & prm)

Send UPDATE request.

Parameters
  • prm.opt -

    Optional call setting, if empty, the current call setting will remain unchanged.

  • prm.txOption -

    Optional message components to be sent with the request.

void xfer(const string & dest, const CallOpParam & prm)

Initiate call transfer to the specified address.

This function will send REFER request to instruct remote call party to initiate a new INVITE session to the specified destination/target.

If application is interested to monitor the successfulness and the progress of the transfer request, it can implement onCallTransferStatus() callback which will report the progress of the call transfer request.

Parameters
  • dest -

    URI of new target to be contacted. The URI may be in name address or addr-spec format.

  • prm.txOption -

    Optional message components to be sent with the request.

void xferReplaces(const Call & dest_call, const CallOpParam & prm)

Initiate attended call transfer.

This function will send REFER request to instruct remote call party to initiate new INVITE session to the URL of destCall. The party at dest_call then should “replace” the call with us with the new call from the REFER recipient.

Parameters
  • dest_call -

    The call to be replaced.

  • prm.options -

    Application may specify PJSUA_XFER_NO_REQUIRE_REPLACES to suppress the inclusion of “Require: replaces” in the outgoing INVITE request created by the REFER request.

  • prm.txOption -

    Optional message components to be sent with the request.

void processRedirect(pjsip_redirect_op cmd)

Accept or reject redirection response.

Application MUST call this function after it signaled PJSIP_REDIRECT_PENDING in the onCallRedirected() callback, to notify the call whether to accept or reject the redirection to the current target. Application can use the combination of PJSIP_REDIRECT_PENDING command in onCallRedirected() callback and this function to ask for user permission before redirecting the call.

Note that if the application chooses to reject or stop redirection (by using PJSIP_REDIRECT_REJECT or PJSIP_REDIRECT_STOP respectively), the call disconnection callback will be called before this function returns. And if the application rejects the target, the onCallRedirected() callback may also be called before this function returns if there is another target to try.

Parameters
  • cmd -

    Redirection operation to be applied to the current target. The semantic of this argument is similar to the description in the onCallRedirected() callback, except that the PJSIP_REDIRECT_PENDING is not accepted here.

void dialDtmf(const string & digits)

Send DTMF digits to remote using RFC 2833 payload formats.

Parameters
  • digits -

    DTMF string digits to be sent.

void sendInstantMessage(const SendInstantMessageParam & prm)

Send instant messaging inside INVITE session.

Parameters
  • prm.contentType -

    MIME type.

  • prm.content -

    The message content.

  • prm.txOption -

    Optional list of headers etc to be included in outgoing request. The body descriptor in the txOption is ignored.

  • prm.userData -

    Optional user data, which will be given back when the IM callback is called.

void sendTypingIndication(const SendTypingIndicationParam & prm)

Send IM typing indication inside INVITE session.

Parameters
  • prm.isTyping -

    True to indicate to remote that local person is currently typing an IM.

  • prm.txOption -

    Optional list of headers etc to be included in outgoing request.

void sendRequest(const CallSendRequestParam & prm)

Send arbitrary request with the call.

This is useful for example to send INFO request. Note that application should not use this function to send requests which would change the invite session’s state, such as re-INVITE, UPDATE, PRACK, and BYE.

Parameters
  • prm.method -

    SIP method of the request.

  • prm.txOption -

    Optional message body and/or list of headers to be included in outgoing request.

string dump(bool with_media, const string indent)

Dump call and media statistics to string.

Return
Call dump and media statistics string.
Parameters
  • with_media -

    True to include media information too.

  • indent -

    Spaces for left indentation.

int vidGetStreamIdx() const

Get the media stream index of the default video stream in the call.

Typically this will just retrieve the stream index of the first activated video stream in the call. If none is active, it will return the first inactive video stream.

Return
The media stream index or -1 if no video stream is present in the call.

bool vidStreamIsRunning(int med_idx, pjmedia_dir dir) const

Determine if video stream for the specified call is currently running (i.e.

has been created, started, and not being paused) for the specified direction.

Return
True if stream is currently running for the specified direction.
Parameters
  • med_idx -

    Media stream index, or -1 to specify default video media.

  • dir -

    The direction to be checked.

void vidSetStream(pjsua_call_vid_strm_op op, const CallVidSetStreamParam & param)

Add, remove, modify, and/or manipulate video media stream for the specified call.

This may trigger a re-INVITE or UPDATE to be sent for the call.

Parameters
  • op -

    The video stream operation to be performed, possible values are pjsua_call_vid_strm_op.

  • param -

    The parameters for the video stream operation (see CallVidSetStreamParam).

StreamInfo getStreamInfo(unsigned med_idx) const

Get media stream info for the specified media index.

Return
The stream info.
Parameters
  • med_idx -

    Media stream index.

StreamStat getStreamStat(unsigned med_idx) const

Get media stream statistic for the specified media index.

Return
The stream statistic.
Parameters
  • med_idx -

    Media stream index.

MediaTransportInfo getMedTransportInfo(unsigned med_idx) const

Get media transport info for the specified media index.

Return
The transport info.
Parameters
  • med_idx -

    Media stream index.

void processMediaUpdate(OnCallMediaStateParam & prm)

Internal function (callled by Endpoint( to process update to call medias when call media state changes.

void processStateChange(OnCallStateParam & prm)

Internal function (called by Endpoint) to process call state change.

virtual void onCallState(OnCallStateParam & prm)

Notify application when call state has changed.

Application may then query the call info to get the detail call states by calling getInfo() function.

Parameters
  • prm -

    Callback parameter.

virtual void onCallTsxState(OnCallTsxStateParam & prm)

This is a general notification callback which is called whenever a transaction within the call has changed state.

Application can implement this callback for example to monitor the state of outgoing requests, or to answer unhandled incoming requests (such as INFO) with a final response.

Parameters
  • prm -

    Callback parameter.

virtual void onCallMediaState(OnCallMediaStateParam & prm)

Notify application when media state in the call has changed.

Normal application would need to implement this callback, e.g. to connect the call’s media to sound device. When ICE is used, this callback will also be called to report ICE negotiation failure.

Parameters
  • prm -

    Callback parameter.

virtual void onCallSdpCreated(OnCallSdpCreatedParam & prm)

Notify application when a call has just created a local SDP (for initial or subsequent SDP offer/answer).

Application can implement this callback to modify the SDP, before it is being sent and/or negotiated with remote SDP, for example to apply per account/call basis codecs priority or to add custom/proprietary SDP attributes.

Parameters
  • prm -

    Callback parameter.

virtual void onStreamCreated(OnStreamCreatedParam & prm)

Notify application when media session is created and before it is registered to the conference bridge.

Application may return different media port if it has added media processing port to the stream. This media port then will be added to the conference bridge instead.

Parameters
  • prm -

    Callback parameter.

virtual void onStreamDestroyed(OnStreamDestroyedParam & prm)

Notify application when media session has been unregistered from the conference bridge and about to be destroyed.

Parameters
  • prm -

    Callback parameter.

virtual void onDtmfDigit(OnDtmfDigitParam & prm)

Notify application upon incoming DTMF digits.

Parameters
  • prm -

    Callback parameter.

virtual void onCallTransferRequest(OnCallTransferRequestParam & prm)

Notify application on call being transferred (i.e.

REFER is received). Application can decide to accept/reject transfer request by setting the code (default is 202). When this callback is not implemented, the default behavior is to accept the transfer.

Parameters
  • prm -

    Callback parameter.

virtual void onCallTransferStatus(OnCallTransferStatusParam & prm)

Notify application of the status of previously sent call transfer request.

Application can monitor the status of the call transfer request, for example to decide whether to terminate existing call.

Parameters
  • prm -

    Callback parameter.

virtual void onCallReplaceRequest(OnCallReplaceRequestParam & prm)

Notify application about incoming INVITE with Replaces header.

Application may reject the request by setting non-2xx code.

Parameters
  • prm -

    Callback parameter.

virtual void onCallReplaced(OnCallReplacedParam & prm)

Notify application that an existing call has been replaced with a new call.

This happens when PJSUA-API receives incoming INVITE request with Replaces header.

After this callback is called, normally PJSUA-API will disconnect this call and establish a new call newCallId.

Parameters
  • prm -

    Callback parameter.

virtual void onCallRxOffer(OnCallRxOfferParam & prm)

Notify application when call has received new offer from remote (i.e.

re-INVITE/UPDATE with SDP is received). Application can decide to accept/reject the offer by setting the code (default is 200). If the offer is accepted, application can update the call setting to be applied in the answer. When this callback is not implemented, the default behavior is to accept the offer using current call setting.

Parameters
  • prm -

    Callback parameter.

virtual void onInstantMessage(OnInstantMessageParam & prm)

Notify application on incoming MESSAGE request.

Parameters
  • prm -

    Callback parameter.

virtual void onInstantMessageStatus(OnInstantMessageStatusParam & prm)

Notify application about the delivery status of outgoing MESSAGE request.

Parameters
  • prm -

    Callback parameter.

virtual void onTypingIndication(OnTypingIndicationParam & prm)

Notify application about typing indication.

Parameters
  • prm -

    Callback parameter.

virtual pjsip_redirect_op onCallRedirected(OnCallRedirectedParam & prm)

This callback is called when the call is about to resend the INVITE request to the specified target, following the previously received redirection response.

Application may accept the redirection to the specified target, reject this target only and make the session continue to try the next target in the list if such target exists, stop the whole redirection process altogether and cause the session to be disconnected, or defer the decision to ask for user confirmation.

This callback is optional, the default behavior is to NOT follow the redirection response.

Return
Action to be performed for the target. Set this parameter to one of the value below:
  • PJSIP_REDIRECT_ACCEPT: immediately accept the redirection. When set, the call will immediately resend INVITE request to the target.
  • PJSIP_REDIRECT_ACCEPT_REPLACE: immediately accept the redirection and replace the To header with the current target. When set, the call will immediately resend INVITE request to the target.
  • PJSIP_REDIRECT_REJECT: immediately reject this target. The call will continue retrying with next target if present, or disconnect the call if there is no more target to try.
  • PJSIP_REDIRECT_STOP: stop the whole redirection process and immediately disconnect the call. The onCallState() callback will be called with PJSIP_INV_STATE_DISCONNECTED state immediately after this callback returns.
  • PJSIP_REDIRECT_PENDING: set to this value if no decision can be made immediately (for example to request confirmation from user). Application then MUST call processRedirect() to either accept or reject the redirection upon getting user decision.
Parameters
  • prm -

    Callback parameter.

virtual void onCallMediaTransportState(OnCallMediaTransportStateParam & prm)

This callback is called when media transport state is changed.

Parameters
  • prm -

    Callback parameter.

virtual void onCallMediaEvent(OnCallMediaEventParam & prm)

Notification about media events such as video notifications.

This callback will most likely be called from media threads, thus application must not perform heavy processing in this callback. Especially, application must not destroy the call or media in this callback. If application needs to perform more complex tasks to handle the event, it should post the task to another thread.

Parameters
  • prm -

    Callback parameter.

virtual void onCreateMediaTransport(OnCreateMediaTransportParam & prm)

This callback can be used by application to implement custom media transport adapter for the call, or to replace the media transport with something completely new altogether.

This callback is called when a new call is created. The library has created a media transport for the call, and it is provided as the mediaTp argument of this callback. The callback may change it with the instance of media transport to be used by the call.

Parameters
  • prm -

    Callback parameter.

Public Static Functions
Call * lookup(int call_id)

Get the Call class for the specified call Id.

Return
The Call instance or NULL if not found.
Parameters
  • call_id -

    The call ID to lookup

Settings

struct pj::CallSetting

Call settings.

Info and Statistics

struct pj::CallInfo

Call information.

Application can query the call information by calling Call::getInfo().

struct pj::CallMediaInfo

Call media information.

struct pj::StreamInfo

Media stream info.

struct pj::StreamStat

Media stream statistic.

struct pj::JbufState

This structure describes jitter buffer state.

struct pj::RtcpStat

Bidirectional RTP stream statistics.

struct pj::RtcpStreamStat

Unidirectional RTP stream statistics.

struct pj::MathStat

This structure describes statistics state.

struct pj::MediaTransportInfo

This structure describes media transport informations.

It corresponds to the pjmedia_transport_info structure.

Callback Parameters

struct pj::OnCallStateParam

This structure contains parameters for Call::onCallState() callback.

struct pj::OnCallTsxStateParam

This structure contains parameters for Call::onCallTsxState() callback.

struct pj::OnCallMediaStateParam

This structure contains parameters for Call::onCallMediaState() callback.

struct pj::OnCallSdpCreatedParam

This structure contains parameters for Call::onCallSdpCreated() callback.

struct pj::OnStreamCreatedParam

This structure contains parameters for Call::onStreamCreated() callback.

struct pj::OnStreamDestroyedParam

This structure contains parameters for Call::onStreamDestroyed() callback.

struct pj::OnDtmfDigitParam

This structure contains parameters for Call::onDtmfDigit() callback.

struct pj::OnCallTransferRequestParam

This structure contains parameters for Call::onCallTransferRequest() callback.

struct pj::OnCallTransferStatusParam

This structure contains parameters for Call::onCallTransferStatus() callback.

struct pj::OnCallReplaceRequestParam

This structure contains parameters for Call::onCallReplaceRequest() callback.

struct pj::OnCallReplacedParam

This structure contains parameters for Call::onCallReplaced() callback.

struct pj::OnCallRxOfferParam

This structure contains parameters for Call::onCallRxOffer() callback.

struct pj::OnCallRedirectedParam

This structure contains parameters for Call::onCallRedirected() callback.

struct pj::OnCallMediaEventParam

This structure contains parameters for Call::onCallMediaEvent() callback.

struct pj::OnCallMediaTransportStateParam

This structure contains parameters for Call::onCallMediaTransportState() callback.

struct pj::OnCreateMediaTransportParam

This structure contains parameters for Call::onCreateMediaTransport() callback.

struct pj::CallOpParam

This structure contains parameters for Call::answer(), Call::hangup(), Call::reinvite(), Call::update(), Call::xfer(), Call::xferReplaces(), Call::setHold().

struct pj::CallSendRequestParam

This structure contains parameters for Call::sendRequest()

struct pj::CallVidSetStreamParam

This structure contains parameters for Call::vidSetStream()

Other

struct pj::MediaEvent

This structure describes a media event.

It corresponds to the pjmedia_event structure.

struct pj::MediaFmtChangedEvent

This structure describes a media format changed event.

struct pj::SdpSession

This structure describes SDP session description.

It corresponds to the pjmedia_sdp_session structure.

struct pj::RtcpSdes

RTCP SDES structure.