Skip to content

SIP Protocol Examples

This page provides practical examples for common SIP protocol operations.

Basic Call Flow

Making a Call

// Initialize call options
const callOptions = {
  to: 'sip:[email protected]',
  from: 'sip:[email protected]',
  mediaOptions: {
    audio: {
      codecs: ['OPUS', 'G.711'],
      echoCancellation: true,
      noiseSuppression: true
    },
    video: {
      enabled: true,
      codecs: ['VP8', 'H.264'],
      resolution: '720p',
      frameRate: 30
    }
  }
};

// Make the call
const call = await client.sip.call(callOptions);

// Handle call events
call.on('trying', () => {
  console.log('Call is being processed');
});

call.on('ringing', () => {
  console.log('Remote endpoint is ringing');
});

call.on('accepted', () => {
  console.log('Call has been accepted');
});

call.on('rejected', (reason) => {
  console.log('Call was rejected:', reason);
});

call.on('terminated', (reason) => {
  console.log('Call ended:', reason);
});

Receiving Calls

// Configure incoming call handler
client.sip.on('incomingCall', async (call) => {
  console.log('Incoming call from:', call.from);

  // Check if we can handle the call
  if (await isAvailableForCalls()) {
    // Answer the call
    await call.answer({
      audio: {
        codecs: ['OPUS', 'G.711'],
        echoCancellation: true
      },
      video: call.hasVideo() ? {
        codecs: ['VP8'],
        resolution: '720p'
      } : undefined
    });
  } else {
    // Reject with Busy Here
    await call.reject(486, 'Busy Here');
  }

  // Handle call state changes
  call.on('connected', () => {
    console.log('Call connected');
  });

  call.on('muted', (type) => {
    console.log(`${type} was muted`);
  });

  call.on('unmuted', (type) => {
    console.log(`${type} was unmuted`);
  });
});

Media Control

Audio Management

// Configure audio settings
const audioConfig = {
  input: {
    echoCancellation: true,
    noiseSuppression: true,
    autoGainControl: true,
    volume: 1.0
  },
  output: {
    volume: 0.8,
    deviceId: 'default'
  },
  codecs: [
    {
      name: 'OPUS',
      clockRate: 48000,
      channels: 2,
      parameters: {
        maxplaybackrate: 48000,
        stereo: 1,
        useinbandfec: 1
      }
    },
    {
      name: 'PCMA',
      clockRate: 8000,
      channels: 1
    }
  ]
};

await call.setAudioConfig(audioConfig);

// Handle audio events
call.on('audioDeviceChanged', (device) => {
  console.log('Audio device changed:', device);
});

call.on('audioLevelChange', (level) => {
  console.log('Audio level:', level);
});

Video Management

// Configure video settings
const videoConfig = {
  input: {
    deviceId: 'default',
    resolution: {
      width: 1280,
      height: 720
    },
    frameRate: 30
  },
  output: {
    scaling: 'crop',
    aspectRatio: '16:9'
  },
  codecs: [
    {
      name: 'VP8',
      parameters: {
        'max-fr': 30,
        'max-fs': 12288
      }
    },
    {
      name: 'H264',
      parameters: {
        'profile-level-id': '42e01f',
        'packetization-mode': 1
      }
    }
  ]
};

await call.setVideoConfig(videoConfig);

// Handle video events
call.on('videoStateChange', (state) => {
  console.log('Video state changed:', state);
});

Messaging

Instant Messaging

// Send text message
await client.sip.sendMessage({
  to: 'sip:[email protected]',
  from: 'sip:[email protected]',
  content: 'Hello Bob!',
  contentType: 'text/plain'
});

// Send formatted message
await client.sip.sendMessage({
  to: 'sip:[email protected]',
  from: 'sip:[email protected]',
  content: '<message>Hello <b>Bob</b>!</message>',
  contentType: 'application/xml'
});

// Handle incoming messages
client.sip.on('message', (message) => {
  console.log('From:', message.from);
  console.log('Content-Type:', message.contentType);
  console.log('Content:', message.content);
});

File Transfer

// Send file
const fileTransfer = await client.sip.sendFile({
  to: 'sip:[email protected]',
  file: {
    name: 'document.pdf',
    type: 'application/pdf',
    size: 1024000,
    data: fileBuffer
  },
  thumbnail: {
    type: 'image/jpeg',
    data: thumbnailBuffer
  }
});

fileTransfer.on('progress', (progress) => {
  console.log(`Upload progress: ${progress}%`);
});

// Receive file
client.sip.on('fileTransfer', async (transfer) => {
  console.log('File:', transfer.file.name);
  console.log('Size:', transfer.file.size);

  const file = await transfer.accept({
    directory: '/downloads'
  });

  transfer.on('progress', (progress) => {
    console.log(`Download progress: ${progress}%`);
  });
});

Presence

Publishing Status

// Publish presence information
await client.sip.publish({
  status: 'online',
  note: 'Available for calls',
  activity: 'meeting',
  capabilities: ['audio', 'video', 'im'],
  deviceType: 'desk',
  mood: 'positive'
});

// Update presence with rich information
await client.sip.publish({
  status: 'busy',
  note: 'In a meeting',
  activity: {
    what: 'meeting',
    with: ['sip:[email protected]', 'sip:[email protected]'],
    duration: 3600
  },
  location: {
    timestamp: new Date(),
    latitude: 51.5074,
    longitude: -0.1278,
    altitude: 20,
    accuracy: 10
  }
});

Subscribing to Presence

// Subscribe to contact's presence
const subscription = await client.sip.subscribe({
  to: 'sip:[email protected]',
  event: 'presence',
  expires: 3600
});

subscription.on('notify', (presence) => {
  console.log('Status:', presence.status);
  console.log('Note:', presence.note);
  console.log('Activity:', presence.activity);
});

subscription.on('terminated', (reason) => {
  console.log('Subscription ended:', reason);
});

Advanced Features

Conference Calls

// Create conference room
const conference = await client.sip.createConference({
  roomName: 'team-meeting',
  maxParticipants: 10,
  mediaOptions: {
    audio: true,
    video: true,
    recording: true
  }
});

// Add participants
await conference.invite([
  'sip:[email protected]',
  'sip:[email protected]'
]);

// Handle conference events
conference.on('participantJoined', (participant) => {
  console.log(`${participant.uri} joined`);
});

conference.on('participantLeft', (participant) => {
  console.log(`${participant.uri} left`);
});

Call Transfer

// Blind transfer
await call.transfer('sip:[email protected]');

// Attended transfer
const transferCall = await call.attendedTransfer('sip:[email protected]');

transferCall.on('ringing', () => {
  console.log('Transfer target is ringing');
});

transferCall.on('accepted', () => {
  console.log('Transfer completed');
});

Quality Monitoring

Media Statistics

// Monitor call quality
call.on('stats', (stats) => {
  console.log('Audio Stats:', {
    packetLoss: stats.audio.packetLoss,
    jitter: stats.audio.jitter,
    roundTripTime: stats.audio.rtt,
    codec: stats.audio.codec,
    level: stats.audio.level
  });

  if (stats.video) {
    console.log('Video Stats:', {
      packetLoss: stats.video.packetLoss,
      frameRate: stats.video.frameRate,
      resolution: stats.video.resolution,
      bitrate: stats.video.bitrate,
      codec: stats.video.codec
    });
  }
});

Network Quality

// Monitor network conditions
call.on('networkQuality', (quality) => {
  console.log('Network Quality:', {
    upload: quality.upload,
    download: quality.download,
    rtt: quality.rtt
  });

  if (quality.upload < 0.5) {
    // Adapt to poor upload conditions
    call.setVideoQuality('low');
  }
});