Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ask STUN server to generate the ice candidates using aiortc?

I have a working WebRTC client, and I want to receive it's video via WebRTC using aiotrc (python). The other client is working fine as the recipient, we have tested it with a browser.

Using python, I configure the server, I create an offer with a Transceiver (I only want to receive the video), and I set the offer as the localDescription:

import json
import socketio
import asyncio
from asgiref.sync import async_to_sync
from aiortc import RTCPeerConnection, RTCSessionDescription, RTCIceCandidate, RTCConfiguration, RTCIceServer, RTCIceGatherer, RTCRtpTransceiver

session_id = 'default'

sio = socketio.Client()

ice_server = RTCIceServer(urls='stun:stun.l.google.com:19302')
pc = RTCPeerConnection(configuration=RTCConfiguration(iceServers=[ice_server]))

pc.addTransceiver("video", direction="recvonly")

def connect():
    sio.connect('https://192.168.10.123', namespaces=['/live'])

connect()

@async_to_sync
async def set_local_description():
    await pc.setLocalDescription(await pc.createOffer())
    print('Local description set to: ', pc.localDescription)
    #send_signaling_message(json.dumps({'sdp':{'sdp': pc.localDescription.sdp, 'type':pc.localDescription.type}}))


set_local_description()

(Where the socket.io is connecting is a fake address in this case). After this point, I have no idea how to gather the ice candidates. I have tried using the iceGatherer with no luck:

ice_gath = RTCIceGatherer(iceServers=[ice_server])
candidates = ice_gath.getLocalCandidates()

I have to send the ice candidate to the recipient. At this point I couldn't find any information about, how to get the ice candidates using aiortc. What is the next step?

like image 415
adamb Avatar asked Sep 02 '25 16:09

adamb


1 Answers

The code you posted has in fact already performed the ICE candidate gathering, when you called setLocalDescription. Look at the session description you are printing and you should see candidates marked as srflx which means "server reflexive": these are your IP addresses as seen from the STUN server's perspective, e.g:

a=candidate:5dd630545cbb8dd4f09c40b43b0f2db4 1 udp 1694498815 PUBLIC.IP.ADDRESS.HERE 42162 typ srflx raddr 192.168.1.44 rport 42162

Also note that by default aiortc already uses Google's STUN server, so here is an even more reduced version of your example:

import asyncio

from aiortc import RTCPeerConnection


async def dump_local_description():
    pc = RTCPeerConnection()
    pc.addTransceiver("video", direction="recvonly")

    await pc.setLocalDescription(await pc.createOffer())
    print(pc.localDescription.sdp)


loop = asyncio.get_event_loop()
loop.run_until_complete(dump_local_description())
like image 120
Jeremy Avatar answered Sep 05 '25 06:09

Jeremy