voip-with-freeswitch

voip-with-freeswitch

Enterprise-grade VoIP solutions using FreeSWITCH and .NET

January 22, 2024 · 15 min read

Building Scalable VoIP with FreeSWITCH

FreeSWITCH is a powerful, open-source telephony platform that can handle millions of concurrent calls. Combined with .NET, you can build enterprise-grade VoIP solutions that scale.

What is FreeSWITCH?

FreeSWITCH is a software-defined telecom stack enabling:

  • Voice calls (SIP, WebRTC)
  • Video calls and conferencing
  • SMS/MMS messaging
  • IVR (Interactive Voice Response)
  • Call recording and transcription

Architecture Overview

Text
┌─────────────┐
│   SIP Clients   │
└────────┬────────┘
         │
    ┌────▼─────┐
    │ FreeSWITCH  │
    └────┬─────┘
         │
    ┌────▼─────┐
    │  .NET API   │
    └────┬─────┘
         │
    ┌────▼─────┐
    │  Database   │
    └──────────┘

FreeSWITCH Installation

Ubuntu/Debian

Terminal
# Add FreeSWITCH repository
wget -O - https://files.freeswitch.org/repo/deb/debian-release/fsstretch-archive-keyring.asc | apt-key add -

# Install FreeSWITCH
apt-get update
apt-get install freeswitch-meta-all

Configuration

Basic vars.xml setup:

XML
<X-PRE-PROCESS cmd="set" data="domain=your-domain.com"/>
<X-PRE-PROCESS cmd="set" data="internal_sip_port=5060"/>
<X-PRE-PROCESS cmd="set" data="external_rtp_ip=auto"/>

.NET Integration

ESL (Event Socket Library)

Connect to FreeSWITCH from .NET:

C#
using FreeSwitch.EventSocket;

public class FreeSwitchService
{
    private readonly InboundSocket _socket;
    
    public async Task ConnectAsync()
    {
        _socket = new InboundSocket("localhost", 8021, "ClueCon");
        await _socket.ConnectAsync();
        
        _socket.OnEvent += HandleEvent;
    }
    
    private void HandleEvent(Event fsEvent)
    {
        switch (fsEvent.EventName)
        {
            case "CHANNEL_CREATE":
                Console.WriteLine($"New call: {fsEvent.GetHeader("Caller-ANI")}");
                break;
            case "CHANNEL_HANGUP":
                Console.WriteLine("Call ended");
                break;
        }
    }
}

Making Outbound Calls

C#
public async Task<string> OriginateCallAsync(string destination, string callerId)
{
    var command = $"originate {{origination_caller_id_number={callerId}}}sofia/gateway/provider/{destination} &park";
    
    var response = await _socket.SendApiAsync(new ApiCommand(command));
    
    if (response.Success)
        return response.Data; // Returns UUID
    
    throw new Exception("Call failed: " + response.ErrorMessage);
}

IVR with .NET

C#
public class IvrController : OutboundSocket
{
    public override async Task OnConnectAsync()
    {
        await Answer();
        await Sleep(1000);
        
        var digit = await PlayAndGetDigits(
            minDigits: 1,
            maxDigits: 1,
            tries: 3,
            timeout: 5000,
            terminators: "#",
            soundFile: "ivr/main-menu.wav",
            invalidFile: "ivr/invalid.wav"
        );
        
        switch (digit)
        {
            case "1":
                await Transfer("sales-queue");
                break;
            case "2":
                await Transfer("support-queue");
                break;
            default:
                await Playback("ivr/goodbye.wav");
                await Hangup();
                break;
        }
    }
}

Advanced Features

Call Recording

XML
<!-- In dialplan -->
<action application="record_session" data="/recordings/${uuid}.wav"/>
C#
public async Task StartRecordingAsync(string uuid)
{
    await _socket.SendApiAsync(
        new ApiCommand($"uuid_record {uuid} start /recordings/{uuid}.wav")
    );
}

Conference Rooms

C#
public async Task CreateConferenceAsync(string roomName, string pin)
{
    var command = $"conference {roomName} dial {{conference_pin={pin}}}sofia/gateway/provider/conference";
    await _socket.SendApiAsync(new ApiCommand(command));
}

public async Task<ConferenceStatus> GetConferenceStatusAsync(string roomName)
{
    var response = await _socket.SendApiAsync(
        new ApiCommand($"conference {roomName} list")
    );
    
    return ParseConferenceResponse(response.Data);
}

WebRTC Support

FreeSWITCH configuration for WebRTC:

XML
<profile name="webrtc">
  <param name="ws-binding" value=":5066"/>
  <param name="wss-binding" value=":7443"/>
  <param name="tls-cert-dir" value="/etc/freeswitch/tls"/>
</profile>

JavaScript client:

JavaScript
const phone = new SIP.UA({
    uri: 'sip:user@domain.com',
    transportOptions: {
        wsServers: ['wss://your-server.com:7443'],
        traceSip: true
    }
});

phone.on('connected', () => {
    phone.invite('sip:destination@domain.com');
});

Scaling FreeSWITCH

Load Balancing

Use Kamailio or OpenSIPS as SIP proxy:

Text
    ┌─────────┐
    │  Clients  │
    └────┬────┘
         │
    ┌────▼────┐
    │ Kamailio  │
    └────┬────┘
         │
    ┌────▼────────────────┐
    │  FreeSWITCH Cluster  │
    │  FS1  │  FS2  │ FS3  │
    └─────────────────────┘

Database Backend

Store users in PostgreSQL:

SQL
CREATE TABLE users (
    username VARCHAR(255) PRIMARY KEY,
    password VARCHAR(255),
    domain VARCHAR(255),
    enabled BOOLEAN DEFAULT true
);

Configure FreeSWITCH to use database:

XML
<param name="odbc-dsn" value="dsn:username:password"/>

Monitoring & Analytics

Real-time Statistics

C#
public class CallStatistics
{
    public async Task<Stats> GetStatsAsync()
    {
        var channels = await _socket.SendApiAsync(new ApiCommand("show channels count"));
        var calls = await _socket.SendApiAsync(new ApiCommand("show calls count"));
        
        return new Stats
        {
            ActiveChannels = int.Parse(channels.Data),
            ActiveCalls = int.Parse(calls.Data)
        };
    }
}

CDR (Call Detail Records)

Store CDRs in database for analytics:

C#
public class CdrRecord
{
    public Guid CallId { get; set; }
    public string Caller { get; set; }
    public string Callee { get; set; }
    public DateTime StartTime { get; set; }
    public DateTime? EndTime { get; set; }
    public int Duration { get; set; }
    public string Disposition { get; set; } // ANSWERED, BUSY, NO_ANSWER
}

Conclusion

FreeSWITCH combined with .NET provides a powerful stack for building VoIP solutions. Whether you're building a call center, conferencing platform, or SIP gateway, this combination offers the flexibility and scalability needed for enterprise deployments.

The learning curve is steep, but the capabilities are worth the investment. Start with basic call routing, then gradually add features like IVR, recording, and WebRTC support.

.NETFreeSWITCHSIPVoIP
Continues in the chat

Subscribe to Newsletter

Get notified about new articles