Asterisk directmedia and NAT
Recently we were vehemently told it is impossible to remove Asterisk from the media path if there is NAT involved. Naturally, we had to find out if that was wrong. It is absolutely possible, and here are a few ways to do it. These observations are based on experiments with Asterisk 11.
In order for audio to travel directly to the phone, bypassing Asterisk, one of two things must happen:
1) The service provider must ignore the IP address specified in the SDP. This is essential because if the phone is behind NAT, this will be a non-routable IP. Instead, the service provider should reply to the IP that the RTP traffic arrived to it from.
2) The phone must know the WAN IP address of its router so that it can identify itself with a routable IP.
The first option is easiest because it does not require configuring your device correctly. The second option requires a little effort, but is compatible with wholesale service providers that allow audio to travel directly between you and their carriers. Let's talk more about option 2. How can your phone learn the IP address of its router?
a) If Asterisk is outside NAT, and the phone is inside NAT, Asterisk will provide the phone's routable address to it upon registration. Here is an example of what the phone receives:
According to this, the phone's internal IP address is 192.168.1.18, and its router's WAN IP is 184.108.40.206. Now that the phone knows this, it can identify itself as 220.127.116.11. If Asterisk is outside NAT, this is the preferred option. If not, keep reading.
Via: SIP/2.0/UDP 192.168.1.18:5060;branch=z0aW2jA-d2214z-8754z-;received=18.104.22.168;rport=5060
b) You can hard-code the IP address into your phone. The technique for this varies from manufacturer to manufacturer. With Obihai devices, the setting is Service Providers >> ITSP Profile X >> SIP >> X_PublicIPAddress. If you have a static IP, infrequently-changing dynamic IP, or you can update your phone automatically using provisioning, and (a) won't work for you, this is the preferred option.
c) The phone could determine its router's WAN IP address using STUN. However, this may not be desirable. It adds a point of failure: if the STUN server goes down, your service won't work. Additionally, some manufacturers such as Obihai do not correctly support STUN, so even when things are working properly, they won't work well.
d) You can (theoretically) use your router's SIP ALG to rewrite SIP packets. However, when we tested our Tomato router, we discovered it not effective for reinvites to another endpoint on our LAN.
As long as you understand what you are doing, you can safely use any of the above four techniques with directmedia=yes in your sip.conf. As long as Asterisk is not doing something that requires it to proxy audio such as listening for DTMF or recording the call, Asterisk will remove itself from the audio path and audio will travel directly to your phone.