Asterisk – installation and dial plans for WebRTC supported PJSIP clients

Asterisk is a framework or toolkit designed for VOIP systems . It can support Enterprise communication systems like PBXs, call distributors, VoIP gateways , conference bridges etc . It is open source and free to use . It is developed in C and runs in linux .

Technically , Asterisk has protocol support for many telephony technologies and protocols such as SIP , H323 . It can connect old PSTN or copper line and VOIP .

Asterisk is a framework for building multi-protocol, real-time communications applications and solutions. Asterisk is to realtime voice and video applications as what Apache is to web applications

– asterisk.org

Combine the SIP channel, the PSTN interface channel and some Dialplan script and you have a gateway.
Change the Dialplan to drop calls into a ConfBridge session and you have a conference server.
Alter it once more to route calls into voice mailboxes and you have a voicemail server.
Tie it all together and you have an amazingly powerful phone system.

– asterisk.org

A repo containing Asterisk configuration and common applications can be found at https://github.com/altanai/asteriskexamples

Asterisk as a Central signalling SIP application Server in VoIP Platform

Due to the wide array of call flow processing and media, channel, bridge management module support of asterisk, it is ideal to sit at the core of a VoIP of Communication platform solution. A WebRTC capable CPaaS overall architecture with inbound and outbound Kamailio proxy and central asterisk signaller and integration to telecom service providers over SIP trunks can be described as below

Quick Installation of Asterisk

goto /usr/src and download the preferred the version of asterisk code from
http://downloads.asterisk.org/pub/telephony/asterisk/

I am using the latest release candidate at the time writing this article asterisk-16.2.0-rc1-patch.tar.gz

Some external Dependencies apt-get install subversion

Then install the source dependencies

 sudo su
contrib/scripts/get_mp3_source.sh

This will install mp3 related programs such as


A addons/mp3
A addons/mp3/decode_ntom.c
A addons/mp3/interface.c
A addons/mp3/MPGLIB_README
A addons/mp3/common.c
A addons/mp3/huffman.h
A addons/mp3/tabinit.c
A addons/mp3/Makefile
A addons/mp3/README
A addons/mp3/decode_i386.c
A addons/mp3/dct64_i386.c
A addons/mp3/MPGLIB_TODO
A addons/mp3/mpg123.h
A addons/mp3/layer3.c
A addons/mp3/mpglib.h
Exported revision 202.

Actual dependencies will be installed via install_prereq script

contrib/scripts/install_prereq install

Output snippet

Run configure which will create scripts for next processes

 ./configure

Build third party scripts

make -j2

After build , to run the installation

make install

Asterisk PBX setup

make basic-pbx

The output should be

Installing basic-pbx config files…
Installing file configs/basic-pbx/README
Installing file configs/basic-pbx/asterisk.conf
Installing file configs/basic-pbx/cdr.conf
Installing file configs/basic-pbx/cdr_custom.conf
Installing file configs/basic-pbx/confbridge.conf
Installing file configs/basic-pbx/extensions.conf
Installing file configs/basic-pbx/indications.conf
Installing file configs/basic-pbx/logger.conf
Installing file configs/basic-pbx/modules.conf
Installing file configs/basic-pbx/musiconhold.conf
Installing file configs/basic-pbx/pjsip.conf
Installing file configs/basic-pbx/voicemail.conf
Updating asterisk.conf

Also run make config to make pbx configs

make config 

start asterisk

systemctl start asterisk

connect to asterisk tool for cli

asterisk -vvvr
Asterisk 16.2.0-rc1, Copyright (C) 1999 - 2018, Digium, Inc. and others. Created by Mark Spencer markster@digium.com
Asterisk comes with ABSOLUTELY NO WARRANTY; type 'core show warranty' for details.
This is free software, with components licensed under the GNU General Public License version 2 and other licenses; you are welcome to redistribute it under certain conditions. Type 'core show license' for details.

Connected to Asterisk 16.2.0-rc1 currently running on ip-172-31-45-26 (pid = 13388)
ip-172-31-45-26*CLI> 

Register sip phones with asterisk PBX and make / receive calls

To make calls among users, we need to configure channel driver with sip support . Using the sip protcol the phones within the enterprise will be able to send call signals out to one another. Open pjsip.conf

Take any endpoint from template , such as

;================================
;Laverne Roberts
;Software Engineer
[1113 (endpoint-internal-d70)
auth = 1113
aors = 1113
callerid = Laverne Roberts <1113>
[1113 (auth-userpass)
password = xxxxxxxx
username = xxxxxxxx
[1113 (aor-single-reg)
mailboxes = 1113@example

and set the values in sip softphone like zoiper , register with provided creds

registering sip phone zoiper with newly created asterisk PBX

If the registration creds used are not matching with the ones defines in pjsip.conf then REGISTER request failed message is displayed

Request 'REGISTER' from '' failed for 'x.x.x.x:18475' (callid: hp8iN6oWLRdER4zvEBdiUg..) - No matching endpoint found

On correct creds used the server prints traces such as

-- Added contact 'sip:1113@x.x.x.x:44312;transport=UDP;rinstance=b8aceff08623b51e' to AOR '1113' with expiration of 60 seconds
== Endpoint 1113 is now Reachable
-- Removed contact 'sip:1113@x.x.x.x:44312;transport=UDP;rinstance=b8aceff08623b51e' from AOR '1113' due to request
== Contact 1113/sip:1113@x.x.x.x:44312;transport=UDP;rinstance=b8aceff08623b51e has been deleted
== Endpoint 1113 is now Unreachable
-- Added contact 'sip:1113@x.x.x.x:18475;transport=UDP;rinstance=5af431512ae0af3a' to AOR '1113' with expiration of 60 seconds
== Endpoint 1113 is now Reachable

Alternatively one can also create new sip endpoints

Dialplan Applications

Playback Hello World

[internal_users]
exten => 6000,1,Answer()
exten => 6000,2,Verbose("---------------- Tring Tring -------")
exten => 6000,3,Wait(1)
exten => 6000,n,Playback(silence/1&hello-world)
exten => 6000,n,Hangup()

NoOP and printing channel variables

exten=>6124,1,Verbose(2,The channel name is ${CHANNEL})
same => n,Verbose(2,The unique id is ${UNIQUEID})
same => n,Verbose(2,The caller id is ${CALLERID(all)})
same => n,Verbose(2,The datetime is ${DATETIME})
same => n,Verbose(2,The timestamp is ${TIMESTAMP})
same => n,Verbose(2,The context is ${CONTEXT})
same => n,Verbose(2,The SYSTEMNAME is ${SYSTEMNAME})
same => n,Verbose(2,The PRIORITY is ${PRIORITY})
same => n,Verbose(2,The CHANNEL is ${CHANNEL})

settings varaibles and Say

exten=>6009,1,Verbose("------------ Set variable -------")
same => n,Set(COUNT=3)
same => n,SayNumber(${COUNT})
same => n,Set(${COUNT}=10)
same => n,SayNumber(${COUNT}) 

Simple Voicemail ( also need configuration on voicemail.conf)

exten => 1235,1,VoiceMail(1235,u)               

PBX and applications

PBX cores settings 
Version:                     16.2.0-rc1
   Build Options:               BUILD_NATIVE, OPTIONAL_API
   Maximum calls:               Not set
   Maximum open file handles:   1024
   Root console verbosity:      5
   Current console verbosity:   5
   Debug level:                 0
   Maximum load average:        0.000000
   Minimum free memory:         0 MB
   Startup time:                10:27:35
   Last reload time:            10:27:35
   System:                      Linux/4.15.0-1021-aws built by root on x86_64 2019-02-11 11:48:29 UTC
   System name:                 
   Entity ID:                   0e:28:c0:44:39:5e
   PBX UUID:                    a2df96bb-6d1a-4f64-a953-cf02030e9851
   Default language:            en
   Language prefix:             Enabled
   User name and group:         /
   Executable includes:         Disabled
   Transcode via SLIN:          Enabled
   Transmit silence during rec: Disabled
   Generic PLC:                 Disabled
   Generic PLC on equal codecs: Disabled
   Min DTMF duration::          80
   Cache media frames:          Enabled
   RTP use dynamic payloads:    1
   RTP dynamic payload types:   35-63,96-127

Subsystems
   Manager (AMI):               Disabled
   Web Manager (AMI/HTTP):      Disabled
   Call data records:           Enabled
   Realtime Architecture (ARA): Disabled

 Directories
   Configuration file:          /etc/asterisk/asterisk.conf
   Configuration directory:     /etc/asterisk
   Module directory:            /usr/lib/asterisk/modules
   Spool directory:             /var/spool/asterisk
   Log directory:               /var/log/asterisk
   Run/Sockets directory:       /var/run/asterisk
   PID file:                    /var/run/asterisk/asterisk.pid
   VarLib directory:            /var/lib/asterisk
   Data directory:              /var/lib/asterisk
   ASTDB:                       /var/lib/asterisk/astdb
   IAX2 Keys directory:         /var/lib/asterisk/keys
   AGI Scripts directory:       /var/lib/asterisk/agi-bin

Asterisk Applications

Some of the application are listed below . Note that this is not an extensive list as more application are added and old ones are removed every minor release .

AddQueueMember: Dynamically adds queue members.
AlarmReceiver: Provide support for receiving alarm reports from a burglar or fire alarm panel.
AMD: Attempt to detect answering machines.
Answer: Answer a channel if ringing.
AttendedTransfer: Attended transfer to the extension provided and TRANSFER_CONTEXT
BackGround: Play an audio file while waiting for digits of an extension to go to.
BackgroundDetect: Background a file with talk detect.
BlindTransfer: Blind transfer channel(s) to the extension and context provided
Bridge: Bridge two channels.
BridgeAdd: Join a bridge that contains the specified channel.
BridgeWait: Put a call into the holding bridge.
Busy: Indicate the Busy condition.
ChanSpy: Listen to a channel, and optionally whisper into it.
ConfBridge: Conference bridge application.
Dial: Attempt to connect to another device or endpoint and bridge the call.
Dictate: Virtual Dictation Machine.
Echo: Echo media, DTMF back to the calling party
ExtenSpy: Listen to a channel, and optionally whisper into it.
ExternalIVR: Interfaces with an external IVR application.
FollowMe: Find-Me/Follow-Me application.
ForkCDR: Forks the current Call Data Record for this channel.
Hangup: Hang up the calling channel.
Log: Send arbitrary text to a selected log level.
MailboxExists: Check to see if Voicemail mailbox exists.
Milliwatt: Generate a Constant 1004Hz tone at 0dbm (mu-law).
MixMonitor: Record a call and mix the audio during the recording. Use of StopMixMonitor is required to guarantee the audio file is available for processing during dialplan execution.
Monitor: Monitor a channel.
Morsecode: Plays morse code.
MusicOnHold: Play Music On Hold indefinitely.
NoCDR: Tell Asterisk to not maintain a CDR for this channel.
NoOp: Do Nothing (No Operation).
Originate: Originate a call.
Park: Park yourself.
PauseMonitor: Pause monitoring of a channel.
PauseQueueMember: Pauses a queue member.
Pickup: Directed extension call pickup.
Playback: Play a file.
PlayTones: Play a tone list.
PrivacyManager: Require phone number to be entered, if no CallerID sent
Proceeding: Indicate proceeding.
Progress: Indicate progress.
Queue: Queue a call for a call queue.
Read: Read a variable.
SendImage: Sends an image file.
SendText: Send a Text Message on a channel.
SendURL: Send a URL.
Set: Set channel variable or function value.
SetAMAFlags: Set the AMA Flags.
SMS: Communicates with SMS service centres and SMS capable analogue phones.
SoftHangup: Hangs up the requested channel.
SpeechActivateGrammar: Activate a grammar.
SpeechBackground: Play a sound file and wait for speech to be recognized.
SpeechCreate: Create a Speech Structure.
SpeechDeactivateGrammar: Deactivate a grammar.
SpeechDestroy: End speech recognition.
SpeechLoadGrammar: Load a grammar.
SpeechProcessingSound: Change background processing sound.
SpeechStart: Start recognizing voice in the audio stream.
SpeechUnloadGrammar: Unload a grammar.
StackPop: Remove one address from gosub stack.
StartMusicOnHold: Play Music On Hold.
Stasis: Invoke an external Stasis application.
StopMixMonitor: Stop recording a call through MixMonitor, and free the recording’s file handle.
StopMonitor: Stop monitoring a channel.
StopMusicOnHold: Stop playing Music On Hold.
StopPlayTones: Stop playing a tone list.
StreamEcho: Echo media, up to ‘N’ streams of a type, and DTMF back to the calling party
VMSayName: Play the name of a voicemail user
VoiceMail: Leave a Voicemail message.
Record: Record to a file.
RemoveQueueMember: Dynamically removes queue members.
ResetCDR: Resets the Call Data Record.
RetryDial: Place a call, retrying on failure allowing an optional exit extension.
Return: Return from gosub routine.
Ringing: Indicate ringing tone.
SayNumber: Say Number.
SMS: Communicates with SMS service centres and SMS capable analogue phones.
SoftHangup: Hangs up the requested channel.
SpeechActivateGrammar: Activate a grammar.
SpeechBackground: Play a sound file and wait for speech to be recognized.
SpeechCreate: Create a Speech Structure.
SpeechDeactivateGrammar: Deactivate a grammar.
SpeechDestroy: End speech recognition.
SpeechLoadGrammar: Load a grammar.
SpeechProcessingSound: Change background processing sound.
SpeechStart: Start recognizing voice in the audio stream.
StartMusicOnHold: Play Music On Hold.
Stasis: Invoke an external Stasis application.
StopMixMonitor: Stop recording a call through MixMonitor, and free the recording’s file handle.
StopMonitor: Stop monitoring a channel.
StopMusicOnHold: Stop playing Music On Hold.
StopPlayTones: Stop playing a tone list.
StreamEcho: Echo media, up to ‘N’ streams of a type, and DTMF back to the calling party
System: Execute a system command.
VoiceMail: Leave a Voicemail message.
VoiceMailMain: Check Voicemail messages.
VoiceMailPlayMsg: Play a single voice mail msg from a mailbox by msg id.
Wait: Waits for some time.
Zapateller: Block telemarketers with SIT.

Webrtc support for asterisk over res_pjsip

Refernce project https://github.com/altanai/asteriskexamples/tree/master/webrtc_pjsip

To connect video based webrtc endpoints ensure you load the codecs and also libsrtp . Overwrite the selective conf in this folders with the existing conf of asterisk to run a basic webrtc video call . These were tested with jssip on asterisk v17 with res_pjsip.

confirm using pjsip – since chan_sip is depriciate. Confirm that yo are not using chan_sip and instead ensure using re_pjsip

module unload chan_sip
module show like res_pjsip

If pjssip is not found load it wither form menuselect or by using cli load module command .

pjssip show endpoints

*CLI> pjsip show endpoints

 Endpoint:  <Endpoint/CID.....................................>  <State.....>  <Channels.>
    I/OAuth:  <AuthId/UserName...........................................................>
        Aor:  <Aor............................................>  <MaxContact>
      Contact:  <Aor/ContactUri..........................> <Hash....> <Status> <RTT(ms)..>
  Transport:  <TransportId........>  <Type>  <cos>  <tos>  <BindAddress..................>
   Identify:  <Identify/Endpoint.........................................................>
        Match:  <criteria.........................>
==========================================================================================

 Endpoint:  7000                                                 Invalid       0 of inf
     InAuth:  7000/7000
        Aor:  7000                                               1

 Endpoint:  8000                                                 Invalid       0 of inf
     InAuth:  8000/8000
        Aor:  8000                                               1

Generating self-signed certs

use the “ast_tls_cert” script in the “contrib/scripts” Asterisk source directory to make a self-signed certificate authority and an Asterisk certificate.

sh ast_tls_cert.sh -C localhost -O "altanai" -d .

after creating the self signed keys start the server

asterisk -vvvvvvc

channels

Peer             User/ANR         Call ID          Format           Hold     Last Message    Expiry     Peer      
10.10.10.10     1060             e8ae107f-ce90-2  (ulaw)           No       Rx: ACK                    1060 

Codecs – check for the webrtc supported audio and video codesc in the list , if not found install the modules and reload.

  31 image png          png              (PNG Image)
   6 audio g726         g726             (G.726 RFC3551)
   4 audio alaw         alaw             (G.711 a-law)
   2 audio g723         g723             (G.723.1)
  20 audio speex        speex            (SpeeX)
  21 audio speex        speex16          (SpeeX 16khz)
  22 audio speex        speex32          (SpeeX 32khz)
  24 audio g722         g722             (G722)
  25 audio siren7       siren7           (ITU G.722.1 (Siren7, licensed from Polycom))
  32 video h261         h261             (H.261 video)
  33 video h263         h263             (H.263 video)
   8 audio adpcm        adpcm            (Dialogic ADPCM)
  36 video h265         h265             (H.265 video)
  44 audio silk         silk8            (SILK Codec (8 KHz))
  45 audio silk         silk12           (SILK Codec (12 KHz))
  46 audio silk         silk16           (SILK Codec (16 KHz))
  47 audio silk         silk24           (SILK Codec (24 KHz))
  28 audio g719         g719             (ITU G.719)
  34 video h263p        h263p            (H.263+ video)
  35 video h264         h264             (H.264 video)
  19 audio g729         g729             (G.729A)
   9 audio slin         slin             (16 bit Signed Linear PCM)
  10 audio slin         slin12           (16 bit Signed Linear PCM (12kHz))
  11 audio slin         slin16           (16 bit Signed Linear PCM (16kHz))
  12 audio slin         slin24           (16 bit Signed Linear PCM (24kHz))
  13 audio slin         slin32           (16 bit Signed Linear PCM (32kHz))
  14 audio slin         slin44           (16 bit Signed Linear PCM (44kHz))
  15 audio slin         slin48           (16 bit Signed Linear PCM (48kHz))
  16 audio slin         slin96           (16 bit Signed Linear PCM (96kHz))
  17 audio slin         slin192          (16 bit Signed Linear PCM (192kHz))
   3 audio ulaw         ulaw             (G.711 u-law)
  18 audio lpc10        lpc10            (LPC10)
  27 audio testlaw      testlaw          (G.711 test-law)
  43 audio none         none             (<Null> codec)
  42 image t38          t38              (T.38 UDPTL Fax)
  39 video vp9          vp9              (VP9 video)
  38 video vp8          vp8              (VP8 video)
   5 audio gsm          gsm              (GSM)
  37 video mpeg4        mpeg4            (MPEG4 video)
  23 audio ilbc         ilbc             (iLBC)
  40 text  red          red              (T.140 Realtime Text with redundancy)
  41 text  t140         t140             (Passthrough T.140 Realtime Text)
  29 audio opus         opus             (Opus Codec)
  30 image jpeg         jpeg             (JPEG image)
   7 audio g726aal2     g726aal2         (G.726 AAL2)
   1 audio codec2       codec2           (Codec 2)
  26 audio siren14      siren14          (ITU G.722.1 Annex C, (Siren14, licensed from Polycom))

Webrtc clients

Here is a succesful run using PJSIP as the webrtc client to communicated to another pjsip client via Asterisk server .

Note that all signalling and media isi getting proxied via the Asterisk server signalling and media plane which is in contrast to the peer to peer nature of WebRTC

Register with SIP Registrar on Asterisk
Specify the contact URI as the Asterisk server too
Incoming Call
WebRTC Call in progress via asterisk SIP and Media Server
Signalling and Media Proxy Via Asterisk

Debugging

set debug all

pjsip set logger on
rtp set debug on

setting debugger on a peer

SIP SET DEBUG PEER 1061

Chrome WebRTC Internals

References :