Skip to content

A conference focus with mixing

A conference focus (RFC 4579) is the user agent every participant of a conference has a dialog with. siphon can be that focus with the media engine doing the mixing: the script answers each participant's INVITE itself, the engine seats the participant in a room and hands back the answer SDP, and every seat hears the room minus itself.

Mixing needs the native siphon-rtp engine (media.backend: siphon-rtp). rtpengine and rtpproxy have no mixer, and every conference_* verb raises RuntimeError naming the backend on them.

media:
  backend: siphon-rtp
  siphon_rtp:
    address: "127.0.0.1:8080"

Rooms and seats

  • A room is named by an id the script chooses. The engine creates it on its first conference_join and ends it with its last conference_leave, so the script owns the id space: one room per conference URI.
  • A seat is a participant's call, addressed by its From-tag. That is the name @rtpengine.on_active_speaker and a room's @rtpengine.on_dtmf hand back.
  • A room holds at most 64 seats. Bridged rooms (conference_bridge) each hear the other's participants.

The focus

The factory URI (RFC 4579 section 5.2) mints a room; an INVITE to a conference URI joins it. A BYE leaves. The roster is just what joined and has not left.

import uuid

from siphon import b2bua, proxy, rtpengine, log

FACTORY = "conference-factory"

# room id -> {call_id: participant URI}
ROSTER = {}
# call_id -> room id, since a factory INVITE's own URI names no room
ROOM_OF_CALL = {}


def room_of(call):
    """The room an INVITE names: a fresh one for the factory URI."""
    user = call.ruri.user
    if user == FACTORY:
        return f"room-{uuid.uuid4().hex[:12]}"
    return user


@proxy.on_request("OPTIONS")
def health(request):
    request.reply(200, "OK")


@b2bua.on_invite
async def on_invite(call):
    room = room_of(call)
    try:
        sdp = await rtpengine.conference_join(room, call)
    except ValueError as error:
        # The room cannot mix the participant's codec (RFC 3264 section 6).
        log.warn(f"{room}: {error}")
        call.reject(488, "Not Acceptable Here")
        return
    # RFC 4579 section 5.1: the focus's Contact is the conference URI, with
    # `isfocus`. A factory-minted room's creator learns its URI here.
    call.answer(200, "OK", body=sdp, content_type="application/sdp",
                contact=f"sip:{room}@{call.ruri.host}", contact_params="isfocus")
    ROOM_OF_CALL[call.call_id] = room
    ROSTER.setdefault(room, {})[call.call_id] = str(call.from_uri)
    log.info(f"{room}: {call.from_uri} joined, {len(ROSTER[room])} seated")
    # RFC 4575: a <user> joined the roster; NOTIFY the subscribers here.


@b2bua.on_bye
async def on_bye(call, initiator):
    room = ROOM_OF_CALL.pop(call.call_id, None)
    if room is None:
        return
    # `rtpengine.delete(call)` would leave the room as well.
    await rtpengine.conference_leave(room, call)
    seats = ROSTER.get(room, {})
    seats.pop(call.call_id, None)
    if not seats:
        ROSTER.pop(room, None)
    # RFC 4575: a <user> left the roster; NOTIFY the subscribers here.


@rtpengine.on_active_speaker
def floor(conference_id, from_tag):
    # `from_tag` is None when the floor goes silent. RFC 4575 carries the
    # speaker as a <media> status; a focus would NOTIFY it from here.
    log.info(f"{conference_id}: {from_tag or 'nobody'} has the floor")

A factory-minted room's URI goes back to its creator as the focus's Contact, with the isfocus feature parameter (RFC 4579 section 5.1), so that later participants can dial it, or be referred to it. The URI has to route back to siphon: the creator's in-dialog requests are sent to it. The RFC 4575 event package itself is not shown: the comments mark where its NOTIFYs would go.

With five participants the room has five seats and each hears the other four. rtpengine.delete(call) on a seated call leaves its room as well, so a script that already deletes media on BYE does not need a second call.

Who hears whom

role= on conference_join, or later on conference_route, places a seat in the room's routing matrix, live and without a re-INVITE:

role hears is heard by
talker the room minus itself everyone (default)
listener the room no one
muted the room no one
whisper the room minus itself only target
monitor target alone, unknown to it no one, or whisper_target
from siphon import rtpengine

async def mute(room, call):
    await rtpengine.conference_route(room, call, "muted")

async def coach(room, supervisor, agent_tag):
    # The supervisor hears the agent and talks to the agent alone.
    await rtpengine.conference_route(
        room, supervisor, "monitor", target=agent_tag, whisper_target=agent_tag
    )

A seat can also be named by a (call_id, from_tag) pair, which is what an event handler holds.

conference_route on a seat the room does not hold is an error (RuntimeError), as is a route after the seat has left. Older engines answered ok for it and did nothing, so a script that routed a seat it never checked (a hold handler that mutes a call whose seat is already gone) will now see the failure; catch it, or route only calls the roster still lists. An adopted seat is named by the engine's tag for the far leg, not by the call's From-tag, so route one from b2bua.conference_roster(room)'s from_tag.

Digits to the other seats

A seat's RFC 4733 telephone-events are @rtpengine.on_dtmf events and never leave the seat. dtmf="forward" on conference_join, conference_offer or b2bua.adopt_replaced has the room also regenerate them toward every other seat, each in that seat's own telephone-event payload type, clock and stream, so a participant driving an IVR on a merged call is heard by it. Only the seat set to forward forwards; the others stay on events (the default, also None). conference_route(..., dtmf=...) switches it live, and dtmf=None keeps the seat's setting. Anything else raises ValueError.

The usual split: the conference owner's own seat forwards, because its client is the one pressing keys on the merged parties, and the adopted seats stay on events so the carriers' own tones are not echoed to everyone:

sdp = await rtpengine.conference_join(room, call, dtmf="forward")   # the owner
...
status = await b2bua.adopt_replaced(call, room)                     # adopted: events

The engine has to list conference_dtmf in node_info (siphon-rtp 0.19); on one that does not, forward (and an explicit dtmf on a route) is refused (RuntimeError; a merge resolves 501) and nothing is sent, instead of the engine ignoring the field and dropping the digits. The seat's setting is the dtmf key of b2bua.conference_roster.

Merging two conferences

from siphon import rtpengine

async def merge(room_a, room_b):
    await rtpengine.conference_bridge(room_a, room_b)              # each hears the other
    # await rtpengine.conference_bridge(room_a, room_b, direction="a_to_b")

rtpengine.conference_unbridge(room_a, room_b) splits them again, whichever way the link was made; a link also ends with either room.

Merging calls this node already holds

A handset's "merge" (RFC 4579 §5.5, TS 24.147) INVITEs the conference factory, then REFERs the focus inside that conference dialog once per call it wants in, each Refer-To carrying a Replaces (RFC 3891) that names the handset's own dialog with the other party. When those calls run through this same node, the focus cannot INVITE itself with the Replaces. b2bua.adopt_replaced merges the call in place instead:

from siphon import b2bua

ROOMS = {}   # conference dialog Call-ID -> room id, filled at the factory INVITE


@b2bua.on_refer
async def on_refer(call):
    call.accept_refer(mode="script")
    status = await b2bua.adopt_replaced(call, ROOMS[call.call_id])
    b2bua.complete_refer(call.call_id, status)

What it does:

  1. Finds the call holding the named dialog, either its caller leg (the subscriber placed the call) or its callee leg (the subscriber was called).
  2. Checks the dialog belongs to the party that sent the REFER. Holding a dialog's identifiers is no authority to take it over (RFC 3891 §5). Both legs carry an auth_user: it has to be the same. Otherwise, both on a stream transport: the same connection. Otherwise: the same source address and the same user on both dialogs, which is the rule a deployment that authorises INVITEs by registration source rather than digest runs on. call.refer_replaces_call shows the facts compared (Call-ID, which leg, source, transport, From URI, auth_user), so a script can refuse more.
  3. Seats the call's other leg, the far party, in the room with siphon-rtp conference_seat: same ports, same session, and no SIP toward that party.
  4. Sends the named leg a BYE with Reason: SIP;cause=200;text="Merged into conference".
  5. Takes the far party off hold when the handset held it before merging, as phones do. The hold belonged to the dialog the merge just ended, so the far party gets one re-INVITE: the session in force, same ports and codecs, at the next o= version, with a=sendrecv. A far party already sendrecv gets no SIP. One that answers recvonly or inactive holds the room itself and is left that way. A refusal, or no answer before Timer B, is logged as a warning and the call stays seated. The merge has already resolved 200, so the REFER's NOTIFY does not wait for the far party. An answer that moves the address, port or codec is also a warning, since a seat cannot follow it.
  6. Becomes the far party's session refresher (RFC 4028). That party's session was refreshed by the handset's leg the merge just ended, so without this it would run out a session interval later. A timer siphon already ran keeps its interval, with siphon refreshing at half of it. Where siphon runs no session timer, it refreshes at once asking to be the refresher (the configured session_timer.session_expires, else 1800), and the party's 2xx sets the interval. The resume of step 5 is that first refresh. The refresh is an UPDATE without a body where the party allows UPDATE, otherwise a re-INVITE of the session in force. A 408 or 481 to it ends the call through the normal teardown.

It resolves to the status the REFER's NOTIFY reports:

Status Meaning
200 merged
481 no confirmed dialog here matches the Replaces (or there is none, or the call is still early)
403 the named dialog is not the referrer's
488 the engine refused the seat (room full, a codec it cannot mix, a draining node) or the call is being transferred, bridged or merged already
501 the media backend is not siphon-rtp, or the engine does not list conference_seat

A refusal leaves the named call exactly as it was. There is no fallback to a re-INVITE of the far party.

The merged call stays a call. Its Ro session, max_call_duration_secs, session timer and CDR carry on, with the far party as its one SIP leg and a room seat where its other leg was. A re-INVITE or UPDATE from the far party is answered against the session in force (@b2bua.on_reoffer sees it first; with several handlers each should return early for calls that are not its own, see several handlers), so a session refresh gets a 200 with the unchanged session. The far party's BYE, a credit teardown, the maximum duration, or a media_timeout on the seat end the call through its normal path, and the engine delete takes the seat out; the room carries on with whoever is left. Its digits and quality reports arrive under the call's own Call-ID, not the room's. GET /admin/calls shows its peer as conference:<room>.

on_owner_leave="end" (the default) ends the merged call, with a BYE carrying Reason: Q.850;cause=16, when the conference dialog that adopted it ends: the referrer pays for both far legs, so a room that outlives it is two other parties talking on its credit. "keep" leaves it in the room. The link is held by siphon, not the script, so it survives a script reload. role= is "talker" (default), "listener" or "muted".

on_last_leave="end_owner" ends the conference dialog the other way round: when the last call adopted under it has left and no seat but the dialog's own remains in the room, siphon BYEs the dialog with Reason: Q.850;cause=16 through the normal teardown, so its CDR and charging close. A conference of one is over. The default, "keep", leaves the dialog to the client. It is held like on_owner_leave, by siphon, so a reload does not lose it. When several calls were adopted with different values, the call that leaves last decides.

Roster and conference-info (RFC 4575)

A focus tells its subscribers who is in the room with application/conference-info+xml NOTIFYs (RFC 4575, event package conference). A script that holds nothing of its own, because a reload empties module state and a conference outlives a deploy, reads the room from siphon and is told when it changes:

  • b2bua.conference_roster(conference_id) is a list of dicts, one per seat in the room, in the order they were seated: call_id (the SIP Call-ID of the dialog with the seated party), from_tag, party_uri, role, joined_at (unix seconds, a float), kind and owner_call_id. kind is "joined" for a seat rtpengine.conference_join or conference_answer took and "adopted" for one adopt_replaced made; owner_call_id is the conference dialog that adopted it, None for a joined seat. An unknown room is an empty list.
  • call.conference is (conference_id, owner_call_id) for a call seated in a room, else None. It reads in @b2bua.on_bye too, before the teardown frees the seat.
  • @b2bua.on_conference_change is called as fn(conference_id, owner_call_id, change, call_id, roster) once for each seat that comes in and once for each seat that goes out, whatever ended it: the adopted call's BYE, a credit or duration teardown, a silent seat, a conference_leave or delete, the conference dialog ending the calls it adopted (one "left" per seat). change is "joined" or "left", call_id the seat that changed, and roster the room after the change. owner_call_id is the dialog that adopted that seat; for a joined seat it is the dialog the adopted seats in the room agree on, else None. It runs off the SIP message path, from siphon's state, so it fires the same after a reload.
  • proxy.subscribe_state.for_resource(uri, event) lists the live subscriptions to a resource: the subscribers to NOTIFY.
from xml.sax.saxutils import quoteattr

from siphon import b2bua, proxy

FOCUS = "sip:{room}@conf.example.com"


def conference_info(room, roster, state):
    users = "".join(
        f"<user entity={quoteattr(seat['party_uri'] or 'sip:anonymous@anonymous.invalid')} state=\"full\">"
        f"<endpoint entity={quoteattr(seat['call_id'])}><status>connected</status></endpoint></user>"
        for seat in roster
    )
    return (
        "<?xml version=\"1.0\"?>"
        f"<conference-info xmlns=\"urn:ietf:params:xml:ns:conference-info\" "
        f"entity={quoteattr(FOCUS.format(room=room))} state=\"{state}\" version=\"{{version}}\">"
        f"<users>{users}</users></conference-info>"
    )


async def notify(handle, room, roster, state):
    # version= is monotonic per subscription (RFC 4575 §5.4, RFC 6665 §4.4.1).
    body = conference_info(room, roster, state).replace("{version}", str(handle.next_event_version()))
    await handle.notify(body=body, content_type="application/conference-info+xml")


@proxy.on_request("SUBSCRIBE")
async def subscribe(request):
    room = room_of(request.ruri)                      # your own mapping
    handle = proxy.subscribe_state.accept(request, expires=3600)
    if handle is not None:
        # Full state first (RFC 4575 §5.4), from siphon's roster.
        await notify(handle, room, b2bua.conference_roster(room), "full")


@b2bua.on_conference_change
async def changed(conference_id, owner_call_id, change, call_id, roster):
    for handle in proxy.subscribe_state.for_resource(FOCUS.format(room=conference_id), "conference"):
        await notify(handle, conference_id, roster, "full")

Sending full state on every change is the simplest correct thing; a script that wants state="partial" deltas builds them from change and call_id. for_resource compares the resource exactly after the normalisation a stored subscription's resource has (brackets and display name stripped), takes the event package token case-insensitively, and leaves out terminated and expired subscriptions and the ones this node originated. It reads the in-process store, like find: the Redis cache is keyed by dialog id and cannot be searched by resource, so a subscription held only there is listed once await proxy.subscribe_state.get(id) has loaded it.

With on_last_leave="end_owner" the roster events are what tell the subscribers the room is over: the last adopted call's "left" is followed by the owner's own.

Calling a participant in

To add someone who has not dialled in (RFC 4579 §5.5, a REFER to the focus naming a user; TS 24.605 CONF) the focus places the call, so the engine is the offerer: conference_offer allocates a new seat and resolves to the offer for the INVITE, and conference_answer seats the participant on its answer. A seat is named by a tag the script chooses.

import uuid

from siphon import b2bua, rtpengine

DIALLING = {}   # Call-ID of the INVITE the focus sent -> (room, seat tag)


async def call_in(room, target, replaces=None, referred_by=None):
    tag = uuid.uuid4().hex[:10]
    sdp = await rtpengine.conference_offer(room, tag)
    headers = {}
    if replaces:
        headers["Replaces"] = replaces          # RFC 3891: take a call over
    if referred_by:
        headers["Referred-By"] = referred_by    # RFC 3892
    call_id = b2bua.originate(target, sdp=sdp, headers=headers)
    DIALLING[call_id] = (room, tag)


@b2bua.on_answer
async def answered(call, reply):
    room, tag = DIALLING.pop(call.call_id, (None, None))
    if room is not None:
        await rtpengine.conference_answer(room, (call.call_id, tag), reply.body)


@b2bua.on_failure
async def not_answered(call, code, reason):
    room, tag = DIALLING.pop(call.call_id, (None, None))
    if room is not None:
        await rtpengine.conference_leave(room, (call.call_id, tag))

The offer lists every codec the room can mix in that engine build (a profile's codec flags edit it) as plain RTP/AVP; an answer has to pick one of them. rtpengine.delete(call) on the answered call leaves the room, as for a joined seat. An offer nobody answers is freed by conference_leave or by the engine's setup timeout.

Playing into a room

conference_play mixes a file, blob or tone into the room as a source nobody is mixed-minus-self against, and resolves to its play_id. Its end arrives as @rtpengine.on_play_finished with the room id as call_id and an empty from_tag. conference_set_play_gain ducks it, conference_stop_play ends one or all of them. Music for a lone participant:

from siphon import rtpengine

MUSIC = {}           # room id -> play_id

async def seated(room, seats):
    if seats == 1:
        MUSIC[room] = await rtpengine.conference_play(room, file="/prompts/moh.wav", repeat="inf")
    elif room in MUSIC:
        await rtpengine.conference_stop_play(room, MUSIC.pop(room))


@rtpengine.on_play_finished
def ended(call_id, from_tag, play_id, reason, played_ms):
    if MUSIC.get(call_id) == play_id:
        MUSIC.pop(call_id)

What the engine does not do yet

These are limits of siphon-rtp 0.14.0, not of the script API:

  • Codec choice. A seat takes the offer's first audio codec, and the engine must be able to decode it and encode the mix back into it (AMR needs the engine's amr build, G.729 its g729 build, and EVS is not implemented). A seat it cannot mix is refused with ValueError; a profile's codec policy is not applied to a seat, so conference_join refuses a profile that sets one rather than seating the call without it (the same goes for ws_uri, ws_tee, record_call and the DSP knobs).
  • Hold and mute by re-INVITE. A seat is no media session of its call, so siphon answers a participant's re-INVITE or UPDATE that changes the media 488 unless @b2bua.on_reoffer answers it. A hold (sendonly) is answered by offer.answer(), after conference_route(room, call, "listener") or "muted" so the room stops hearing it:

@b2bua.on_reoffer
async def seat_reoffer(call, offer):
    room = ROOM_OF_CALL.get(call.call_id)
    if room is None:
        return
    if offer.kind == "hold":
        await rtpengine.conference_route(room, call, "muted")
    elif offer.kind == "resume":
        await rtpengine.conference_route(room, call, "talker")
    offer.answer()
- Re-seating. There is no verb that updates a seat in place, and the engine does not report a second seat under one From-tag, so a call holds one seat and a second conference_join raises ValueError. A re-INVITE that changes the media has to leave and join again, which ends the room (and its playbacks and bridges) when the call was its only seat. - The 64-seat cap and a seat's packetization limits are checked by the room after the engine has answered the join, so a 65th participant is answered and then not mixed. Keep the count in the roster. - Recording a room (conference_start_recording) is not exposed yet: its completion has no script hook to arrive on.

The script on this page is examples/conference_focus.py, with its config in examples/conference_focus.yaml.