RTCPeerConnection
The connection between the local peer and a remote one.
- class webrtc.interfaces.rtc_peer_connection.RTCPeerConnection(configuration=None)
A connection to a remote peer, which negotiates and carries media tracks and data channels.
The application exchanges descriptions (
create_offer(),create_answer()) and ICE candidates with the remote peer over its own signaling channel. Operations that change the negotiation run one after another, in the order they’re called. See MDN: RTCPeerConnection.- Events:
negotiationneeded (
webrtc.Event) – Negotiation (an offer/answer exchange) is needed.icecandidate (
webrtc.RTCPeerConnectionIceEvent) – A local ICE candidate was gathered and should be sent to the remote peer. ItscandidateisNoneonce gathering is complete.icecandidateerror (
webrtc.RTCPeerConnectionIceErrorEvent) – A STUN or TURN server failed.signalingstatechange (
webrtc.Event) –signaling_statechanged.iceconnectionstatechange (
webrtc.Event) –ice_connection_statechanged.icegatheringstatechange (
webrtc.Event) –ice_gathering_statechanged.connectionstatechange (
webrtc.Event) –connection_statechanged.track (
webrtc.RTCTrackEvent) – A remote track was negotiated.datachannel (
webrtc.RTCDataChannelEvent) – The remote peer created a data channel.
A connection with handlers or a pending operation stays alive until it or its event loop closes.
- Parameters:
configuration (
webrtc.RTCConfiguration, optional) – The configuration of the connection. The defaults ofwebrtc.RTCConfigurationare used if it’s omitted.- Raises:
webrtc.InvalidSyntaxError – If an ICE server URL is invalid.
webrtc.InvalidAccessError – If a TURN server has no credentials, or a certificate has expired.
ValueError – If a member of the configuration is out of range.
TypeError – If a member of the configuration has a wrong type, or a value its enum doesn’t have.
Events
negotiationneeded:Eventsignalingstatechange:Eventiceconnectionstatechange:Eventicegatheringstatechange:Eventconnectionstatechange:Eventicecandidate:RTCPeerConnectionIceEventicecandidateerror:RTCPeerConnectionIceErrorEventtrack:RTCTrackEventdatachannel:RTCDataChannelEvent
Handlers are registered with
on().- async create_offer(options=None)
Creates an offer that starts a negotiation or renegotiates one.
The offer describes the transceivers and data channels of the connection, with the codecs it supports and the ICE candidates gathered so far. It isn’t applied until it’s passed to
set_local_description(). See MDN: RTCPeerConnection/createOffer.- Parameters:
options (
webrtc.RTCOfferOptions, optional) – How to create the offer.- Returns:
webrtc.RTCSessionDescriptionInit– The offer, to set withset_local_description().- Raises:
webrtc.InvalidStateError – If the signaling state isn’t
stableorhave-local-offer, or the connection is closed.- Return type:
- async create_answer(options=None)
Creates an answer to the offer set as the remote description.
It isn’t applied until it’s passed to
set_local_description(). See MDN: RTCPeerConnection/createAnswer.- Parameters:
options (
webrtc.RTCAnswerOptions, optional) – How to create the answer.- Returns:
webrtc.RTCSessionDescriptionInit– The answer, to set withset_local_description().- Raises:
TypeError – If the options aren’t an
webrtc.RTCAnswerOptions.webrtc.InvalidStateError – If the connection is closed or has no remote offer.
- Return type:
- async set_local_description(description=None)
Applies a local session description, which starts ICE gathering.
See MDN: RTCPeerConnection/setLocalDescription.
- Parameters:
description (
webrtc.RTCSessionDescription, optional) – The description, as returned bycreate_offer()orcreate_answer(), or arollbackone. Anwebrtc.RTCSessionDescriptionInitorwebrtc.RTCLocalSessionDescriptionInitis accepted too, with its SDP modified if needed. Without it, or without a type and an SDP, the offer or the answer the signaling state calls for is created and set.- Raises:
webrtc.InvalidStateError – If the type doesn’t match the signaling state, or the connection is closed.
webrtc.InvalidModificationError – If the SDP changes the fingerprint
create_offer()orcreate_answer()made.webrtc.RTCError – If the SDP can’t be parsed (
sdp_syntax_error).TypeError – If the description has an SDP but no type, or is neither of the accepted types.
- async set_remote_description(description)
Applies an offer, an answer or a rollback received from the remote peer.
An offer set while there’s a local offer rolls the local one back first. Remote tracks the description adds are announced with
trackevents. See MDN: RTCPeerConnection/setRemoteDescription.- Parameters:
description (
webrtc.RTCSessionDescriptionInit) – The description received from the remote peer, like one fromwebrtc.RTCSessionDescriptionInit.from_json(). Anwebrtc.RTCSessionDescriptionis accepted too.- Raises:
webrtc.InvalidStateError – If the type doesn’t match the signaling state, or the connection is closed.
webrtc.RTCError – If the SDP can’t be parsed (
sdp_syntax_error).webrtc.InvalidAccessError – If the description can’t be applied.
TypeError – If the description is neither of the accepted types.
- add_track(track, *streams)
Starts sending a track to the remote peer, from the next negotiation.
If there’s an unused transceiver of the same kind, it’s reused. Otherwise a new one is added. See MDN: RTCPeerConnection/addTrack.
- Parameters:
track (
webrtc.MediaStreamTrack) – The track to send.*streams (
webrtc.MediaStream) – The local streams the remote peer receives the track in.
- Returns:
webrtc.RTCRtpSender– The sender of the track.- Raises:
webrtc.InvalidStateError – If the connection is closed.
webrtc.InvalidAccessError – If a sender of the connection already has the track.
- Return type:
- add_transceiver(track_or_kind, init=None)
Adds a new transceiver, negotiated with the next offer.
See MDN: RTCPeerConnection/addTransceiver.
- Parameters:
track_or_kind (
webrtc.MediaStreamTrackorwebrtc.MediaType) – The track the sender of the transceiver sends, or the kind of media ('audio'or'video') for a transceiver without one.init (
webrtc.RTCRtpTransceiverInit, optional) – The options of the new transceiver.
- Returns:
webrtc.RTCRtpTransceiver– The new transceiver.- Raises:
TypeError – If the kind is neither audio nor video, or a
ridof the send encodings is invalid, or missing or repeated with several encodings.webrtc.OperationError – If the codec of a send encoding can’t be sent.
webrtc.InvalidStateError – If the connection is closed.
- Return type:
- get_transceivers()
Returns the transceivers of the connection, in the order they were added.
See MDN: RTCPeerConnection/getTransceivers.
- Returns:
listofwebrtc.RTCRtpTransceiver– The transceivers.- Return type:
- get_senders()
Returns the senders of the transceivers of the connection, one per transceiver.
See MDN: RTCPeerConnection/getSenders.
- Returns:
listofwebrtc.RTCRtpSender– The senders, including the ones without a track.- Return type:
- get_receivers()
Returns the receivers of the transceivers of the connection, one per transceiver.
See MDN: RTCPeerConnection/getReceivers.
- Returns:
listofwebrtc.RTCRtpReceiver– The receivers.- Return type:
- remove_track(sender)
Stops sending the track of a sender, from the next negotiation. The sender stays in
get_senders().Does nothing if the sender has no track, or is stopped or rolled back. See MDN: RTCPeerConnection/removeTrack.
- Parameters:
sender (
webrtc.RTCRtpSender) – A sender of this connection.- Raises:
webrtc.InvalidStateError – If the connection is closed.
webrtc.InvalidAccessError – If the sender wasn’t created by this connection.
- async add_ice_candidate(candidate=None)
Adds a candidate received from the remote peer to the remote description.
See MDN: RTCPeerConnection/addIceCandidate.
- Parameters:
candidate (
webrtc.RTCIceCandidateInitorwebrtc.RTCIceCandidate, optional) – The candidate, like one fromwebrtc.RTCIceCandidateInit.from_json(). An emptycandidate, orNone, means the end of candidates.- Raises:
TypeError – If a non-empty candidate has neither
sdp_midnorsdp_m_line_index.webrtc.InvalidStateError – If there’s no remote description, or the connection is closed.
webrtc.OperationError – If the candidate can’t be parsed or doesn’t match a media section.
- create_data_channel(label, data_channel_dict=None)
Creates a channel to exchange messages with the remote peer.
The first channel needs a negotiation, which adds the SCTP transport. A
negotiatedchannel isn’t announced to the remote peer, so both peers create it with the sameid. See MDN: RTCPeerConnection/createDataChannel.- Parameters:
label (
str) – The name of the channel, up to 65535 bytes in UTF-8.data_channel_dict (
webrtc.RTCDataChannelInit, optional) – How to create the channel.
- Returns:
webrtc.RTCDataChannel– The channel.- Raises:
TypeError – If the label or an option is out of range, or both
max_packet_life_timeandmax_retransmitsare set, ornegotiatedis set withoutid.webrtc.InvalidStateError – If the connection is closed.
webrtc.OperationError – If the
idis in use, or no id is left.
- Return type:
- async get_stats(selector=None)
Collects the stats of the connection, or of the sender or the receiver of a track.
See MDN: RTCPeerConnection/getStats.
- Parameters:
selector (
webrtc.MediaStreamTrack, optional) – A track of exactly one sender or receiver of the connection. Only the stats of that sender or receiver are collected.- Returns:
webrtc.RTCStatsReport– The stats.- Raises:
webrtc.InvalidAccessError – If no sender or receiver, or more than one, has the track.
webrtc.InvalidStateError – If the connection is closed.
- Return type:
- async static generate_certificate(keygen_algorithm)
Generates a key and a self-signed certificate on a worker thread, for
RTCConfiguration.certificates.See MDN: RTCPeerConnection/generateCertificate_static.
- Parameters:
keygen_algorithm (
strorwebrtc.Algorithm) – A WebCrypto algorithm:'ECDSA'(with the P-256 curve), anwebrtc.EcKeyGenParams, or anwebrtc.RsaHashedKeyGenParamslikeRsaHashedKeyGenParams('RSASSA-PKCS1-v1_5', modulus_length=2048, public_exponent=bytes([1, 0, 1]), hash='SHA-256'). Itsexpiressets for how many milliseconds the certificate is valid, up to a year (30 days by default).- Returns:
webrtc.RTCCertificate– The certificate.- Raises:
webrtc.NotSupportedError – If the algorithm isn’t supported.
TypeError – If
expiresisn’t an unsigned 64-bit integer.
- Return type:
- get_configuration()
Returns the configuration of the connection, as it was last set.
The certificates are the ones in use, generated or given. See MDN: RTCPeerConnection/getConfiguration.
- Returns:
webrtc.RTCConfiguration– A copy of the configuration. Changing it doesn’t affect the connection.- Return type:
- set_configuration(configuration=None)
Replaces the configuration of the connection. Members that aren’t set get their default values.
Changed ICE servers or ICE transport policy apply to the candidates gathered next, like after
restart_ice(). See MDN: RTCPeerConnection/setConfiguration.- Parameters:
configuration (
webrtc.RTCConfiguration, optional) – The new configuration.- Raises:
webrtc.InvalidStateError – If the connection is closed.
webrtc.InvalidModificationError – If a member that can’t be changed differs, like
webrtc.RTCConfiguration.bundle_policyorwebrtc.RTCConfiguration.always_negotiate_data_channels.webrtc.InvalidSyntaxError – If an ICE server URL is invalid.
webrtc.InvalidAccessError – If a TURN server has no credentials, or a certificate has expired.
ValueError – If a member of the configuration is out of range.
TypeError – If a member of the configuration has a wrong type, or a value its enum doesn’t have.
- restart_ice()
Requests an ICE restart, with new credentials and candidates, from the next negotiation on either side.
It leads to a
negotiationneededevent. It does nothing before the first local description, since that one already has new credentials, or once the connection is closed. See MDN: RTCPeerConnection/restartIce.
- close()
Closes the connection for good, stopping its transceivers and data channels.
No events follow except remote tracks’
ended. See MDN: RTCPeerConnection/close.
- property sctp: RTCSctpTransport | None
The transport of the data channels.
It’s
Noneuntil the data channels are negotiated. See MDN: RTCPeerConnection/sctp.- Type:
webrtc.RTCSctpTransport, optional
- property local_description: RTCSessionDescription | None
The pending local description, or else the current one.
Noneuntil one is set. It includes the ICE candidates gathered so far. See MDN: RTCPeerConnection/localDescription.- Type:
webrtc.RTCSessionDescription, optional
- property remote_description: RTCSessionDescription | None
The pending remote description, or else the current one.
Noneuntil one is set. It includes the candidates added withadd_ice_candidate(). See MDN: RTCPeerConnection/remoteDescription.- Type:
webrtc.RTCSessionDescription, optional
- property current_local_description: RTCSessionDescription | None
The local description of the last completed negotiation.
See MDN: RTCPeerConnection/currentLocalDescription.
- Type:
webrtc.RTCSessionDescription, optional
- property current_remote_description: RTCSessionDescription | None
The remote description of the last completed negotiation.
See MDN: RTCPeerConnection/currentRemoteDescription.
- Type:
webrtc.RTCSessionDescription, optional
- property pending_local_description: RTCSessionDescription | None
The local description of a negotiation in progress.
See MDN: RTCPeerConnection/pendingLocalDescription.
- Type:
webrtc.RTCSessionDescription, optional
- property pending_remote_description: RTCSessionDescription | None
The remote description of a negotiation in progress.
See MDN: RTCPeerConnection/pendingRemoteDescription.
- Type:
webrtc.RTCSessionDescription, optional
- property can_trickle_ice_candidates: bool | None
Whether the remote peer takes candidates one by one (trickle ICE).
Noneuntil there’s a remote description. See MDN: RTCPeerConnection/canTrickleIceCandidates.- Type:
bool, optional
- property connection_state: RTCPeerConnectionState
The overall state of the ICE and DTLS transports of the connection.
- property signaling_state: RTCSignalingState
Where the connection is in the offer/answer exchange.
See MDN: RTCPeerConnection/signalingState.
- Type:
- property ice_connection_state: RTCIceConnectionState
The overall state of the ICE transports of the connection.
- property ice_gathering_state: RTCIceGatheringState
The overall candidate gathering state of the ICE transports.