Module livekit.rtc.room

Classes

class ConnectError (message: str)
Expand source code
class ConnectError(Exception):
    def __init__(self, message: str):
        self.message = message

Common base class for all non-exit exceptions.

Ancestors

  • builtins.Exception
  • builtins.BaseException
class DataPacket (data: bytes,
kind: proto_room.DataPacketKind.ValueType,
participant: RemoteParticipant | None,
topic: str | None = None)
Expand source code
@dataclass
class DataPacket:
    data: bytes
    """The payload of the data packet."""
    kind: proto_room.DataPacketKind.ValueType
    """Type of the data packet (e.g., RELIABLE, LOSSY)."""
    participant: RemoteParticipant | None
    """Participant who sent the data. None when sent by a server SDK."""
    topic: str | None = None
    """Topic associated with the data packet."""

DataPacket(data: 'bytes', kind: 'proto_room.DataPacketKind.ValueType', participant: 'RemoteParticipant | None', topic: 'str | None' = None)

Instance variables

var data : bytes

The payload of the data packet.

var kind : int

Type of the data packet (e.g., RELIABLE, LOSSY).

var participant : RemoteParticipant | None

Participant who sent the data. None when sent by a server SDK.

var topic : str | None

Topic associated with the data packet.

class DataStreamOptions (max_payload_byte_length: int | None = None)
Expand source code
@dataclass
class DataStreamOptions:
    max_payload_byte_length: int | None = None
    """Maximum decompressed payload size in bytes accepted for a single incoming
    data stream; oversized streams terminate with StreamError on the receiver.
    When None, uses the FFI default."""

DataStreamOptions(max_payload_byte_length: 'int | None' = None)

Instance variables

var max_payload_byte_length : int | None

Maximum decompressed payload size in bytes accepted for a single incoming data stream; oversized streams terminate with StreamError on the receiver. When None, uses the FFI default.

class Room (loop: Optional[asyncio.AbstractEventLoop] = None)
Expand source code
class Room(EventEmitter[EventTypes]):
    def __init__(
        self,
        loop: Optional[asyncio.AbstractEventLoop] = None,
    ) -> None:
        """Initializes a new Room instance.

        Parameters:
            loop (Optional[asyncio.AbstractEventLoop]): The event loop to use. If not provided, the default event loop is used.
        """
        super().__init__()

        self._ffi_handle: Optional[FfiHandle] = None
        self._loop = loop or asyncio.get_event_loop()
        self._room_queue = BroadcastQueue[proto_ffi.FfiEvent]()
        self._info = proto_room.RoomInfo()
        self._rpc_invocation_tasks: set[asyncio.Task] = set()

        self._remote_participants: Dict[str, RemoteParticipant] = {}
        self._connection_state = ConnectionState.CONN_DISCONNECTED
        self._first_sid_future = asyncio.Future[str]()
        self._local_participant: LocalParticipant | None = None
        self._is_connecting: bool = False

        # active incoming stream readers, keyed by FFI reader handle id
        self._text_stream_readers: Dict[int, TextStreamReader] = {}
        self._byte_stream_readers: Dict[int, ByteStreamReader] = {}
        self._text_stream_handlers: Dict[str, TextStreamHandler] = {}
        self._byte_stream_handlers: Dict[str, ByteStreamHandler] = {}

        self._token: str | None = None
        self._server_url: str | None = None

    def __del__(self) -> None:
        if self._ffi_handle is not None:
            FfiClient.instance.queue.unsubscribe(self._ffi_queue)

    @property
    async def sid(self) -> str:
        """Asynchronously retrieves the session ID (SID) of the room.

        Returns:
            str: The session ID of the room.

        Raises:
            RuntimeError: If the room is disconnected and no SID was received.
        """
        if self._info.sid:
            return self._info.sid

        if self._connection_state == ConnectionState.CONN_DISCONNECTED and not self._is_connecting:
            raise RuntimeError("cannot get sid of a disconnected room")

        # This future is shared state for the Room. Caller-side timeouts, e.g.
        # asyncio.wait_for(room.sid, ...), should not cancel it for future waiters.
        return await asyncio.shield(self._first_sid_future)

    def _resolve_first_sid(self, sid: str) -> None:
        # The room SID can arrive through the initial connect result or later
        # room update events. Resolve the first-SID waiter from any source that
        # carries it so waiters do not depend on event ordering.
        if sid:
            self._info.sid = sid
            if not self._first_sid_future.done():
                self._first_sid_future.set_result(sid)

    def _fail_first_sid(self, exc: BaseException) -> None:
        if not self._first_sid_future.done():
            self._first_sid_future.set_exception(exc)
            # Retrieve the exception to suppress unretrieved future warnings if unawaited
            self._first_sid_future.exception()

    @property
    def local_participant(self) -> LocalParticipant:
        """Gets the local participant in the room.

        Returns:
            LocalParticipant: The local participant in the room.
        """
        if self._local_participant is None:
            raise Exception("cannot access local participant before connecting")

        return self._local_participant

    @property
    def connection_state(self) -> ConnectionState.ValueType:
        """Gets the connection state of the room.

        Returns:
            ConnectionState: The connection state of the room.
        """
        return self._connection_state

    @property
    def remote_participants(self) -> Mapping[str, RemoteParticipant]:
        """Gets the remote participants in the room.

        Returns:
            dict[str, RemoteParticipant]: A dictionary of remote participants indexed by their
            identity.
        """
        return self._remote_participants

    @property
    def name(self) -> str:
        """Gets the name of the room.

        Returns:
            str: The name of the room.
        """
        return self._info.name

    @property
    def metadata(self) -> str:
        """Gets the metadata associated with the room.

        Returns:
            str: The metadata of the room.
        """
        return self._info.metadata

    @property
    def e2ee_manager(self) -> E2EEManager:
        """Gets the end-to-end encryption (E2EE) manager for the room.

        Returns:
            E2EEManager: The E2EE manager instance.
        """
        return self._e2ee_manager

    @property
    def num_participants(self) -> int:
        """Gets the number of participants in the room.
        This value is updated periodically, and is eventually consistent.

        Returns:
            int: The number of participants in the room.
        """
        return self._info.num_participants

    @property
    def num_publishers(self) -> int:
        """Gets the number of publishers in the room.
        This value is updated periodically, and is eventually consistent.

        Returns:
            int: The number of publishers in the room.
        """
        return self._info.num_publishers

    @property
    def creation_time(self) -> datetime.datetime:
        """Time when the room was created.

        Returns:
            datetime.datetime: The creation time of the room.
        """
        return datetime.datetime.fromtimestamp(
            self._info.creation_time / 1000, datetime.timezone.utc
        )

    @property
    def is_recording(self) -> bool:
        """Whether the room is actively recording.

        Returns:
            bool: True if actively recording, False otherwise.
        """
        return self._info.active_recording

    @property
    def departure_timeout(self) -> float:
        """Amount of time to hold the room open after the last standard participant leaves.

        Returns:
            float: The departure timeout of the room.
        """
        return float(self._info.departure_timeout)

    @property
    def empty_timeout(self) -> float:
        """Amount of time to keep the room open if no participants join.

        Returns:
            float: The empty timeout of the room.
        """
        return float(self._info.empty_timeout)

    def isconnected(self) -> bool:
        """Checks if the room is currently connected.

        Returns:
            bool: True if connected, False otherwise.
        """
        return (
            self._ffi_handle is not None
            and self._connection_state != ConnectionState.CONN_DISCONNECTED
        )

    def on(self, event: EventTypes, callback: Optional[Callable] = None) -> Callable:
        """Registers an event handler for a specific event type.

        Parameters:
            event (EventTypes): The name of the event to listen for.
            callback (Callable): The function to call when the event occurs.

        Returns:
            Callable: The registered callback function.

        Available events:
            - **"participant_connected"**: Called when a new participant joins the room.
                - Arguments: `participant` (RemoteParticipant)
            - **"participant_disconnected"**: Called when a participant leaves the room.
                - Arguments: `participant` (RemoteParticipant)
            - **"participant_active"**: Called when a remote participant becomes active and is ready to receive data messages.
                - Arguments: `participant` (RemoteParticipant)
            - **"local_track_published"**: Called when a local track is published.
                - Arguments: `publication` (LocalTrackPublication), `track` (Track)
            - **"local_track_unpublished"**: Called when a local track is unpublished.
                - Arguments: `publication` (LocalTrackPublication)
            - **"local_track_republished"**: Called when the SDK auto-republished a local
                track during a full reconnect. The publication object is updated in place
                with the new server-assigned SIDs (its previous SID is passed alongside so
                callers can reconcile any external state keyed by the old SID).
                - Arguments: `publication` (LocalTrackPublication), `previous_sid` (str)
            - **"local_track_subscribed"**: Called when a local track is subscribed.
                - Arguments: `track` (Track)
            - **"track_published"**: Called when a remote participant publishes a track.
                - Arguments: `publication` (RemoteTrackPublication), `participant` (RemoteParticipant)
            - **"track_unpublished"**: Called when a remote participant unpublishes a track.
                - Arguments: `publication` (RemoteTrackPublication), `participant` (RemoteParticipant)
            - **"track_subscribed"**: Called when a track is subscribed.
                - Arguments: `track` (Track), `publication` (RemoteTrackPublication), `participant` (RemoteParticipant)
            - **"track_unsubscribed"**: Called when a track is unsubscribed.
                - Arguments: `track` (Track), `publication` (RemoteTrackPublication), `participant` (RemoteParticipant)
            - **"track_subscription_failed"**: Called when a track subscription fails.
                - Arguments: `participant` (RemoteParticipant), `track_sid` (str), `error` (str)
            - **"track_muted"**: Called when a track is muted.
                - Arguments: `participant` (Participant), `publication` (TrackPublication)
            - **"track_unmuted"**: Called when a track is unmuted.
                - Arguments: `participant` (Participant), `publication` (TrackPublication)
            - **"active_speakers_changed"**: Called when the list of active speakers changes.
                - Arguments: `speakers` (list[Participant])
            - **"room_metadata_changed"**: Called when the room's metadata is updated.
                - Arguments: `old_metadata` (str), `new_metadata` (str)
            - **"participant_metadata_changed"**: Called when a participant's metadata is updated.
                - Arguments: `participant` (Participant), `old_metadata` (str), `new_metadata` (str)
            - **"participant_name_changed"**: Called when a participant's name is changed.
                - Arguments: `participant` (Participant), `old_name` (str), `new_name` (str)
            - **"participant_attributes_changed"**: Called when a participant's attributes change.
                - Arguments: `changed_attributes` (dict), `participant` (Participant)
            - **"participant_encryption_status_changed"**: Called when a participant's encryption status changes.
                - Arguments `is_encrypted` (bool), `participant` (Participant)
            - **"connection_quality_changed"**: Called when a participant's connection quality changes.
                - Arguments: `participant` (Participant), `quality` (ConnectionQuality)
            - **"transcription_received"**: Called when a transcription is received.
                - Arguments: `segments` (list[TranscriptionSegment]), `participant` (Participant), `publication` (TrackPublication)
            - **"data_received"**: Called when data is received.
                - Arguments: `data_packet` (DataPacket)
            - **"sip_dtmf_received"**: Called when a SIP DTMF signal is received.
                - Arguments: `sip_dtmf` (SipDTMF)
            - **"e2ee_state_changed"**: Called when a participant's E2EE state changes.
                - Arguments: `participant` (Participant), `state` (EncryptionState)
            - **"connection_state_changed"**: Called when the room's connection state changes.
                - Arguments: `connection_state` (ConnectionState)
            - **"connected"**: Called when the room is successfully connected.
                - Arguments: None
            - **"disconnected"**: Called when the room is disconnected.
                - Arguments: `reason` (DisconnectReason)
            - **"reconnecting"**: Called when the room is attempting to reconnect.
                - Arguments: None
            - **"reconnected"**: Called when the room has successfully reconnected.
                - Arguments: None
            - **"room_updated"**: Called when any information about the room is updated.
                - Arguments: None
            - **"moved"**: Called when the participant has been moved to another room.
                - Arguments: None
            - **"data_track_published"**: Called when a remote participant publishes a data track.
                - Arguments: `track` (RemoteDataTrack)
            - **"data_track_unpublished"**: Called when a remote participant unpublishes a data track.
                - Arguments: `sid` (str)

        Example:
            ```python
            def on_participant_connected(participant):
                print(f"Participant connected: {participant.identity}")

            room.on("participant_connected", on_participant_connected)
            ```
        """
        return super().on(event, callback)

    async def connect(self, url: str, token: str, options: RoomOptions = RoomOptions()) -> None:
        """Connects to a LiveKit room using the specified URL and token.

        Parameters:
            url (str): The WebSocket URL of the LiveKit server to connect to.
            token (str): The access token for authentication and authorization.
            options (RoomOptions, optional): Additional options for the room connection.

        Raises:
            ConnectError: If the connection fails.

        Example:
            ```python
            room = Room()

            # Listen for events before connecting to the room
            @room.on("participant_connected")
            def on_participant_connected(participant):
                print(f"Participant connected: {participant.identity}")

            await room.connect("ws://localhost:7880", "your_token")
            ```
        """
        self._server_url = url
        self._token = token
        self._is_connecting = True
        if self._first_sid_future.done() and not self._info.sid:
            self._first_sid_future = asyncio.Future[str]()
        req = proto_ffi.FfiRequest()
        req.connect.url = url
        req.connect.token = token

        # options
        req.connect.options.auto_subscribe = options.auto_subscribe
        req.connect.options.dynacast = options.dynacast

        if (
            options.data_stream is not None
            and options.data_stream.max_payload_byte_length is not None
        ):
            req.connect.options.data_stream.max_payload_byte_length = (
                options.data_stream.max_payload_byte_length
            )

        if options.connect_timeout is not None:
            req.connect.options.connect_timeout_ms = int(options.connect_timeout * 1000)

        if options.single_peer_connection is not None:
            req.connect.options.single_peer_connection = options.single_peer_connection

        if options.e2ee:
            warnings.warn(
                "options.e2ee is deprecated, use options.encryption instead",
                DeprecationWarning,
                stacklevel=2,
            )

            req.connect.options.e2ee.encryption_type = options.e2ee.encryption_type
            if options.e2ee.key_provider_options.shared_key is not None:
                req.connect.options.e2ee.key_provider_options.shared_key = (
                    options.e2ee.key_provider_options.shared_key
                )
            req.connect.options.e2ee.key_provider_options.ratchet_salt = (
                options.e2ee.key_provider_options.ratchet_salt
            )
            req.connect.options.e2ee.key_provider_options.failure_tolerance = (
                options.e2ee.key_provider_options.failure_tolerance
            )
            req.connect.options.e2ee.key_provider_options.ratchet_window_size = (
                options.e2ee.key_provider_options.ratchet_window_size
            )
            req.connect.options.e2ee.key_provider_options.key_ring_size = (
                options.e2ee.key_provider_options.key_ring_size
            )
            req.connect.options.e2ee.key_provider_options.key_derivation_function = (
                options.e2ee.key_provider_options.key_derivation_function
            )

        if options.encryption:
            req.connect.options.encryption.encryption_type = options.encryption.encryption_type
            if options.encryption.key_provider_options.shared_key is not None:
                req.connect.options.encryption.key_provider_options.shared_key = (
                    options.encryption.key_provider_options.shared_key
                )
            req.connect.options.encryption.key_provider_options.ratchet_salt = (
                options.encryption.key_provider_options.ratchet_salt
            )
            req.connect.options.encryption.key_provider_options.failure_tolerance = (
                options.encryption.key_provider_options.failure_tolerance
            )
            req.connect.options.encryption.key_provider_options.ratchet_window_size = (
                options.encryption.key_provider_options.ratchet_window_size
            )
            req.connect.options.encryption.key_provider_options.key_ring_size = (
                options.encryption.key_provider_options.key_ring_size
            )
            req.connect.options.encryption.key_provider_options.key_derivation_function = (
                options.encryption.key_provider_options.key_derivation_function
            )

        if options.rtc_config:
            req.connect.options.rtc_config.ice_transport_type = (
                options.rtc_config.ice_transport_type
            )
            req.connect.options.rtc_config.continual_gathering_policy = (
                options.rtc_config.continual_gathering_policy
            )
            req.connect.options.rtc_config.ice_servers.extend(options.rtc_config.ice_servers)

        # subscribe before connecting so we don't miss any events
        # Media streams have their own subscriptions. Keep other events, including
        # the publish/unpublish callbacks forwarded through _room_queue.
        self._ffi_queue = FfiClient.instance.queue.subscribe(
            self._loop,
            filter_fn=lambda e: (
                e.WhichOneof("message") not in ("audio_stream_event", "video_stream_event")
            ),
        )

        try:
            queue = FfiClient.instance.queue.subscribe()
            try:
                resp = FfiClient.instance.request(req)
                cb: proto_ffi.FfiEvent = await queue.wait_for(
                    lambda e: e.connect.async_id == resp.connect.async_id
                )
            finally:
                FfiClient.instance.queue.unsubscribe(queue)

            if cb.connect.error:
                FfiClient.instance.queue.unsubscribe(self._ffi_queue)
                raise ConnectError(cb.connect.error)

            self._ffi_handle = FfiHandle(cb.connect.result.room.handle.id)

            self._e2ee_manager = E2EEManager(
                self._ffi_handle.handle, options.encryption or options.e2ee
            )

            self._info = cb.connect.result.room.info
            self._resolve_first_sid(self._info.sid)
            self._connection_state = ConnectionState.CONN_CONNECTED

            self._local_participant = LocalParticipant(
                self._room_queue, cb.connect.result.local_participant
            )

            for pt in cb.connect.result.participants:
                rp = self._create_remote_participant(pt.participant)

                # add the initial remote participant tracks
                for owned_publication_info in pt.publications:
                    publication = RemoteTrackPublication(owned_publication_info)
                    rp._track_publications[publication.sid] = publication

            # start listening to room events
            self._task = self._loop.create_task(self._listen_task())
        except BaseException as e:
            if self._ffi_handle is None and hasattr(self, "_ffi_queue"):
                FfiClient.instance.queue.unsubscribe(self._ffi_queue)
            self._fail_first_sid(
                RuntimeError("room connection was cancelled")
                if isinstance(e, asyncio.CancelledError)
                else e
            )
            raise
        finally:
            self._is_connecting = False

        # unsubscribe from the FFI queue once the listen task ends.
        # disconnect() unsubscribes too, but it early-returns when the
        # room is already disconnected (e.g. removed remotely).
        ffi_queue = self._ffi_queue
        self._task.add_done_callback(lambda _: FfiClient.instance.queue.unsubscribe(ffi_queue))

        # Unblock the FFI server once this SDK is ready to receive room events.
        ready_req = proto_ffi.FfiRequest()
        ready_req.ready_for_room_event.room_handle = self._ffi_handle.handle
        FfiClient.instance.request(ready_req)

    async def get_rtc_stats(self) -> RtcStats:
        if not self.isconnected():
            raise RuntimeError("the room isn't connected")

        req = proto_ffi.FfiRequest()
        req.get_session_stats.room_handle = self._ffi_handle.handle  # type: ignore

        queue = FfiClient.instance.queue.subscribe()
        try:
            resp = FfiClient.instance.request(req)
            cb: proto_ffi.FfiEvent = await queue.wait_for(
                lambda e: e.get_session_stats.async_id == resp.get_session_stats.async_id
            )
        finally:
            FfiClient.instance.queue.unsubscribe(queue)

        if cb.get_session_stats.error:
            raise RuntimeError(cb.get_session_stats.error)

        publisher_stats = list(cb.get_session_stats.result.publisher_stats)
        subscriber_stats = list(cb.get_session_stats.result.subscriber_stats)

        return RtcStats(publisher_stats=publisher_stats, subscriber_stats=subscriber_stats)

    def register_byte_stream_handler(self, topic: str, handler: ByteStreamHandler) -> None:
        existing_handler = self._byte_stream_handlers.get(topic)
        if existing_handler is None:
            self._byte_stream_handlers[topic] = handler
        else:
            raise ValueError("byte stream handler for topic '%s' already set" % topic)

    def unregister_byte_stream_handler(self, topic: str) -> None:
        if self._byte_stream_handlers.get(topic):
            self._byte_stream_handlers.pop(topic)

    def register_text_stream_handler(self, topic: str, handler: TextStreamHandler) -> None:
        existing_handler = self._text_stream_handlers.get(topic)
        if existing_handler is None:
            self._text_stream_handlers[topic] = handler
        else:
            raise ValueError("text stream handler for topic '%s' already set" % topic)

    def unregister_text_stream_handler(self, topic: str) -> None:
        if self._text_stream_handlers.get(topic):
            self._text_stream_handlers.pop(topic)

    async def simulate_scenario(self, scenario: SimulateScenarioKind.ValueType) -> None:
        """Trigger a reconnection / chaos scenario for testing.

        See `SimulateScenarioKind` for the available variants. Most useful
        in tests to deterministically force a Resume (signal-only reconnect
        that preserves the PeerConnection and existing publications) or a
        full reconnect (the SDK rebuilds the RtcSession and re-publishes
        existing local tracks).

        Raises a `RuntimeError` if the SDK reports a failure.
        """
        if not self.isconnected() or self._ffi_handle is None:
            raise RuntimeError("simulate_scenario requires a connected room")

        req = proto_ffi.FfiRequest()
        req.simulate_scenario.room_handle = self._ffi_handle.handle
        req.simulate_scenario.scenario = scenario
        queue = FfiClient.instance.queue.subscribe()
        try:
            resp = FfiClient.instance.request(req)
            cb = await queue.wait_for(
                lambda e: e.simulate_scenario.async_id == resp.simulate_scenario.async_id
            )
        finally:
            FfiClient.instance.queue.unsubscribe(queue)

        if cb.simulate_scenario.HasField("error") and cb.simulate_scenario.error:
            raise RuntimeError(f"simulate_scenario failed: {cb.simulate_scenario.error}")

    async def disconnect(
        self, *, reason: DisconnectReason.ValueType = DisconnectReason.CLIENT_INITIATED
    ) -> None:
        """Disconnects from the room."""
        if not self.isconnected():
            return

        await self._drain_rpc_invocation_tasks()
        self._error_stream_readers()
        self._dispose_open_stream_writers()

        req = proto_ffi.FfiRequest()
        req.disconnect.room_handle = self._ffi_handle.handle  # type: ignore
        req.disconnect.reason = reason
        queue = FfiClient.instance.queue.subscribe()
        try:
            resp = FfiClient.instance.request(req)
            await queue.wait_for(lambda e: e.disconnect.async_id == resp.disconnect.async_id)
        finally:
            FfiClient.instance.queue.unsubscribe(queue)

        await self._task
        FfiClient.instance.queue.unsubscribe(self._ffi_queue)

        # we should manually flip the state, since the connection could have been torn down before
        # the callbacks were processed
        if self._connection_state != ConnectionState.CONN_DISCONNECTED:
            self.local_participant._info.disconnect_reason = reason
            self._connection_state = ConnectionState.CONN_DISCONNECTED
            self._fail_first_sid(RuntimeError("room disconnected before receiving sid"))
            self.emit("connection_state_changed", self._connection_state)
            self.emit("disconnected", reason)

    async def _listen_task(self) -> None:
        # listen to incoming room events
        while True:
            event = await self._ffi_queue.get()
            if event.WhichOneof("message") == "rpc_method_invocation":
                self._on_rpc_method_invocation(event.rpc_method_invocation)
            elif event.room_event.room_handle == self._ffi_handle.handle:  # type: ignore
                if event.room_event.HasField("eos"):
                    break

                try:
                    self._on_room_event(event.room_event)
                except Exception:
                    logging.exception(
                        "error running user callback for %s: %s",
                        event.room_event.WhichOneof("message"),
                        event.room_event,
                    )

            # wait for the subscribers to process the event
            # before processing the next one
            self._room_queue.put_nowait(event)
            await self._room_queue.join()

        # Clean up any pending RPC invocation tasks
        await self._drain_rpc_invocation_tasks()
        self._error_stream_readers()
        self._dispose_open_stream_writers()
        self._fail_first_sid(RuntimeError("room disconnected before receiving sid"))

    def _on_rpc_method_invocation(self, rpc_invocation: RpcMethodInvocationEvent) -> None:
        if self._local_participant is None:
            return

        if rpc_invocation.local_participant_handle == self._local_participant._ffi_handle.handle:
            task = self._loop.create_task(
                self._local_participant._handle_rpc_method_invocation(
                    rpc_invocation.invocation_id,
                    rpc_invocation.method,
                    rpc_invocation.request_id,
                    rpc_invocation.caller_identity,
                    rpc_invocation.payload,
                    rpc_invocation.response_timeout_ms / 1000.0,
                )
            )
            self._rpc_invocation_tasks.add(task)
            task.add_done_callback(self._rpc_invocation_tasks.discard)

    def _on_room_event(self, event: proto_room.RoomEvent) -> None:
        which = event.WhichOneof("message")
        if which == "participant_connected":
            rparticipant = self._create_remote_participant(event.participant_connected.info)
            self.emit("participant_connected", rparticipant)
        elif which == "participant_disconnected":
            identity = event.participant_disconnected.participant_identity
            rparticipant = self._remote_participants.pop(identity)
            rparticipant._info.disconnect_reason = event.participant_disconnected.disconnect_reason
            self.emit("participant_disconnected", rparticipant)
        elif which == "participant_active":
            rp = self._retrieve_remote_participant(event.participant_active.participant_identity)
            if rp:
                rp._info.state = proto_participant.PARTICIPANT_STATE_ACTIVE
                self.emit("participant_active", rp)
        elif which == "local_track_published":
            sid = event.local_track_published.track_sid
            lpublication = self.local_participant.track_publications[sid]
            ltrack = lpublication.track
            if ltrack is not None:
                ltrack._set_room(self)
            self.emit("local_track_published", lpublication, ltrack)
        elif which == "local_track_unpublished":
            # During teardown the publication may already have been removed
            # from the participant's dict by LocalParticipant.unpublish_track
            # (the FFI event races that async response), so the SID can be gone
            # by the time this event is dispatched. Look it up defensively and
            # skip the emit when it is no longer tracked, mirroring the
            # local_track_republished and remote track_unpublished handlers,
            # instead of raising a KeyError that _listen_task logs as an error.
            sid = event.local_track_unpublished.publication_sid
            unpublished = self.local_participant._track_publications.get(sid)
            if unpublished is not None:
                del self.local_participant._track_publications[sid]
                track = unpublished.track
                if track is not None:
                    track._set_room(None)
                # Emit while `publication.track` is still set, preserving the
                # pre-existing payload for callbacks. This handler is synchronous
                # and emit() invokes listeners synchronously, so nulling the track
                # right after still completes before any other coroutine (e.g.
                # unpublish_track) can interleave.
                self.emit("local_track_unpublished", unpublished)
                # Mirror track_unsubscribed: drop the publication's track
                # reference. This also makes unpublish_track's own _set_room(None)
                # a no-op when it loses the race (its `publication._track is not
                # None` guard short-circuits), avoiding a redundant clear.
                if track is not None:
                    unpublished._track = None
            else:
                logging.debug("local_track_unpublished for untracked publication sid %s", sid)
        elif which == "local_track_republished":
            # The SDK auto-republished a local track during a full
            # reconnect: the underlying Track (and its bound source) is
            # preserved, but the publication and track SIDs were re-issued
            # by the server. Update the existing LocalTrackPublication
            # object in place so application code holding a cached
            # reference continues to see current state, then rekey it
            # under the new SID in the participant's publications dict.
            previous_sid = event.local_track_republished.previous_sid
            republished = self.local_participant._track_publications.get(previous_sid)
            if republished is not None:
                del self.local_participant._track_publications[previous_sid]
                republished._info = event.local_track_republished.info
                self.local_participant._track_publications[republished.sid] = republished
                if republished.track is not None:
                    # Keep the local-track invariant (track.sid == publication.sid,
                    # set at publish_track) intact across republish, then re-push
                    # metadata so any attached FrameProcessor learns the new
                    # publication SID / credentials. _set_room with the same room
                    # is a no-op for the token_refreshed listener but re-fans the
                    # metadata to every registered AudioStream.
                    republished.track._info.sid = republished.sid
                    republished.track._set_room(self)
                self.emit("local_track_republished", republished, previous_sid)
        elif which == "local_track_subscribed":
            sid = event.local_track_subscribed.track_sid
            lpublication = self.local_participant.track_publications[sid]
            if not lpublication._first_subscription.done():
                lpublication._first_subscription.set_result(None)
            self.emit("local_track_subscribed", lpublication.track)
        elif which == "track_published":
            # The participant may already have been removed by a racing
            # disconnect or a duplicate event, so the lookup is done defensively
            # and the emit is skipped when the participant is gone, mirroring the
            # track_unpublished handler, instead of raising a KeyError that
            # _listen_task logs as an error.
            identity = event.track_published.participant_identity
            published_participant = self._remote_participants.get(identity)
            if published_participant is not None:
                published = RemoteTrackPublication(event.track_published.publication)
                published_participant._track_publications[published.sid] = published
                self.emit("track_published", published, published_participant)
            else:
                logger.debug("track_published for untracked participant %s", identity)
        elif which == "track_unpublished":
            # The participant or publication may already have been removed by a
            # racing disconnect or a duplicate event, so both lookups are done
            # defensively and the emit is skipped when the entry is gone,
            # mirroring the local_track_unpublished handler, instead of raising a
            # KeyError that _listen_task logs as an error.
            identity = event.track_unpublished.participant_identity
            sid = event.track_unpublished.publication_sid
            rp = self._remote_participants.get(identity)
            if rp is not None:
                rpub = rp._track_publications.pop(sid, None)
                if rpub is not None:
                    self.emit("track_unpublished", rpub, rp)
                else:
                    logger.debug("track_unpublished for untracked publication sid %s", sid)
            else:
                logger.debug("track_unpublished for untracked participant %s", identity)
        elif which == "track_subscribed":
            # The participant or publication may already have been removed by a
            # racing disconnect or unpublish, so both lookups are done
            # defensively and the emit is skipped when either entry is gone,
            # mirroring the track_unpublished handler, instead of raising a
            # KeyError that _listen_task logs as an error.
            owned_track_info = event.track_subscribed.track
            track_info = owned_track_info.info
            identity = event.track_subscribed.participant_identity
            subscribed_participant = self._remote_participants.get(identity)
            subscribed = (
                subscribed_participant.track_publications.get(track_info.sid)
                if subscribed_participant is not None
                else None
            )
            if subscribed_participant is not None and subscribed is not None:
                subscribed._subscribed = True
                if track_info.kind == TrackKind.KIND_VIDEO:
                    remote_video_track = RemoteVideoTrack(owned_track_info)
                    remote_video_track._set_room(self)
                    subscribed._track = remote_video_track
                    self.emit(
                        "track_subscribed", remote_video_track, subscribed, subscribed_participant
                    )
                elif track_info.kind == TrackKind.KIND_AUDIO:
                    remote_audio_track = RemoteAudioTrack(owned_track_info)
                    remote_audio_track._set_room(self)
                    subscribed._track = remote_audio_track
                    self.emit(
                        "track_subscribed", remote_audio_track, subscribed, subscribed_participant
                    )
            else:
                logger.debug(
                    "track_subscribed for untracked participant %s or publication %s",
                    identity,
                    track_info.sid,
                )
        elif which == "track_unsubscribed":
            # The participant or publication may already have been removed by a
            # racing disconnect or unpublish, so both lookups are done
            # defensively and the emit is skipped when either entry is gone,
            # mirroring the track_unpublished handler, instead of raising a
            # KeyError that _listen_task logs as an error.
            identity = event.track_unsubscribed.participant_identity
            unsubscribed_participant = self._remote_participants.get(identity)
            unsubscribed = (
                unsubscribed_participant.track_publications.get(event.track_unsubscribed.track_sid)
                if unsubscribed_participant is not None
                else None
            )
            if unsubscribed_participant is not None and unsubscribed is not None:
                rtrack = unsubscribed.track
                if rtrack is not None:
                    rtrack._set_room(None)
                unsubscribed._track = None
                unsubscribed._subscribed = False
                self.emit("track_unsubscribed", rtrack, unsubscribed, unsubscribed_participant)
            else:
                logger.debug(
                    "track_unsubscribed for untracked participant %s or publication %s",
                    identity,
                    event.track_unsubscribed.track_sid,
                )
        elif which == "track_subscription_failed":
            # The participant may already have been removed by a racing
            # disconnect, so the lookup is done defensively and the emit is
            # skipped when the participant is gone, instead of raising a KeyError
            # that _listen_task logs as an error.
            identity = event.track_subscription_failed.participant_identity
            failed_participant = self._remote_participants.get(identity)
            if failed_participant is not None:
                error = event.track_subscription_failed.error
                self.emit(
                    "track_subscription_failed",
                    failed_participant,
                    event.track_subscription_failed.track_sid,
                    error,
                )
            else:
                logger.debug("track_subscription_failed for untracked participant %s", identity)
        elif which == "track_muted":
            identity = event.track_muted.participant_identity
            # TODO: pass participant identity
            participant = self._retrieve_participant(identity)
            assert isinstance(participant, Participant)
            publication = participant.track_publications[event.track_muted.track_sid]
            publication._info.muted = True
            if publication.track:
                publication.track._info.muted = True

            self.emit("track_muted", participant, publication)
        elif which == "track_unmuted":
            identity = event.track_unmuted.participant_identity
            # TODO: pass participant identity
            participant = self._retrieve_participant(identity)
            assert isinstance(participant, Participant)
            publication = participant.track_publications[event.track_unmuted.track_sid]
            publication._info.muted = False
            if publication.track:
                publication.track._info.muted = False

            self.emit("track_unmuted", participant, publication)
        elif which == "active_speakers_changed":
            speakers: list[Participant] = []
            # TODO: pass participant identity
            for identity in event.active_speakers_changed.participant_identities:
                participant = self._retrieve_participant(identity)
                assert isinstance(participant, Participant)
                speakers.append(participant)

            self.emit("active_speakers_changed", speakers)
        elif which == "room_metadata_changed":
            old_metadata = self.metadata
            self._info.metadata = event.room_metadata_changed.metadata
            self.emit("room_metadata_changed", old_metadata, self.metadata)
        elif which == "room_sid_changed":
            self._resolve_first_sid(event.room_sid_changed.sid)
            self._info.sid = event.room_sid_changed.sid
            # This is an internal event, not exposed to users
        elif which == "participant_metadata_changed":
            identity = event.participant_metadata_changed.participant_identity
            # TODO: pass participant identity
            participant = self._retrieve_participant(identity)
            assert isinstance(participant, Participant)
            old_metadata = participant.metadata
            participant._info.metadata = event.participant_metadata_changed.metadata
            self.emit(
                "participant_metadata_changed",
                participant,
                old_metadata,
                participant.metadata,
            )
        elif which == "participant_name_changed":
            identity = event.participant_name_changed.participant_identity
            participant = self._retrieve_participant(identity)
            assert isinstance(participant, Participant)
            old_name = participant.name
            participant._info.name = event.participant_name_changed.name
            self.emit("participant_name_changed", participant, old_name, participant.name)
        elif which == "participant_attributes_changed":
            identity = event.participant_attributes_changed.participant_identity
            attributes = event.participant_attributes_changed.attributes
            changed_attributes = dict(
                (entry.key, entry.value)
                for entry in event.participant_attributes_changed.changed_attributes
            )
            participant = self._retrieve_participant(identity)
            assert isinstance(participant, Participant)
            participant._info.attributes.clear()
            participant._info.attributes.update((entry.key, entry.value) for entry in attributes)
            self.emit(
                "participant_attributes_changed",
                changed_attributes,
                participant,
            )
        elif which == "participant_encryption_status_changed":
            identity = event.participant_encryption_status_changed.participant_identity
            participant = self._retrieve_participant(identity)
            self.emit(
                "participant_encryption_status_changed",
                participant,
                event.participant_encryption_status_changed.is_encrypted,
            )
        elif which == "participant_permission_changed":
            identity = event.participant_permission_changed.participant_identity
            participant = self._retrieve_participant(identity)
            assert isinstance(participant, Participant)
            participant._info.permission.CopyFrom(event.participant_permission_changed.permission)
            self.emit(
                "participant_permissions_changed",
                participant,
                participant.permissions,
            )
        elif which == "connection_quality_changed":
            identity = event.connection_quality_changed.participant_identity
            participant = self._retrieve_participant(identity)
            quality = _connection_quality_from_proto(event.connection_quality_changed.quality)
            if participant:
                participant._connection_quality = quality
            self.emit(
                "connection_quality_changed",
                participant,
                quality,
            )
        elif which == "transcription_received":
            transcription = event.transcription_received
            segments = [
                TranscriptionSegment(
                    id=s.id,
                    text=s.text,
                    final=s.final,
                    start_time=s.start_time,
                    end_time=s.end_time,
                    language=s.language,
                )
                for s in transcription.segments
            ]
            part = self._retrieve_participant(transcription.participant_identity)
            pub: TrackPublication | None = None
            if part:
                pub = part.track_publications.get(transcription.track_sid)
            self.emit("transcription_received", segments, part, pub)
        elif which == "data_packet_received":
            packet = event.data_packet_received
            which_val = packet.WhichOneof("value")
            if which_val == "user":
                owned_buffer_info = packet.user.data
                buffer_info = owned_buffer_info.data
                data = ctypes.string_at(buffer_info.data_ptr, buffer_info.data_len)
                FfiHandle(owned_buffer_info.handle.id).dispose()
                rparticipant = cast(
                    RemoteParticipant,
                    self._retrieve_remote_participant(packet.participant_identity),
                )
                self.emit(
                    "data_received",
                    DataPacket(
                        data=data,
                        kind=packet.kind,
                        participant=rparticipant,
                        topic=packet.user.topic,
                    ),
                )
            elif which_val == "sip_dtmf":
                rparticipant = cast(
                    RemoteParticipant,
                    self._retrieve_remote_participant(packet.participant_identity),
                )
                self.emit(
                    "sip_dtmf_received",
                    SipDTMF(
                        code=packet.sip_dtmf.code,
                        digit=packet.sip_dtmf.digit,
                        participant=rparticipant,
                    ),
                )
        elif which == "e2ee_state_changed":
            identity = event.e2ee_state_changed.participant_identity
            e2ee_state = event.e2ee_state_changed.state
            # TODO: pass participant identity
            self.emit("e2ee_state_changed", self._retrieve_participant(identity), e2ee_state)
        elif which == "connection_state_changed":
            connection_state = event.connection_state_changed.state
            self._connection_state = connection_state
            self.emit("connection_state_changed", connection_state)
        elif which == "disconnected":
            self._fail_first_sid(RuntimeError("room disconnected before receiving sid"))
            self.emit("disconnected", event.disconnected.reason)
        elif which == "reconnecting":
            self.emit("reconnecting")
        elif which == "reconnected":
            self.emit("reconnected")
        elif which == "text_stream_opened":
            self._handle_text_stream_opened(event.text_stream_opened)
        elif which == "byte_stream_opened":
            self._handle_byte_stream_opened(event.byte_stream_opened)
        elif which == "room_updated":
            self._info = event.room_updated
            self._resolve_first_sid(self._info.sid)
            self.emit("room_updated")

        elif which == "moved":
            self._info = event.moved
            self._resolve_first_sid(self._info.sid)
            self.emit("moved")

        elif which == "participants_updated":
            for info in event.participants_updated.participants:
                participant = self._retrieve_participant(info.identity)
                if participant:
                    participant._info = info

        elif which == "token_refreshed":
            self._token = event.token_refreshed.token
            self.emit("token_refreshed")

        elif which == "data_track_published":
            remote_data_track = RemoteDataTrack(event.data_track_published.track)
            self.emit("data_track_published", remote_data_track)

        elif which == "data_track_unpublished":
            self.emit("data_track_unpublished", event.data_track_unpublished.sid)

    def _handle_text_stream_opened(self, opened: proto_room.TextStreamOpened) -> None:
        topic = opened.reader.info.topic
        text_stream_handler = self._text_stream_handlers.get(topic)
        handle_id = opened.reader.handle.id
        if text_stream_handler is None:
            logging.info(
                "ignoring text stream with topic '%s', no callback attached",
                topic,
            )
            # the reader is never consumed by read_incremental, so the owned
            # handle (and its buffered chunks) must be disposed here
            FfiHandle(handle_id).dispose()
            return

        def on_close() -> None:
            self._text_stream_readers.pop(handle_id, None)

        text_reader = TextStreamReader(opened.reader, on_close=on_close)
        self._text_stream_readers[handle_id] = text_reader
        text_stream_handler(text_reader, opened.participant_identity)

    def _handle_byte_stream_opened(self, opened: proto_room.ByteStreamOpened) -> None:
        topic = opened.reader.info.topic
        byte_stream_handler = self._byte_stream_handlers.get(topic)
        handle_id = opened.reader.handle.id
        if byte_stream_handler is None:
            logging.info(
                "ignoring byte stream with topic '%s', no callback attached",
                topic,
            )
            # the reader is never consumed by read_incremental, so the owned
            # handle (and its buffered chunks) must be disposed here
            FfiHandle(handle_id).dispose()
            return

        def on_close() -> None:
            self._byte_stream_readers.pop(handle_id, None)

        byte_reader = ByteStreamReader(opened.reader, on_close=on_close)
        self._byte_stream_readers[handle_id] = byte_reader
        byte_stream_handler(byte_reader, opened.participant_identity)

    def _dispose_open_stream_writers(self) -> None:
        """Drops the native writers of data streams left open at disconnect.

        A writer releases its handle only when it is closed, so one the
        application abandoned — or left behind after a failed write — would
        otherwise be held by the FFI server for the life of the process.
        """
        if self._local_participant is not None:
            self._local_participant._dispose_open_stream_writers()

    def _error_stream_readers(self) -> None:
        """Wakes up any pending stream reads with a StreamError on disconnect.

        This also drops each reader's FFI queue subscription, which would
        otherwise outlive the room: a reader unsubscribes itself only once a
        read consumes its end-of-stream event, so one the application never
        finished reading would stay subscribed for the life of the process.
        The readers stay open, so a read can still drain whatever arrived
        before the disconnect and then raise StreamError.
        """
        for text_reader in list(self._text_stream_readers.values()):
            text_reader._signal_disconnect()
        for byte_reader in list(self._byte_stream_readers.values()):
            byte_reader._signal_disconnect()
        self._text_stream_readers.clear()
        self._byte_stream_readers.clear()

    async def _drain_rpc_invocation_tasks(self) -> None:
        if self._rpc_invocation_tasks:
            for task in self._rpc_invocation_tasks:
                task.cancel()
            await asyncio.gather(*self._rpc_invocation_tasks, return_exceptions=True)

    def _retrieve_remote_participant(self, identity: str) -> Optional[RemoteParticipant]:
        """Retrieve a remote participant by identity"""
        return self._remote_participants.get(identity, None)

    def _retrieve_participant(self, identity: str) -> Optional[Participant]:
        """Retrieve a local or remote participant by identity"""
        if (
            identity
            and self._local_participant is not None
            and identity == self._local_participant.identity
        ):
            return self._local_participant

        return self._retrieve_remote_participant(identity)

    def _create_remote_participant(
        self, owned_info: proto_participant.OwnedParticipant
    ) -> RemoteParticipant:
        if owned_info.info.identity in self._remote_participants:
            raise Exception("participant already exists")

        participant = RemoteParticipant(owned_info)
        self._remote_participants[participant.identity] = participant
        return participant

    def __repr__(self) -> str:
        sid = "unknown"
        if self._info.sid:
            sid = self._info.sid
        elif (
            self._first_sid_future.done()
            and not self._first_sid_future.cancelled()
            and self._first_sid_future.exception() is None
        ):
            sid = self._first_sid_future.result()

        return f"rtc.Room(sid={sid}, name={self.name}, metadata={self.metadata}, connection_state={ConnectionState.Name(self._connection_state)})"

Abstract base class for generic types.

On Python 3.12 and newer, generic classes implicitly inherit from Generic when they declare a parameter list after the class's name::

class Mapping[KT, VT]:
    def __getitem__(self, key: KT) -> VT:
        ...
    # Etc.

On older versions of Python, however, generic classes have to explicitly inherit from Generic.

After a class has been declared to be generic, it can then be used as follows::

def lookup_name[KT, VT](mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
    try:
        return mapping[key]
    except KeyError:
        return default

Initializes a new Room instance.

Parameters

loop (Optional[asyncio.AbstractEventLoop]): The event loop to use. If not provided, the default event loop is used.

Ancestors

Instance variables

prop connection_state : ConnectionState.ValueType
Expand source code
@property
def connection_state(self) -> ConnectionState.ValueType:
    """Gets the connection state of the room.

    Returns:
        ConnectionState: The connection state of the room.
    """
    return self._connection_state

Gets the connection state of the room.

Returns

ConnectionState
The connection state of the room.
prop creation_time : datetime.datetime
Expand source code
@property
def creation_time(self) -> datetime.datetime:
    """Time when the room was created.

    Returns:
        datetime.datetime: The creation time of the room.
    """
    return datetime.datetime.fromtimestamp(
        self._info.creation_time / 1000, datetime.timezone.utc
    )

Time when the room was created.

Returns

datetime.datetime
The creation time of the room.
prop departure_timeout : float
Expand source code
@property
def departure_timeout(self) -> float:
    """Amount of time to hold the room open after the last standard participant leaves.

    Returns:
        float: The departure timeout of the room.
    """
    return float(self._info.departure_timeout)

Amount of time to hold the room open after the last standard participant leaves.

Returns

float
The departure timeout of the room.
prop e2ee_manager : E2EEManager
Expand source code
@property
def e2ee_manager(self) -> E2EEManager:
    """Gets the end-to-end encryption (E2EE) manager for the room.

    Returns:
        E2EEManager: The E2EE manager instance.
    """
    return self._e2ee_manager

Gets the end-to-end encryption (E2EE) manager for the room.

Returns

E2EEManager
The E2EE manager instance.
prop empty_timeout : float
Expand source code
@property
def empty_timeout(self) -> float:
    """Amount of time to keep the room open if no participants join.

    Returns:
        float: The empty timeout of the room.
    """
    return float(self._info.empty_timeout)

Amount of time to keep the room open if no participants join.

Returns

float
The empty timeout of the room.
prop is_recording : bool
Expand source code
@property
def is_recording(self) -> bool:
    """Whether the room is actively recording.

    Returns:
        bool: True if actively recording, False otherwise.
    """
    return self._info.active_recording

Whether the room is actively recording.

Returns

bool
True if actively recording, False otherwise.
prop local_participant : LocalParticipant
Expand source code
@property
def local_participant(self) -> LocalParticipant:
    """Gets the local participant in the room.

    Returns:
        LocalParticipant: The local participant in the room.
    """
    if self._local_participant is None:
        raise Exception("cannot access local participant before connecting")

    return self._local_participant

Gets the local participant in the room.

Returns

LocalParticipant
The local participant in the room.
prop metadata : str
Expand source code
@property
def metadata(self) -> str:
    """Gets the metadata associated with the room.

    Returns:
        str: The metadata of the room.
    """
    return self._info.metadata

Gets the metadata associated with the room.

Returns

str
The metadata of the room.
prop name : str
Expand source code
@property
def name(self) -> str:
    """Gets the name of the room.

    Returns:
        str: The name of the room.
    """
    return self._info.name

Gets the name of the room.

Returns

str
The name of the room.
prop num_participants : int
Expand source code
@property
def num_participants(self) -> int:
    """Gets the number of participants in the room.
    This value is updated periodically, and is eventually consistent.

    Returns:
        int: The number of participants in the room.
    """
    return self._info.num_participants

Gets the number of participants in the room. This value is updated periodically, and is eventually consistent.

Returns

int
The number of participants in the room.
prop num_publishers : int
Expand source code
@property
def num_publishers(self) -> int:
    """Gets the number of publishers in the room.
    This value is updated periodically, and is eventually consistent.

    Returns:
        int: The number of publishers in the room.
    """
    return self._info.num_publishers

Gets the number of publishers in the room. This value is updated periodically, and is eventually consistent.

Returns

int
The number of publishers in the room.
prop remote_participants : Mapping[str, RemoteParticipant]
Expand source code
@property
def remote_participants(self) -> Mapping[str, RemoteParticipant]:
    """Gets the remote participants in the room.

    Returns:
        dict[str, RemoteParticipant]: A dictionary of remote participants indexed by their
        identity.
    """
    return self._remote_participants

Gets the remote participants in the room.

Returns

dict[str, RemoteParticipant]
A dictionary of remote participants indexed by their

identity.

prop sid : str
Expand source code
@property
async def sid(self) -> str:
    """Asynchronously retrieves the session ID (SID) of the room.

    Returns:
        str: The session ID of the room.

    Raises:
        RuntimeError: If the room is disconnected and no SID was received.
    """
    if self._info.sid:
        return self._info.sid

    if self._connection_state == ConnectionState.CONN_DISCONNECTED and not self._is_connecting:
        raise RuntimeError("cannot get sid of a disconnected room")

    # This future is shared state for the Room. Caller-side timeouts, e.g.
    # asyncio.wait_for(room.sid, ...), should not cancel it for future waiters.
    return await asyncio.shield(self._first_sid_future)

Asynchronously retrieves the session ID (SID) of the room.

Returns

str
The session ID of the room.

Raises

RuntimeError
If the room is disconnected and no SID was received.

Methods

async def connect(self,
url: str,
token: str,
options: RoomOptions = RoomOptions(auto_subscribe=True, dynacast=False, e2ee=None, encryption=None, rtc_config=None, connect_timeout=None, single_peer_connection=None, data_stream=None)) ‑> None
Expand source code
async def connect(self, url: str, token: str, options: RoomOptions = RoomOptions()) -> None:
    """Connects to a LiveKit room using the specified URL and token.

    Parameters:
        url (str): The WebSocket URL of the LiveKit server to connect to.
        token (str): The access token for authentication and authorization.
        options (RoomOptions, optional): Additional options for the room connection.

    Raises:
        ConnectError: If the connection fails.

    Example:
        ```python
        room = Room()

        # Listen for events before connecting to the room
        @room.on("participant_connected")
        def on_participant_connected(participant):
            print(f"Participant connected: {participant.identity}")

        await room.connect("ws://localhost:7880", "your_token")
        ```
    """
    self._server_url = url
    self._token = token
    self._is_connecting = True
    if self._first_sid_future.done() and not self._info.sid:
        self._first_sid_future = asyncio.Future[str]()
    req = proto_ffi.FfiRequest()
    req.connect.url = url
    req.connect.token = token

    # options
    req.connect.options.auto_subscribe = options.auto_subscribe
    req.connect.options.dynacast = options.dynacast

    if (
        options.data_stream is not None
        and options.data_stream.max_payload_byte_length is not None
    ):
        req.connect.options.data_stream.max_payload_byte_length = (
            options.data_stream.max_payload_byte_length
        )

    if options.connect_timeout is not None:
        req.connect.options.connect_timeout_ms = int(options.connect_timeout * 1000)

    if options.single_peer_connection is not None:
        req.connect.options.single_peer_connection = options.single_peer_connection

    if options.e2ee:
        warnings.warn(
            "options.e2ee is deprecated, use options.encryption instead",
            DeprecationWarning,
            stacklevel=2,
        )

        req.connect.options.e2ee.encryption_type = options.e2ee.encryption_type
        if options.e2ee.key_provider_options.shared_key is not None:
            req.connect.options.e2ee.key_provider_options.shared_key = (
                options.e2ee.key_provider_options.shared_key
            )
        req.connect.options.e2ee.key_provider_options.ratchet_salt = (
            options.e2ee.key_provider_options.ratchet_salt
        )
        req.connect.options.e2ee.key_provider_options.failure_tolerance = (
            options.e2ee.key_provider_options.failure_tolerance
        )
        req.connect.options.e2ee.key_provider_options.ratchet_window_size = (
            options.e2ee.key_provider_options.ratchet_window_size
        )
        req.connect.options.e2ee.key_provider_options.key_ring_size = (
            options.e2ee.key_provider_options.key_ring_size
        )
        req.connect.options.e2ee.key_provider_options.key_derivation_function = (
            options.e2ee.key_provider_options.key_derivation_function
        )

    if options.encryption:
        req.connect.options.encryption.encryption_type = options.encryption.encryption_type
        if options.encryption.key_provider_options.shared_key is not None:
            req.connect.options.encryption.key_provider_options.shared_key = (
                options.encryption.key_provider_options.shared_key
            )
        req.connect.options.encryption.key_provider_options.ratchet_salt = (
            options.encryption.key_provider_options.ratchet_salt
        )
        req.connect.options.encryption.key_provider_options.failure_tolerance = (
            options.encryption.key_provider_options.failure_tolerance
        )
        req.connect.options.encryption.key_provider_options.ratchet_window_size = (
            options.encryption.key_provider_options.ratchet_window_size
        )
        req.connect.options.encryption.key_provider_options.key_ring_size = (
            options.encryption.key_provider_options.key_ring_size
        )
        req.connect.options.encryption.key_provider_options.key_derivation_function = (
            options.encryption.key_provider_options.key_derivation_function
        )

    if options.rtc_config:
        req.connect.options.rtc_config.ice_transport_type = (
            options.rtc_config.ice_transport_type
        )
        req.connect.options.rtc_config.continual_gathering_policy = (
            options.rtc_config.continual_gathering_policy
        )
        req.connect.options.rtc_config.ice_servers.extend(options.rtc_config.ice_servers)

    # subscribe before connecting so we don't miss any events
    # Media streams have their own subscriptions. Keep other events, including
    # the publish/unpublish callbacks forwarded through _room_queue.
    self._ffi_queue = FfiClient.instance.queue.subscribe(
        self._loop,
        filter_fn=lambda e: (
            e.WhichOneof("message") not in ("audio_stream_event", "video_stream_event")
        ),
    )

    try:
        queue = FfiClient.instance.queue.subscribe()
        try:
            resp = FfiClient.instance.request(req)
            cb: proto_ffi.FfiEvent = await queue.wait_for(
                lambda e: e.connect.async_id == resp.connect.async_id
            )
        finally:
            FfiClient.instance.queue.unsubscribe(queue)

        if cb.connect.error:
            FfiClient.instance.queue.unsubscribe(self._ffi_queue)
            raise ConnectError(cb.connect.error)

        self._ffi_handle = FfiHandle(cb.connect.result.room.handle.id)

        self._e2ee_manager = E2EEManager(
            self._ffi_handle.handle, options.encryption or options.e2ee
        )

        self._info = cb.connect.result.room.info
        self._resolve_first_sid(self._info.sid)
        self._connection_state = ConnectionState.CONN_CONNECTED

        self._local_participant = LocalParticipant(
            self._room_queue, cb.connect.result.local_participant
        )

        for pt in cb.connect.result.participants:
            rp = self._create_remote_participant(pt.participant)

            # add the initial remote participant tracks
            for owned_publication_info in pt.publications:
                publication = RemoteTrackPublication(owned_publication_info)
                rp._track_publications[publication.sid] = publication

        # start listening to room events
        self._task = self._loop.create_task(self._listen_task())
    except BaseException as e:
        if self._ffi_handle is None and hasattr(self, "_ffi_queue"):
            FfiClient.instance.queue.unsubscribe(self._ffi_queue)
        self._fail_first_sid(
            RuntimeError("room connection was cancelled")
            if isinstance(e, asyncio.CancelledError)
            else e
        )
        raise
    finally:
        self._is_connecting = False

    # unsubscribe from the FFI queue once the listen task ends.
    # disconnect() unsubscribes too, but it early-returns when the
    # room is already disconnected (e.g. removed remotely).
    ffi_queue = self._ffi_queue
    self._task.add_done_callback(lambda _: FfiClient.instance.queue.unsubscribe(ffi_queue))

    # Unblock the FFI server once this SDK is ready to receive room events.
    ready_req = proto_ffi.FfiRequest()
    ready_req.ready_for_room_event.room_handle = self._ffi_handle.handle
    FfiClient.instance.request(ready_req)

Connects to a LiveKit room using the specified URL and token.

Parameters

url (str): The WebSocket URL of the LiveKit server to connect to. token (str): The access token for authentication and authorization. options (RoomOptions, optional): Additional options for the room connection.

Raises

ConnectError
If the connection fails.

Example

room = Room()

# Listen for events before connecting to the room
@room.on("participant_connected")
def on_participant_connected(participant):
    print(f"Participant connected: {participant.identity}")

await room.connect("ws://localhost:7880", "your_token")
async def disconnect(self, *, reason: DisconnectReason.ValueType = 1) ‑> None
Expand source code
async def disconnect(
    self, *, reason: DisconnectReason.ValueType = DisconnectReason.CLIENT_INITIATED
) -> None:
    """Disconnects from the room."""
    if not self.isconnected():
        return

    await self._drain_rpc_invocation_tasks()
    self._error_stream_readers()
    self._dispose_open_stream_writers()

    req = proto_ffi.FfiRequest()
    req.disconnect.room_handle = self._ffi_handle.handle  # type: ignore
    req.disconnect.reason = reason
    queue = FfiClient.instance.queue.subscribe()
    try:
        resp = FfiClient.instance.request(req)
        await queue.wait_for(lambda e: e.disconnect.async_id == resp.disconnect.async_id)
    finally:
        FfiClient.instance.queue.unsubscribe(queue)

    await self._task
    FfiClient.instance.queue.unsubscribe(self._ffi_queue)

    # we should manually flip the state, since the connection could have been torn down before
    # the callbacks were processed
    if self._connection_state != ConnectionState.CONN_DISCONNECTED:
        self.local_participant._info.disconnect_reason = reason
        self._connection_state = ConnectionState.CONN_DISCONNECTED
        self._fail_first_sid(RuntimeError("room disconnected before receiving sid"))
        self.emit("connection_state_changed", self._connection_state)
        self.emit("disconnected", reason)

Disconnects from the room.

async def get_rtc_stats(self) ‑> RtcStats
Expand source code
async def get_rtc_stats(self) -> RtcStats:
    if not self.isconnected():
        raise RuntimeError("the room isn't connected")

    req = proto_ffi.FfiRequest()
    req.get_session_stats.room_handle = self._ffi_handle.handle  # type: ignore

    queue = FfiClient.instance.queue.subscribe()
    try:
        resp = FfiClient.instance.request(req)
        cb: proto_ffi.FfiEvent = await queue.wait_for(
            lambda e: e.get_session_stats.async_id == resp.get_session_stats.async_id
        )
    finally:
        FfiClient.instance.queue.unsubscribe(queue)

    if cb.get_session_stats.error:
        raise RuntimeError(cb.get_session_stats.error)

    publisher_stats = list(cb.get_session_stats.result.publisher_stats)
    subscriber_stats = list(cb.get_session_stats.result.subscriber_stats)

    return RtcStats(publisher_stats=publisher_stats, subscriber_stats=subscriber_stats)
def isconnected(self) ‑> bool
Expand source code
def isconnected(self) -> bool:
    """Checks if the room is currently connected.

    Returns:
        bool: True if connected, False otherwise.
    """
    return (
        self._ffi_handle is not None
        and self._connection_state != ConnectionState.CONN_DISCONNECTED
    )

Checks if the room is currently connected.

Returns

bool
True if connected, False otherwise.
def on(self, event: EventTypes, callback: Optional[Callable] = None) ‑> Callable
Expand source code
def on(self, event: EventTypes, callback: Optional[Callable] = None) -> Callable:
    """Registers an event handler for a specific event type.

    Parameters:
        event (EventTypes): The name of the event to listen for.
        callback (Callable): The function to call when the event occurs.

    Returns:
        Callable: The registered callback function.

    Available events:
        - **"participant_connected"**: Called when a new participant joins the room.
            - Arguments: `participant` (RemoteParticipant)
        - **"participant_disconnected"**: Called when a participant leaves the room.
            - Arguments: `participant` (RemoteParticipant)
        - **"participant_active"**: Called when a remote participant becomes active and is ready to receive data messages.
            - Arguments: `participant` (RemoteParticipant)
        - **"local_track_published"**: Called when a local track is published.
            - Arguments: `publication` (LocalTrackPublication), `track` (Track)
        - **"local_track_unpublished"**: Called when a local track is unpublished.
            - Arguments: `publication` (LocalTrackPublication)
        - **"local_track_republished"**: Called when the SDK auto-republished a local
            track during a full reconnect. The publication object is updated in place
            with the new server-assigned SIDs (its previous SID is passed alongside so
            callers can reconcile any external state keyed by the old SID).
            - Arguments: `publication` (LocalTrackPublication), `previous_sid` (str)
        - **"local_track_subscribed"**: Called when a local track is subscribed.
            - Arguments: `track` (Track)
        - **"track_published"**: Called when a remote participant publishes a track.
            - Arguments: `publication` (RemoteTrackPublication), `participant` (RemoteParticipant)
        - **"track_unpublished"**: Called when a remote participant unpublishes a track.
            - Arguments: `publication` (RemoteTrackPublication), `participant` (RemoteParticipant)
        - **"track_subscribed"**: Called when a track is subscribed.
            - Arguments: `track` (Track), `publication` (RemoteTrackPublication), `participant` (RemoteParticipant)
        - **"track_unsubscribed"**: Called when a track is unsubscribed.
            - Arguments: `track` (Track), `publication` (RemoteTrackPublication), `participant` (RemoteParticipant)
        - **"track_subscription_failed"**: Called when a track subscription fails.
            - Arguments: `participant` (RemoteParticipant), `track_sid` (str), `error` (str)
        - **"track_muted"**: Called when a track is muted.
            - Arguments: `participant` (Participant), `publication` (TrackPublication)
        - **"track_unmuted"**: Called when a track is unmuted.
            - Arguments: `participant` (Participant), `publication` (TrackPublication)
        - **"active_speakers_changed"**: Called when the list of active speakers changes.
            - Arguments: `speakers` (list[Participant])
        - **"room_metadata_changed"**: Called when the room's metadata is updated.
            - Arguments: `old_metadata` (str), `new_metadata` (str)
        - **"participant_metadata_changed"**: Called when a participant's metadata is updated.
            - Arguments: `participant` (Participant), `old_metadata` (str), `new_metadata` (str)
        - **"participant_name_changed"**: Called when a participant's name is changed.
            - Arguments: `participant` (Participant), `old_name` (str), `new_name` (str)
        - **"participant_attributes_changed"**: Called when a participant's attributes change.
            - Arguments: `changed_attributes` (dict), `participant` (Participant)
        - **"participant_encryption_status_changed"**: Called when a participant's encryption status changes.
            - Arguments `is_encrypted` (bool), `participant` (Participant)
        - **"connection_quality_changed"**: Called when a participant's connection quality changes.
            - Arguments: `participant` (Participant), `quality` (ConnectionQuality)
        - **"transcription_received"**: Called when a transcription is received.
            - Arguments: `segments` (list[TranscriptionSegment]), `participant` (Participant), `publication` (TrackPublication)
        - **"data_received"**: Called when data is received.
            - Arguments: `data_packet` (DataPacket)
        - **"sip_dtmf_received"**: Called when a SIP DTMF signal is received.
            - Arguments: `sip_dtmf` (SipDTMF)
        - **"e2ee_state_changed"**: Called when a participant's E2EE state changes.
            - Arguments: `participant` (Participant), `state` (EncryptionState)
        - **"connection_state_changed"**: Called when the room's connection state changes.
            - Arguments: `connection_state` (ConnectionState)
        - **"connected"**: Called when the room is successfully connected.
            - Arguments: None
        - **"disconnected"**: Called when the room is disconnected.
            - Arguments: `reason` (DisconnectReason)
        - **"reconnecting"**: Called when the room is attempting to reconnect.
            - Arguments: None
        - **"reconnected"**: Called when the room has successfully reconnected.
            - Arguments: None
        - **"room_updated"**: Called when any information about the room is updated.
            - Arguments: None
        - **"moved"**: Called when the participant has been moved to another room.
            - Arguments: None
        - **"data_track_published"**: Called when a remote participant publishes a data track.
            - Arguments: `track` (RemoteDataTrack)
        - **"data_track_unpublished"**: Called when a remote participant unpublishes a data track.
            - Arguments: `sid` (str)

    Example:
        ```python
        def on_participant_connected(participant):
            print(f"Participant connected: {participant.identity}")

        room.on("participant_connected", on_participant_connected)
        ```
    """
    return super().on(event, callback)

Registers an event handler for a specific event type.

Parameters

event (EventTypes): The name of the event to listen for. callback (Callable): The function to call when the event occurs.

Returns

Callable
The registered callback function.

Available events: - "participant_connected": Called when a new participant joins the room. - Arguments: participant (RemoteParticipant) - "participant_disconnected": Called when a participant leaves the room. - Arguments: participant (RemoteParticipant) - "participant_active": Called when a remote participant becomes active and is ready to receive data messages. - Arguments: participant (RemoteParticipant) - "local_track_published": Called when a local track is published. - Arguments: publication (LocalTrackPublication), track (Track) - "local_track_unpublished": Called when a local track is unpublished. - Arguments: publication (LocalTrackPublication) - "local_track_republished": Called when the SDK auto-republished a local track during a full reconnect. The publication object is updated in place with the new server-assigned SIDs (its previous SID is passed alongside so callers can reconcile any external state keyed by the old SID). - Arguments: publication (LocalTrackPublication), previous_sid (str) - "local_track_subscribed": Called when a local track is subscribed. - Arguments: track (Track) - "track_published": Called when a remote participant publishes a track. - Arguments: publication (RemoteTrackPublication), participant (RemoteParticipant) - "track_unpublished": Called when a remote participant unpublishes a track. - Arguments: publication (RemoteTrackPublication), participant (RemoteParticipant) - "track_subscribed": Called when a track is subscribed. - Arguments: track (Track), publication (RemoteTrackPublication), participant (RemoteParticipant) - "track_unsubscribed": Called when a track is unsubscribed. - Arguments: track (Track), publication (RemoteTrackPublication), participant (RemoteParticipant) - "track_subscription_failed": Called when a track subscription fails. - Arguments: participant (RemoteParticipant), track_sid (str), error (str) - "track_muted": Called when a track is muted. - Arguments: participant (Participant), publication (TrackPublication) - "track_unmuted": Called when a track is unmuted. - Arguments: participant (Participant), publication (TrackPublication) - "active_speakers_changed": Called when the list of active speakers changes. - Arguments: speakers (list[Participant]) - "room_metadata_changed": Called when the room's metadata is updated. - Arguments: old_metadata (str), new_metadata (str) - "participant_metadata_changed": Called when a participant's metadata is updated. - Arguments: participant (Participant), old_metadata (str), new_metadata (str) - "participant_name_changed": Called when a participant's name is changed. - Arguments: participant (Participant), old_name (str), new_name (str) - "participant_attributes_changed": Called when a participant's attributes change. - Arguments: changed_attributes (dict), participant (Participant) - "participant_encryption_status_changed": Called when a participant's encryption status changes. - Arguments is_encrypted (bool), participant (Participant) - "connection_quality_changed": Called when a participant's connection quality changes. - Arguments: participant (Participant), quality (ConnectionQuality) - "transcription_received": Called when a transcription is received. - Arguments: segments (list[TranscriptionSegment]), participant (Participant), publication (TrackPublication) - "data_received": Called when data is received. - Arguments: data_packet (DataPacket) - "sip_dtmf_received": Called when a SIP DTMF signal is received. - Arguments: sip_dtmf (SipDTMF) - "e2ee_state_changed": Called when a participant's E2EE state changes. - Arguments: participant (Participant), state (EncryptionState) - "connection_state_changed": Called when the room's connection state changes. - Arguments: connection_state (ConnectionState) - "connected": Called when the room is successfully connected. - Arguments: None - "disconnected": Called when the room is disconnected. - Arguments: reason (DisconnectReason) - "reconnecting": Called when the room is attempting to reconnect. - Arguments: None - "reconnected": Called when the room has successfully reconnected. - Arguments: None - "room_updated": Called when any information about the room is updated. - Arguments: None - "moved": Called when the participant has been moved to another room. - Arguments: None - "data_track_published": Called when a remote participant publishes a data track. - Arguments: track (RemoteDataTrack) - "data_track_unpublished": Called when a remote participant unpublishes a data track. - Arguments: sid (str)

Example

def on_participant_connected(participant):
    print(f"Participant connected: {participant.identity}")

room.on("participant_connected", on_participant_connected)
def register_byte_stream_handler(self, topic: str, handler: ByteStreamHandler) ‑> None
Expand source code
def register_byte_stream_handler(self, topic: str, handler: ByteStreamHandler) -> None:
    existing_handler = self._byte_stream_handlers.get(topic)
    if existing_handler is None:
        self._byte_stream_handlers[topic] = handler
    else:
        raise ValueError("byte stream handler for topic '%s' already set" % topic)
def register_text_stream_handler(self, topic: str, handler: TextStreamHandler) ‑> None
Expand source code
def register_text_stream_handler(self, topic: str, handler: TextStreamHandler) -> None:
    existing_handler = self._text_stream_handlers.get(topic)
    if existing_handler is None:
        self._text_stream_handlers[topic] = handler
    else:
        raise ValueError("text stream handler for topic '%s' already set" % topic)
async def simulate_scenario(self, scenario: SimulateScenarioKind.ValueType) ‑> None
Expand source code
async def simulate_scenario(self, scenario: SimulateScenarioKind.ValueType) -> None:
    """Trigger a reconnection / chaos scenario for testing.

    See `SimulateScenarioKind` for the available variants. Most useful
    in tests to deterministically force a Resume (signal-only reconnect
    that preserves the PeerConnection and existing publications) or a
    full reconnect (the SDK rebuilds the RtcSession and re-publishes
    existing local tracks).

    Raises a `RuntimeError` if the SDK reports a failure.
    """
    if not self.isconnected() or self._ffi_handle is None:
        raise RuntimeError("simulate_scenario requires a connected room")

    req = proto_ffi.FfiRequest()
    req.simulate_scenario.room_handle = self._ffi_handle.handle
    req.simulate_scenario.scenario = scenario
    queue = FfiClient.instance.queue.subscribe()
    try:
        resp = FfiClient.instance.request(req)
        cb = await queue.wait_for(
            lambda e: e.simulate_scenario.async_id == resp.simulate_scenario.async_id
        )
    finally:
        FfiClient.instance.queue.unsubscribe(queue)

    if cb.simulate_scenario.HasField("error") and cb.simulate_scenario.error:
        raise RuntimeError(f"simulate_scenario failed: {cb.simulate_scenario.error}")

Trigger a reconnection / chaos scenario for testing.

See SimulateScenarioKind for the available variants. Most useful in tests to deterministically force a Resume (signal-only reconnect that preserves the PeerConnection and existing publications) or a full reconnect (the SDK rebuilds the RtcSession and re-publishes existing local tracks).

Raises a RuntimeError if the SDK reports a failure.

def unregister_byte_stream_handler(self, topic: str) ‑> None
Expand source code
def unregister_byte_stream_handler(self, topic: str) -> None:
    if self._byte_stream_handlers.get(topic):
        self._byte_stream_handlers.pop(topic)
def unregister_text_stream_handler(self, topic: str) ‑> None
Expand source code
def unregister_text_stream_handler(self, topic: str) -> None:
    if self._text_stream_handlers.get(topic):
        self._text_stream_handlers.pop(topic)

Inherited members

class RoomOptions (auto_subscribe: bool = True,
dynacast: bool = False,
e2ee: E2EEOptions | None = None,
encryption: E2EEOptions | None = None,
rtc_config: RtcConfiguration | None = None,
connect_timeout: float | None = None,
single_peer_connection: bool | None = None,
data_stream: DataStreamOptions | None = None)
Expand source code
@dataclass
class RoomOptions:
    auto_subscribe: bool = True
    """Automatically subscribe to tracks when participants join."""
    dynacast: bool = False
    e2ee: E2EEOptions | None = None
    """Deprecated, use `encryption` field instead"""
    encryption: E2EEOptions | None = None
    """Options for end-to-end encryption."""
    rtc_config: RtcConfiguration | None = None
    """WebRTC-related configuration."""
    connect_timeout: float | None = None
    """Timeout in seconds for each signal connection attempt. When None, uses the default (5s)."""
    single_peer_connection: bool | None = None
    """Use a single peer connection for both publish and subscribe. When None, uses the default (true)."""
    data_stream: DataStreamOptions | None = None
    """Options for incoming data streams. When None, uses the FFI defaults."""

RoomOptions(auto_subscribe: 'bool' = True, dynacast: 'bool' = False, e2ee: 'E2EEOptions | None' = None, encryption: 'E2EEOptions | None' = None, rtc_config: 'RtcConfiguration | None' = None, connect_timeout: 'float | None' = None, single_peer_connection: 'bool | None' = None, data_stream: 'DataStreamOptions | None' = None)

Instance variables

var auto_subscribe : bool

Automatically subscribe to tracks when participants join.

var connect_timeout : float | None

Timeout in seconds for each signal connection attempt. When None, uses the default (5s).

var data_stream : DataStreamOptions | None

Options for incoming data streams. When None, uses the FFI defaults.

var dynacast : bool
var e2ee : E2EEOptions | None

Deprecated, use encryption field instead

var encryption : E2EEOptions | None

Options for end-to-end encryption.

var rtc_config : RtcConfiguration | None

WebRTC-related configuration.

var single_peer_connection : bool | None

Use a single peer connection for both publish and subscribe. When None, uses the default (true).

class RpcMethodInvocationEvent (*args, **kwargs)

A ProtocolMessage

Ancestors

  • google._upb._message.Message
  • google.protobuf.message.Message

Class variables

var DESCRIPTOR
class RtcConfiguration (ice_transport_type: proto_room.IceTransportType.ValueType = 2,
continual_gathering_policy: proto_room.ContinualGatheringPolicy.ValueType = 1,
ice_servers: list[proto_room.IceServer] = <factory>)
Expand source code
@dataclass
class RtcConfiguration:
    ice_transport_type: proto_room.IceTransportType.ValueType = (
        proto_room.IceTransportType.TRANSPORT_ALL
    )
    """Specifies the type of ICE transport to be used (e.g., all, relay, etc.)."""
    continual_gathering_policy: proto_room.ContinualGatheringPolicy.ValueType = (
        proto_room.ContinualGatheringPolicy.GATHER_CONTINUALLY
    )
    """Policy for continual gathering of ICE candidates."""
    ice_servers: list[proto_room.IceServer] = field(default_factory=list)
    """List of ICE servers for STUN/TURN. When empty, it uses the default ICE servers provided by
    the SFU."""

RtcConfiguration(ice_transport_type: 'proto_room.IceTransportType.ValueType' = 2, continual_gathering_policy: 'proto_room.ContinualGatheringPolicy.ValueType' = 1, ice_servers: 'list[proto_room.IceServer]' = )

Instance variables

var continual_gathering_policy : int

Policy for continual gathering of ICE candidates.

var ice_servers : list[room_pb2.IceServer]

List of ICE servers for STUN/TURN. When empty, it uses the default ICE servers provided by the SFU.

var ice_transport_type : int

Specifies the type of ICE transport to be used (e.g., all, relay, etc.).

class RtcStats (publisher_stats: list[proto_stats.RtcStats],
subscriber_stats: list[proto_stats.RtcStats])
Expand source code
@dataclass
class RtcStats:
    publisher_stats: list[proto_stats.RtcStats]
    subscriber_stats: list[proto_stats.RtcStats]

RtcStats(publisher_stats: 'list[proto_stats.RtcStats]', subscriber_stats: 'list[proto_stats.RtcStats]')

Instance variables

var publisher_stats : list[stats_pb2.RtcStats]
var subscriber_stats : list[stats_pb2.RtcStats]
class SipDTMF (code: int, digit: str, participant: RemoteParticipant | None = None)
Expand source code
@dataclass
class SipDTMF:
    code: int
    """DTMF code corresponding to the digit."""
    digit: str
    """DTMF digit sent."""
    participant: RemoteParticipant | None = None
    """Participant who sent the DTMF digit. None when sent by a server SDK."""

SipDTMF(code: 'int', digit: 'str', participant: 'RemoteParticipant | None' = None)

Instance variables

var code : int

DTMF code corresponding to the digit.

var digit : str

DTMF digit sent.

var participant : RemoteParticipant | None

Participant who sent the DTMF digit. None when sent by a server SDK.