4. Endpoint

The Endpoint class is a singleton class, and application MUST create one and at most one of this class instance before it can do anything else, and similarly, once this class is destroyed, application must NOT call any library API. This class is the core class of PJSUA2, and it provides the following functions:

  • Starting up and shutting down
  • Customization of configurations, such as core UA (User Agent) SIP configuration, media configuration, and logging configuration

This chapter will describe the functions above.

To use the Endpoint class, normally application does not need to subclass it unless:

  • application wants to implement/override Endpoints callback methods to get the events such as transport state change or NAT detection completion, or
  • application schedules a timer using Endpoint.utilTimerSchedule() API. In this case, application needs to implement the onTimer() callback to get the notification when the timer expires.

Instantiating the Endpoint

Before anything else, you must instantiate the Endpoint class:

Endpoint *ep = new Endpoint;

Once the endpoint is instantiated, you can retrieve the Endpoint instance using Endpoint.instance() static method.

Creating the Library

Create the library by calling its libCreate() method:

try {
} catch(Error& err) {
    cout << "Startup error: " << err.info() << endl;

The libCreate() method will raise exception if error occurs, so we need to trap the exception using try/catch clause as above.

Initializing the Library and Configuring the Settings

The EpConfig class provides endpoint configuration which allows the customization of the following settings:

  • UAConfig, to specify core SIP user agent settings.
  • MediaConfig, to specify various media global settings
  • LogConfig, to customize logging settings.

Note that some settings can be further specified on per account basis, in the AccountConfig.

To customize the settings, create instance of EpConfig class and specify them during the endpoint initialization (will be explained more later), for example:

EpConfig ep_cfg;
ep_cfg.logConfig.level = 5;
ep_cfg.uaConfig.maxCalls = 4;
ep_cfg.mediaConfig.sndClockRate = 16000;

Next, you can initialize the library by calling libInit():

try {
    EpConfig ep_cfg;
    // Specify customization of settings in ep_cfg
} catch(Error& err) {
    cout << "Initialization error: " << err.info() << endl;

The snippet above initializes the library with the default settings.

Creating One or More Transports

Application needs to create one or more transports before it can send or receive SIP messages:

try {
    TransportConfig tcfg;
    tcfg.port = 5060;
    TransportId tid = ep->transportCreate(PJSIP_TRANSPORT_UDP, tcfg);
} catch(Error& err) {
    cout << "Transport creation error: " << err.info() << endl;

The transportCreate() method returns the newly created Transport ID and it takes the transport type and TransportConfig object to customize the transport settings like bound address and listening port number. Without this, by default the transport will be bound to INADDR_ANY and any available port.

There is no real use of the Transport ID, except to create userless account (with Account.create(), as will be explained later), and perhaps to display the list of transports to user if the application wants it.

Starting the Library

Now we’re ready to start the library. We need to start the library to finalize the initialization phase, e.g. to complete the initial STUN address resolution, initialize/start the sound device, etc. To start the library, call libStart() method:

try {
} catch(Error& err) {
    cout << "Startup error: " << err.info() << endl;

Shutting Down the Library

Once the application exits, the library needs to be shutdown so that resources can be released back to the operating system. Although this can be done by deleting the Endpoint instance, which will internally call libDestroy(), it is better to call it manually because on Java or Python there are problems with garbage collection as explained earlier:

delete ep;

Class Reference

The Endpoint

class pj::Endpoint

Endpoint represents an instance of pjsua library.

There can only be one instance of pjsua library in an application, hence this class is a singleton.

Public Functions

Default constructor.

virtual ~Endpoint()

Virtual destructor.

Version libVersion() const

Get library version.

void libCreate()

Instantiate pjsua application.

Application must call this function before calling any other functions, to make sure that the underlying libraries are properly initialized. Once this function has returned success, application must call destroy() before quitting.

pjsua_state libGetState() const

Get library state.

library state.

void libInit(const EpConfig & prmEpConfig)

Initialize pjsua with the specified settings.

All the settings are optional, and the default values will be used when the config is not specified.

Note that create() MUST be called before calling this function.


void libStart()

Call this function after all initialization is done, so that the library can do additional checking set up.

Application may call this function any time after init().

void libRegisterThread(const string & name)

Register a thread that was created by external or native API to the library.

Note that each time this function is called, it will allocate some memory to store the thread description, which will only be freed when the library is destroyed.

  • name -

    The optional name to be assigned to the thread.

bool libIsThreadRegistered()

Check if this thread has been registered to the library.

Note that this function is only applicable for library main & worker threads and external/native threads registered using libRegisterThread().

void libStopWorkerThreads()

Stop all worker threads.

int libHandleEvents(unsigned msec_timeout)

Poll pjsua for events, and if necessary block the caller thread for the specified maximum interval (in miliseconds).

Application doesn’t normally need to call this function if it has configured worker thread (thread_cnt field) in pjsua_config structure, because polling then will be done by these worker threads instead.

If EpConfig::UaConfig::mainThreadOnly is enabled and this function is called from the main thread (by default the main thread is thread that calls libCreate()), this function will also scan and run any pending jobs in the list.

The number of events that have been handled during the poll. Negative value indicates error, and application can retrieve the error as (status = -return_value).
  • msec_timeout -

    Maximum time to wait, in miliseconds.

void libDestroy(unsigned prmFlags = 0)

Destroy pjsua.

Application is recommended to perform graceful shutdown before calling this function (such as unregister the account from the SIP server, terminate presense subscription, and hangup active calls), however, this function will do all of these if it finds there are active sessions that need to be terminated. This function will block for few seconds to wait for replies from remote.

Application.may safely call this function more than once if it doesn’t keep track of it’s state.

  • prmFlags -

    Combination of pjsua_destroy_flag enumeration.

string utilStrError(pj_status_t prmErr)

Retrieve the error string for the specified status code.

  • prmErr -

    The error code.

void utilLogWrite(int prmLevel, const string & prmSender, const string & prmMsg)

Write a log message.

  • prmLevel -

    Log verbosity level (1-5)

  • prmSender -

    The log sender.

  • prmMsg -

    The log message.

void utilLogWrite(LogEntry & e)

Write a log entry.

  • e -

    The log entry.

pj_status_t utilVerifySipUri(const string & prmUri)

This is a utility function to verify that valid SIP url is given.

If the URL is a valid SIP/SIPS scheme, PJ_SUCCESS will be returned.

PJ_SUCCESS on success, or the appropriate error code.
  • prmUri -

    The URL string.

pj_status_t utilVerifyUri(const string & prmUri)

This is a utility function to verify that valid URI is given.

Unlike utilVerifySipUri(), this function will return PJ_SUCCESS if tel: URI is given.

PJ_SUCCESS on success, or the appropriate error code.
  • prmUri -

    The URL string.

Token utilTimerSchedule(unsigned prmMsecDelay, Token prmUserData)

Schedule a timer with the specified interval and user data.

When the interval elapsed, onTimer() callback will be called. Note that the callback may be executed by different thread, depending on whether worker thread is enabled or not.

Token to identify the timer, which could be given to utilTimerCancel().
  • prmMsecDelay -

    The time interval in msec.

  • prmUserData -

    Arbitrary user data, to be given back to application in the callback.

void utilTimerCancel(Token prmToken)

Cancel previously scheduled timer with the specified timer token.


void utilAddPendingJob(PendingJob * job)

Utility to register a pending job to be executed by main thread.

If EpConfig::UaConfig::mainThreadOnly is false, the job will be executed immediately.

  • job -

    The job class.

IntVector utilSslGetAvailableCiphers()

Get cipher list supported by SSL/TLS backend.

void natDetectType(void)

This is a utility function to detect NAT type in front of this endpoint.

Once invoked successfully, this function will complete asynchronously and report the result in onNatDetectionComplete().

After NAT has been detected and the callback is called, application can get the detected NAT type by calling natGetType(). Application can also perform NAT detection by calling natDetectType() again at later time.

Note that STUN must be enabled to run this function successfully.

pj_stun_nat_type natGetType()

Get the NAT type as detected by natDetectType() function.

This function will only return useful NAT type after natDetectType() has completed successfully and onNatDetectionComplete() callback has been called.

Exception: if this function is called while detection is in progress, PJ_EPENDING exception will be raised.

void natCheckStunServers(const StringVector & prmServers, bool prmWait, Token prmUserData)

Auxiliary function to resolve and contact each of the STUN server entries (sequentially) to find which is usable.

The libInit() must have been called before calling this function.

  • prmServers -

    Array of STUN servers to try. The endpoint will try to resolve and contact each of the STUN server entry until it finds one that is usable. Each entry may be a domain name, host name, IP address, and it may contain an optional port number. For example:

    • “pjsip.org” (domain name)
    • “sip.pjsip.org” (host name)
    • “pjsip.org:33478” (domain name and a non- standard port number)
    • “” (IP address and port number)

  • prmWait -

    Specify if the function should block until it gets the result. In this case, the function will block while the resolution is being done, and the callback will be called before this function returns.

  • prmUserData -

    Arbitrary user data to be passed back to application in the callback.

void natCancelCheckStunServers(Token token, bool notify_cb = false)

Cancel pending STUN resolution which match the specified token.

Exception: PJ_ENOTFOUND if there is no matching one, or other error.

  • token -

    The token to match. This token was given to natCheckStunServers()

  • notify_cb -

    Boolean to control whether the callback should be called for cancelled resolutions. When the callback is called, the status in the result will be set as PJ_ECANCELLED.

TransportId transportCreate(pjsip_transport_type_e type, const TransportConfig & cfg)

Create and start a new SIP transport according to the specified settings.

The transport ID.
  • type -

    Transport type.

  • cfg -

    Transport configuration.

IntVector transportEnum()

Enumerate all transports currently created in the system.

This function will return all transport IDs, and application may then call transportGetInfo() function to retrieve detailed information about the transport.

Array of transport IDs.

TransportInfo transportGetInfo(TransportId id)

Get information about transport.

Transport info.
  • id -

    Transport ID.

void transportSetEnable(TransportId id, bool enabled)

Disable a transport or re-enable it.

By default transport is always enabled after it is created. Disabling a transport does not necessarily close the socket, it will only discard incoming messages and prevent the transport from being used to send outgoing messages.

  • id -

    Transport ID.

  • enabled -

    Enable or disable the transport.

void transportClose(TransportId id)

Close the transport.

The system will wait until all transactions are closed while preventing new users from using the transport, and will close the transport when its usage count reaches zero.

  • id -

    Transport ID.

void hangupAllCalls(void)

Terminate all calls.

This will initiate call hangup for all currently active calls.

void mediaAdd(AudioMedia & media)

Add media to the media list.

  • media -

    media to be added.

void mediaRemove(AudioMedia & media)

Remove media from the media list.

  • media -

    media to be removed.

bool mediaExists(const AudioMedia & media) const

Check if media has been added to the media list.

True if media has been added, false otherwise.
  • media -

    media to be check.

unsigned mediaMaxPorts() const

Get maximum number of media port.

Maximum number of media port in the conference bridge.

unsigned mediaActivePorts() const

Get current number of active media port in the bridge.

The number of active media port.

const AudioMediaVector & mediaEnumPorts() const

Enumerate all media port.

The list of media port.

AudDevManager & audDevManager()

Get the instance of Audio Device Manager.

The Audio Device Manager.

const CodecInfoVector & codecEnum()

Enum all supported codecs in the system.

Array of codec info.

void codecSetPriority(const string & codec_id, pj_uint8_t priority)

Change codec priority.

  • codec_id -

    Codec ID, which is a string that uniquely identify the codec (such as “speex/8000”).

  • priority -

    Codec priority, 0-255, where zero means to disable the codec.

CodecParam codecGetParam(const string & codec_id) const

Get codec parameters.

Codec parameters. If codec is not found, Error will be thrown.
  • codec_id -

    Codec ID.

void codecSetParam(const string & codec_id, const CodecParam param)

Set codec parameters.

  • codec_id -

    Codec ID.

  • param -

    Codec parameter to set. Set to NULL to reset codec parameter to library default settings.

virtual void onNatDetectionComplete(const OnNatDetectionCompleteParam & prm)

Callback when the Endpoint has finished performing NAT type detection that is initiated with natDetectType().

  • prm -

    Callback parameters containing the detection result.

virtual void onNatCheckStunServersComplete(const OnNatCheckStunServersCompleteParam & prm)

Callback when the Endpoint has finished performing STUN server checking that is initiated with natCheckStunServers().

  • prm -

    Callback parameters.

virtual void onTransportState(const OnTransportStateParam & prm)

This callback is called when transport state has changed.

  • prm -

    Callback parameters.

virtual void onTimer(const OnTimerParam & prm)

Callback when a timer has fired.

The timer was scheduled by utilTimerSchedule().

  • prm -

    Callback parameters.

virtual void onSelectAccount(OnSelectAccountParam & prm)

This callback can be used by application to override the account to be used to handle an incoming message.

Initially, the account to be used will be calculated automatically by the library. This initial account will be used if application does not implement this callback, or application sets an invalid account upon returning from this callback.

Note that currently the incoming messages requiring account assignment are INVITE, MESSAGE, SUBSCRIBE, and unsolicited NOTIFY. This callback may be called before the callback of the SIP event itself, i.e: incoming call, pager, subscription, or unsolicited-event.

  • prm -

    Callback parameters.

Public Static Functions
Endpoint & instance()

Retrieve the singleton instance of the endpoint.

Endpoint Configurations


struct pj::EpConfig

Endpoint configuration.


struct pj::MediaConfig

This structure describes media configuration, which will be specified when calling Lib::init().


struct pj::LogConfig

Logging configuration, which can be (optionally) specified when calling Lib::init().

class pj::LogWriter

Interface for writing log messages.

Applications can inherit this class and supply it in the LogConfig structure to implement custom log writing facility.

Public Functions
virtual ~LogWriter()


virtual void write(const LogEntry & entry) = 0

Write a log entry.

struct pj::LogEntry

Data containing log entry to be written by the LogWriter.

User Agent

struct pj::UaConfig

SIP User Agent related settings.

Callback Parameters

struct pj::OnNatDetectionCompleteParam

Argument to Endpoint::onNatDetectionComplete() callback.

struct pj::OnNatCheckStunServersCompleteParam

Argument to Endpoint::onNatCheckStunServersComplete() callback.

struct pj::OnTimerParam

Parameter of Endpoint::onTimer() callback.

struct pj::OnTransportStateParam

Parameter of Endpoint::onTransportState() callback.

struct pj::OnSelectAccountParam

Parameter of Endpoint::onSelectAccount() callback.


struct pj::PendingJob