index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
718,870
aiortc.rtcpeerconnection
__updateConnectionState
null
def __updateConnectionState(self) -> None: # compute new state # NOTE: we do not have a "disconnected" state dtlsStates = set(map(lambda x: x.state, self.__dtlsTransports)) iceStates = set(map(lambda x: x.state, self.__iceTransports)) if self.__isClosed: state = "closed" elif "failed" in iceStates or "failed" in dtlsStates: state = "failed" elif not iceStates.difference(["new", "closed"]) and not dtlsStates.difference( ["new", "closed"] ): state = "new" elif "checking" in iceStates or "connecting" in dtlsStates: state = "connecting" elif "new" in dtlsStates: # this avoids a spurious connecting -> connected -> connecting # transition after ICE connects but before DTLS starts state = "connecting" else: state = "connected" # update state if state != self.__connectionState: self.__log_debug("connectionState %s -> %s", self.__connectionState, state) self.__connectionState = state self.emit("connectionstatechange") # if all DTLS connections are closed, initiate a shutdown if ( not self.__isClosed and self.__closeTask is None and dtlsStates == set(["closed"]) ): self.__closeTask = asyncio.ensure_future(self.close())
(self) -> NoneType
718,871
aiortc.rtcpeerconnection
__updateIceConnectionState
null
def __updateIceConnectionState(self) -> None: # compute new state # NOTE: we do not have "connected" or "disconnected" states states = set(map(lambda x: x.state, self.__iceTransports)) if self.__isClosed: state = "closed" elif "failed" in states: state = "failed" elif states == set(["completed"]): state = "completed" elif "checking" in states: state = "checking" else: state = "new" # update state if state != self.__iceConnectionState: self.__log_debug( "iceConnectionState %s -> %s", self.__iceConnectionState, state ) self.__iceConnectionState = state self.emit("iceconnectionstatechange")
(self) -> NoneType
718,872
aiortc.rtcpeerconnection
__updateIceGatheringState
null
def __updateIceGatheringState(self) -> None: # compute new state states = set(map(lambda x: x.iceGatherer.state, self.__iceTransports)) if states == set(["completed"]): state = "complete" elif "gathering" in states: state = "gathering" else: state = "new" # update state if state != self.__iceGatheringState: self.__log_debug( "iceGatheringState %s -> %s", self.__iceGatheringState, state ) self.__iceGatheringState = state self.emit("icegatheringstatechange")
(self) -> NoneType
718,873
aiortc.rtcpeerconnection
__validate_description
null
def __validate_description( self, description: sdp.SessionDescription, is_local: bool ) -> None: # check description is compatible with signaling state if is_local: if description.type == "offer": if self.signalingState not in ["stable", "have-local-offer"]: raise InvalidStateError( "Cannot handle offer in signaling state " f'"{self.signalingState}"' ) elif description.type == "answer": if self.signalingState not in [ "have-remote-offer", "have-local-pranswer", ]: raise InvalidStateError( "Cannot handle answer in signaling state " f'"{self.signalingState}"' ) else: if description.type == "offer": if self.signalingState not in ["stable", "have-remote-offer"]: raise InvalidStateError( "Cannot handle offer in signaling state " f'"{self.signalingState}"' ) elif description.type == "answer": if self.signalingState not in [ "have-local-offer", "have-remote-pranswer", ]: raise InvalidStateError( "Cannot handle answer in signaling state " f'"{self.signalingState}"' ) for media in description.media: # check ICE credentials were provided if not media.ice.usernameFragment or not media.ice.password: raise ValueError("ICE username fragment or password is missing") # check DTLS role is allowed if description.type == "offer" and media.dtls.role != "auto": raise ValueError("DTLS setup attribute must be 'actpass' for an offer") if description.type in ["answer", "pranswer"] and media.dtls.role not in [ "client", "server", ]: raise ValueError( "DTLS setup attribute must be 'active' or 'passive' for an answer" ) # check RTCP mux is used if media.kind in ["audio", "video"] and not media.rtcp_mux: raise ValueError("RTCP mux is not enabled") # check the number of media section matches if description.type in ["answer", "pranswer"]: offer = ( self.__remoteDescription() if is_local else self.__localDescription() ) offer_media = [(media.kind, media.rtp.muxId) for media in offer.media] answer_media = [ (media.kind, media.rtp.muxId) for media in description.media ] if answer_media != offer_media: raise ValueError("Media sections in answer do not match offer")
(self, description: aiortc.sdp.SessionDescription, is_local: bool) -> NoneType
718,875
aiortc.rtcpeerconnection
__init__
null
def __init__(self, configuration: Optional[RTCConfiguration] = None) -> None: super().__init__() self.__certificates = [RTCCertificate.generateCertificate()] self.__cname = f"{uuid.uuid4()}" self.__configuration = configuration or RTCConfiguration() self.__dtlsTransports: Set[RTCDtlsTransport] = set() self.__iceTransports: Set[RTCIceTransport] = set() self.__remoteDtls: Dict[ Union[RTCRtpTransceiver, RTCSctpTransport], RTCDtlsParameters ] = {} self.__remoteIce: Dict[ Union[RTCRtpTransceiver, RTCSctpTransport], RTCIceParameters ] = {} self.__seenMids: Set[str] = set() self.__sctp: Optional[RTCSctpTransport] = None self.__sctp_mline_index: Optional[int] = None self._sctpLegacySdp = True self.__sctpRemotePort: Optional[int] = None self.__sctpRemoteCaps = None self.__stream_id = str(uuid.uuid4()) self.__transceivers: List[RTCRtpTransceiver] = [] self.__closeTask: Optional[asyncio.Task] = None self.__connectionState = "new" self.__iceConnectionState = "new" self.__iceGatheringState = "new" self.__isClosed: Optional[asyncio.Future[bool]] = None self.__signalingState = "stable" self.__currentLocalDescription: Optional[sdp.SessionDescription] = None self.__currentRemoteDescription: Optional[sdp.SessionDescription] = None self.__pendingLocalDescription: Optional[sdp.SessionDescription] = None self.__pendingRemoteDescription: Optional[sdp.SessionDescription] = None
(self, configuration: Optional[aiortc.rtcconfiguration.RTCConfiguration] = None) -> NoneType
718,882
aiortc.rtcpeerconnection
addIceCandidate
Add a new :class:`RTCIceCandidate` received from the remote peer. The specified candidate must have a value for either `sdpMid` or `sdpMLineIndex`. :param candidate: The new remote candidate.
@property def signalingState(self): """ The current signaling state. Possible values: `"closed"`, `"have-local-offer"`, `"have-remote-offer`", `"stable"`. When the state changes, the `"signalingstatechange"` event is fired. """ return self.__signalingState
(self, candidate: aiortc.rtcicetransport.RTCIceCandidate) -> NoneType
718,883
aiortc.rtcpeerconnection
addTrack
Add a :class:`MediaStreamTrack` to the set of media tracks which will be transmitted to the remote peer.
def addTrack(self, track: MediaStreamTrack) -> RTCRtpSender: """ Add a :class:`MediaStreamTrack` to the set of media tracks which will be transmitted to the remote peer. """ # check state is valid self.__assertNotClosed() if track.kind not in ["audio", "video"]: raise InternalError(f'Invalid track kind "{track.kind}"') # don't add track twice self.__assertTrackHasNoSender(track) for transceiver in self.__transceivers: if transceiver.kind == track.kind: if transceiver.sender.track is None: transceiver.sender.replaceTrack(track) transceiver.direction = or_direction( transceiver.direction, "sendonly" ) return transceiver.sender transceiver = self.__createTransceiver( direction="sendrecv", kind=track.kind, sender_track=track ) return transceiver.sender
(self, track: aiortc.mediastreams.MediaStreamTrack) -> aiortc.rtcrtpsender.RTCRtpSender
718,884
aiortc.rtcpeerconnection
addTransceiver
Add a new :class:`RTCRtpTransceiver`.
def addTransceiver( self, trackOrKind: Union[str, MediaStreamTrack], direction: str = "sendrecv" ) -> RTCRtpTransceiver: """ Add a new :class:`RTCRtpTransceiver`. """ self.__assertNotClosed() # determine track or kind if isinstance(trackOrKind, MediaStreamTrack): kind = trackOrKind.kind track = trackOrKind else: kind = trackOrKind track = None if kind not in ["audio", "video"]: raise InternalError(f'Invalid track kind "{kind}"') # check direction if direction not in sdp.DIRECTIONS: raise InternalError(f'Invalid direction "{direction}"') # don't add track twice if track: self.__assertTrackHasNoSender(track) return self.__createTransceiver( direction=direction, kind=kind, sender_track=track )
(self, trackOrKind: Union[str, aiortc.mediastreams.MediaStreamTrack], direction: str = 'sendrecv') -> aiortc.rtcrtptransceiver.RTCRtpTransceiver
718,886
aiortc.rtcpeerconnection
close
Terminate the ICE agent, ending ICE processing and streams.
def addTransceiver( self, trackOrKind: Union[str, MediaStreamTrack], direction: str = "sendrecv" ) -> RTCRtpTransceiver: """ Add a new :class:`RTCRtpTransceiver`. """ self.__assertNotClosed() # determine track or kind if isinstance(trackOrKind, MediaStreamTrack): kind = trackOrKind.kind track = trackOrKind else: kind = trackOrKind track = None if kind not in ["audio", "video"]: raise InternalError(f'Invalid track kind "{kind}"') # check direction if direction not in sdp.DIRECTIONS: raise InternalError(f'Invalid direction "{direction}"') # don't add track twice if track: self.__assertTrackHasNoSender(track) return self.__createTransceiver( direction=direction, kind=kind, sender_track=track )
(self)
718,887
aiortc.rtcpeerconnection
createAnswer
Create an SDP answer to an offer received from a remote peer during the offer/answer negotiation of a WebRTC connection. :rtype: :class:`RTCSessionDescription`
def addTransceiver( self, trackOrKind: Union[str, MediaStreamTrack], direction: str = "sendrecv" ) -> RTCRtpTransceiver: """ Add a new :class:`RTCRtpTransceiver`. """ self.__assertNotClosed() # determine track or kind if isinstance(trackOrKind, MediaStreamTrack): kind = trackOrKind.kind track = trackOrKind else: kind = trackOrKind track = None if kind not in ["audio", "video"]: raise InternalError(f'Invalid track kind "{kind}"') # check direction if direction not in sdp.DIRECTIONS: raise InternalError(f'Invalid direction "{direction}"') # don't add track twice if track: self.__assertTrackHasNoSender(track) return self.__createTransceiver( direction=direction, kind=kind, sender_track=track )
(self)
718,888
aiortc.rtcpeerconnection
createDataChannel
Create a data channel with the given label. :rtype: :class:`RTCDataChannel`
def createDataChannel( self, label, maxPacketLifeTime=None, maxRetransmits=None, ordered=True, protocol="", negotiated=False, id=None, ): """ Create a data channel with the given label. :rtype: :class:`RTCDataChannel` """ if maxPacketLifeTime is not None and maxRetransmits is not None: raise ValueError("Cannot specify both maxPacketLifeTime and maxRetransmits") if not self.__sctp: self.__createSctpTransport() parameters = RTCDataChannelParameters( id=id, label=label, maxPacketLifeTime=maxPacketLifeTime, maxRetransmits=maxRetransmits, negotiated=negotiated, ordered=ordered, protocol=protocol, ) return RTCDataChannel(self.__sctp, parameters)
(self, label, maxPacketLifeTime=None, maxRetransmits=None, ordered=True, protocol='', negotiated=False, id=None)
718,889
aiortc.rtcpeerconnection
createOffer
Create an SDP offer for the purpose of starting a new WebRTC connection to a remote peer. :rtype: :class:`RTCSessionDescription`
def createDataChannel( self, label, maxPacketLifeTime=None, maxRetransmits=None, ordered=True, protocol="", negotiated=False, id=None, ): """ Create a data channel with the given label. :rtype: :class:`RTCDataChannel` """ if maxPacketLifeTime is not None and maxRetransmits is not None: raise ValueError("Cannot specify both maxPacketLifeTime and maxRetransmits") if not self.__sctp: self.__createSctpTransport() parameters = RTCDataChannelParameters( id=id, label=label, maxPacketLifeTime=maxPacketLifeTime, maxRetransmits=maxRetransmits, negotiated=negotiated, ordered=ordered, protocol=protocol, ) return RTCDataChannel(self.__sctp, parameters)
(self) -> aiortc.rtcsessiondescription.RTCSessionDescription
718,892
aiortc.rtcpeerconnection
getReceivers
Returns the list of :class:`RTCRtpReceiver` objects that are currently attached to the connection.
def getReceivers(self) -> List[RTCRtpReceiver]: """ Returns the list of :class:`RTCRtpReceiver` objects that are currently attached to the connection. """ return list(map(lambda x: x.receiver, self.__transceivers))
(self) -> List[aiortc.rtcrtpreceiver.RTCRtpReceiver]
718,893
aiortc.rtcpeerconnection
getSenders
Returns the list of :class:`RTCRtpSender` objects that are currently attached to the connection.
def getSenders(self) -> List[RTCRtpSender]: """ Returns the list of :class:`RTCRtpSender` objects that are currently attached to the connection. """ return list(map(lambda x: x.sender, self.__transceivers))
(self) -> List[aiortc.rtcrtpsender.RTCRtpSender]
718,894
aiortc.rtcpeerconnection
getStats
Returns statistics for the connection. :rtype: :class:`RTCStatsReport`
def getSenders(self) -> List[RTCRtpSender]: """ Returns the list of :class:`RTCRtpSender` objects that are currently attached to the connection. """ return list(map(lambda x: x.sender, self.__transceivers))
(self) -> aiortc.stats.RTCStatsReport
718,895
aiortc.rtcpeerconnection
getTransceivers
Returns the list of :class:`RTCRtpTransceiver` objects that are currently attached to the connection.
def getTransceivers(self) -> List[RTCRtpTransceiver]: """ Returns the list of :class:`RTCRtpTransceiver` objects that are currently attached to the connection. """ return list(self.__transceivers)
(self) -> List[aiortc.rtcrtptransceiver.RTCRtpTransceiver]
718,902
aiortc.rtcpeerconnection
setLocalDescription
Change the local description associated with the connection. :param sessionDescription: An :class:`RTCSessionDescription` generated by :meth:`createOffer` or :meth:`createAnswer()`.
def getTransceivers(self) -> List[RTCRtpTransceiver]: """ Returns the list of :class:`RTCRtpTransceiver` objects that are currently attached to the connection. """ return list(self.__transceivers)
(self, sessionDescription: aiortc.rtcsessiondescription.RTCSessionDescription) -> NoneType
718,903
aiortc.rtcpeerconnection
setRemoteDescription
Changes the remote description associated with the connection. :param sessionDescription: An :class:`RTCSessionDescription` created from information received over the signaling channel.
def getTransceivers(self) -> List[RTCRtpTransceiver]: """ Returns the list of :class:`RTCRtpTransceiver` objects that are currently attached to the connection. """ return list(self.__transceivers)
(self, sessionDescription: aiortc.rtcsessiondescription.RTCSessionDescription) -> NoneType
718,904
aiortc.stats
RTCRemoteInboundRtpStreamStats
The :class:`RTCRemoteInboundRtpStreamStats` dictionary represents the remote endpoint's measurement metrics for a particular incoming RTP stream.
class RTCRemoteInboundRtpStreamStats(RTCReceivedRtpStreamStats): """ The :class:`RTCRemoteInboundRtpStreamStats` dictionary represents the remote endpoint's measurement metrics for a particular incoming RTP stream. """ roundTripTime: float fractionLost: float
(timestamp: datetime.datetime, type: str, id: str, ssrc: int, kind: str, transportId: str, packetsReceived: int, packetsLost: int, jitter: int, roundTripTime: float, fractionLost: float) -> None
718,908
aiortc.stats
RTCRemoteOutboundRtpStreamStats
The :class:`RTCRemoteOutboundRtpStreamStats` dictionary represents the remote endpoint's measurement metrics for its outgoing RTP stream.
class RTCRemoteOutboundRtpStreamStats(RTCSentRtpStreamStats): """ The :class:`RTCRemoteOutboundRtpStreamStats` dictionary represents the remote endpoint's measurement metrics for its outgoing RTP stream. """ remoteTimestamp: Optional[datetime.datetime] = None
(timestamp: datetime.datetime, type: str, id: str, ssrc: int, kind: str, transportId: str, packetsSent: int, bytesSent: int, remoteTimestamp: Optional[datetime.datetime] = None) -> None
718,912
aiortc.rtcrtpparameters
RTCRtcpParameters
The :class:`RTCRtcpParameters` dictionary provides information on RTCP settings.
class RTCRtcpParameters: """ The :class:`RTCRtcpParameters` dictionary provides information on RTCP settings. """ cname: Optional[str] = None "The Canonical Name (CNAME) used by RTCP." mux: bool = False "Whether RTP and RTCP are multiplexed." ssrc: Optional[int] = None "The Synchronization Source identifier."
(cname: Optional[str] = None, mux: bool = False, ssrc: Optional[int] = None) -> None
718,913
aiortc.rtcrtpparameters
__eq__
null
from dataclasses import dataclass, field from typing import Dict, List, Optional, Union ParametersDict = Dict[str, Union[int, str, None]] @dataclass class RTCRtpCodecCapability: """ The :class:`RTCRtpCodecCapability` dictionary provides information on codec capabilities. """ mimeType: str "The codec MIME media type/subtype, for instance `'audio/PCMU'`." clockRate: int "The codec clock rate expressed in Hertz." channels: Optional[int] = None "The number of channels supported (e.g. two for stereo)." parameters: ParametersDict = field(default_factory=dict) "Codec-specific parameters available for signaling." @property def name(self): return self.mimeType.split("/")[1]
(self, other)
718,916
aiortc.rtcrtpparameters
RTCRtpCapabilities
The :class:`RTCRtpCapabilities` dictionary provides information about support codecs and header extensions.
class RTCRtpCapabilities: """ The :class:`RTCRtpCapabilities` dictionary provides information about support codecs and header extensions. """ codecs: List[RTCRtpCodecCapability] = field(default_factory=list) "A list of :class:`RTCRtpCodecCapability`." headerExtensions: List[RTCRtpHeaderExtensionCapability] = field( default_factory=list ) "A list of :class:`RTCRtpHeaderExtensionCapability`."
(codecs: List[aiortc.rtcrtpparameters.RTCRtpCodecCapability] = <factory>, headerExtensions: List[aiortc.rtcrtpparameters.RTCRtpHeaderExtensionCapability] = <factory>) -> None
718,920
aiortc.rtcrtpparameters
RTCRtpCodecCapability
The :class:`RTCRtpCodecCapability` dictionary provides information on codec capabilities.
class RTCRtpCodecCapability: """ The :class:`RTCRtpCodecCapability` dictionary provides information on codec capabilities. """ mimeType: str "The codec MIME media type/subtype, for instance `'audio/PCMU'`." clockRate: int "The codec clock rate expressed in Hertz." channels: Optional[int] = None "The number of channels supported (e.g. two for stereo)." parameters: ParametersDict = field(default_factory=dict) "Codec-specific parameters available for signaling." @property def name(self): return self.mimeType.split("/")[1]
(mimeType: str, clockRate: int, channels: Optional[int] = None, parameters: Dict[str, Union[int, str, NoneType]] = <factory>) -> None
718,924
aiortc.rtcrtpparameters
RTCRtpCodecParameters
The :class:`RTCRtpCodecParameters` dictionary provides information on codec settings.
class RTCRtpCodecParameters: """ The :class:`RTCRtpCodecParameters` dictionary provides information on codec settings. """ mimeType: str "The codec MIME media type/subtype, for instance `'audio/PCMU'`." clockRate: int "The codec clock rate expressed in Hertz." channels: Optional[int] = None "The number of channels supported (e.g. two for stereo)." payloadType: Optional[int] = None "The value that goes in the RTP Payload Type Field." rtcpFeedback: List["RTCRtcpFeedback"] = field(default_factory=list) "Transport layer and codec-specific feedback messages for this codec." parameters: ParametersDict = field(default_factory=dict) "Codec-specific parameters available for signaling." @property def name(self): return self.mimeType.split("/")[1] def __str__(self): s = f"{self.name}/{self.clockRate}" if self.channels == 2: s += "/2" return s
(mimeType: str, clockRate: int, channels: Optional[int] = None, payloadType: Optional[int] = None, rtcpFeedback: List[aiortc.rtcrtpparameters.RTCRtcpFeedback] = <factory>, parameters: Dict[str, Union[int, str, NoneType]] = <factory>) -> None
718,928
aiortc.rtcrtpparameters
__str__
null
def __str__(self): s = f"{self.name}/{self.clockRate}" if self.channels == 2: s += "/2" return s
(self)
718,929
aiortc.rtcrtpreceiver
RTCRtpContributingSource
The :class:`RTCRtpContributingSource` dictionary contains information about a contributing source (CSRC).
class RTCRtpContributingSource: """ The :class:`RTCRtpContributingSource` dictionary contains information about a contributing source (CSRC). """ timestamp: datetime.datetime "The timestamp associated with this source." source: int "The CSRC identifier associated with this source."
(timestamp: datetime.datetime, source: int) -> None
718,930
aiortc.rtcrtpreceiver
__eq__
null
import asyncio import datetime import logging import queue import random import threading import time from dataclasses import dataclass from typing import Callable, Dict, List, Optional, Set from av.frame import Frame from . import clock from .codecs import depayload, get_capabilities, get_decoder, is_rtx from .exceptions import InvalidStateError from .jitterbuffer import JitterBuffer from .mediastreams import MediaStreamError, MediaStreamTrack from .rate import RemoteBitrateEstimator from .rtcdtlstransport import RTCDtlsTransport from .rtcrtpparameters import ( RTCRtpCapabilities, RTCRtpCodecParameters, RTCRtpReceiveParameters, ) from .rtp import ( RTCP_PSFB_APP, RTCP_PSFB_PLI, RTCP_RTPFB_NACK, RTP_HISTORY_SIZE, AnyRtcpPacket, RtcpByePacket, RtcpPsfbPacket, RtcpReceiverInfo, RtcpRrPacket, RtcpRtpfbPacket, RtcpSrPacket, RtpPacket, clamp_packets_lost, pack_remb_fci, unwrap_rtx, ) from .stats import ( RTCInboundRtpStreamStats, RTCRemoteOutboundRtpStreamStats, RTCStatsReport, ) from .utils import uint16_add, uint16_gt logger = logging.getLogger(__name__) def decoder_worker(loop, input_q, output_q): codec_name = None decoder = None while True: task = input_q.get() if task is None: # inform the track that is has ended asyncio.run_coroutine_threadsafe(output_q.put(None), loop) break codec, encoded_frame = task if codec.name != codec_name: decoder = get_decoder(codec) codec_name = codec.name for frame in decoder.decode(encoded_frame): # pass the decoded frame to the track asyncio.run_coroutine_threadsafe(output_q.put(frame), loop) if decoder is not None: del decoder
(self, other)
718,932
aiortc.rtcrtpreceiver
__repr__
null
@dataclass class RTCRtpContributingSource: """ The :class:`RTCRtpContributingSource` dictionary contains information about a contributing source (CSRC). """ timestamp: datetime.datetime "The timestamp associated with this source." source: int "The CSRC identifier associated with this source."
(self)
718,933
aiortc.rtcrtpparameters
RTCRtpHeaderExtensionCapability
The :class:`RTCRtpHeaderExtensionCapability` dictionary provides information on a supported header extension.
class RTCRtpHeaderExtensionCapability: """ The :class:`RTCRtpHeaderExtensionCapability` dictionary provides information on a supported header extension. """ uri: str "The URI of the RTP header extension."
(uri: str) -> None
718,937
aiortc.rtcrtpparameters
RTCRtpHeaderExtensionParameters
The :class:`RTCRtpHeaderExtensionParameters` dictionary enables a header extension to be configured for use within an :class:`RTCRtpSender` or :class:`RTCRtpReceiver`.
class RTCRtpHeaderExtensionParameters: """ The :class:`RTCRtpHeaderExtensionParameters` dictionary enables a header extension to be configured for use within an :class:`RTCRtpSender` or :class:`RTCRtpReceiver`. """ id: int "The value that goes in the packet." uri: str "The URI of the RTP header extension."
(id: int, uri: str) -> None
718,941
aiortc.rtcrtpparameters
RTCRtpParameters
The :class:`RTCRtpParameters` dictionary describes the configuration of an :class:`RTCRtpReceiver` or an :class:`RTCRtpSender`.
class RTCRtpParameters: """ The :class:`RTCRtpParameters` dictionary describes the configuration of an :class:`RTCRtpReceiver` or an :class:`RTCRtpSender`. """ codecs: List[RTCRtpCodecParameters] = field(default_factory=list) "A list of :class:`RTCRtpCodecParameters` to send or receive." headerExtensions: List[RTCRtpHeaderExtensionParameters] = field( default_factory=list ) "A list of :class:`RTCRtpHeaderExtensionParameters`." muxId: str = "" "The muxId assigned to the RTP stream, if any, empty string if unset." rtcp: RTCRtcpParameters = field(default_factory=RTCRtcpParameters) "Parameters to configure RTCP."
(codecs: List[aiortc.rtcrtpparameters.RTCRtpCodecParameters] = <factory>, headerExtensions: List[aiortc.rtcrtpparameters.RTCRtpHeaderExtensionParameters] = <factory>, muxId: str = '', rtcp: aiortc.rtcrtpparameters.RTCRtcpParameters = <factory>) -> None
718,945
aiortc.rtcrtpreceiver
RTCRtpReceiver
The :class:`RTCRtpReceiver` interface manages the reception and decoding of data for a :class:`MediaStreamTrack`. :param kind: The kind of media (`'audio'` or `'video'`). :param transport: An :class:`RTCDtlsTransport`.
class RTCRtpReceiver: """ The :class:`RTCRtpReceiver` interface manages the reception and decoding of data for a :class:`MediaStreamTrack`. :param kind: The kind of media (`'audio'` or `'video'`). :param transport: An :class:`RTCDtlsTransport`. """ def __init__(self, kind: str, transport: RTCDtlsTransport) -> None: if transport.state == "closed": raise InvalidStateError self._enabled = True self.__active_ssrc: Dict[int, datetime.datetime] = {} self.__codecs: Dict[int, RTCRtpCodecParameters] = {} self.__decoder_queue: queue.Queue = queue.Queue() self.__decoder_thread: Optional[threading.Thread] = None self.__kind = kind if kind == "audio": self.__jitter_buffer = JitterBuffer(capacity=16, prefetch=4) self.__nack_generator = None self.__remote_bitrate_estimator = None else: self.__jitter_buffer = JitterBuffer(capacity=128, is_video=True) self.__nack_generator = NackGenerator() self.__remote_bitrate_estimator = RemoteBitrateEstimator() self._track: Optional[RemoteStreamTrack] = None self.__rtcp_exited = asyncio.Event() self.__rtcp_started = asyncio.Event() self.__rtcp_task: Optional[asyncio.Future[None]] = None self.__rtx_ssrc: Dict[int, int] = {} self.__started = False self.__stats = RTCStatsReport() self.__timestamp_mapper = TimestampMapper() self.__transport = transport # RTCP self.__lsr: Dict[int, int] = {} self.__lsr_time: Dict[int, float] = {} self.__remote_streams: Dict[int, StreamStatistics] = {} self.__rtcp_ssrc: Optional[int] = None # logging self.__log_debug: Callable[..., None] = lambda *args: None if logger.isEnabledFor(logging.DEBUG): self.__log_debug = lambda msg, *args: logger.debug( f"RTCRtpReceiver(%s) {msg}", self.__kind, *args ) @property def track(self) -> MediaStreamTrack: """ The :class:`MediaStreamTrack` which is being handled by the receiver. """ return self._track @property def transport(self) -> RTCDtlsTransport: """ The :class:`RTCDtlsTransport` over which the media for the receiver's track is received. """ return self.__transport @classmethod def getCapabilities(self, kind) -> Optional[RTCRtpCapabilities]: """ Returns the most optimistic view of the system's capabilities for receiving media of the given `kind`. :rtype: :class:`RTCRtpCapabilities` """ return get_capabilities(kind) async def getStats(self) -> RTCStatsReport: """ Returns statistics about the RTP receiver. :rtype: :class:`RTCStatsReport` """ for ssrc, stream in self.__remote_streams.items(): self.__stats.add( RTCInboundRtpStreamStats( # RTCStats timestamp=clock.current_datetime(), type="inbound-rtp", id="inbound-rtp_" + str(id(self)), # RTCStreamStats ssrc=ssrc, kind=self.__kind, transportId=self.transport._stats_id, # RTCReceivedRtpStreamStats packetsReceived=stream.packets_received, packetsLost=stream.packets_lost, jitter=stream.jitter, # RTPInboundRtpStreamStats ) ) self.__stats.update(self.transport._get_stats()) return self.__stats def getSynchronizationSources(self) -> List[RTCRtpSynchronizationSource]: """ Returns a :class:`RTCRtpSynchronizationSource` for each unique SSRC identifier received in the last 10 seconds. """ cutoff = clock.current_datetime() - datetime.timedelta(seconds=10) sources = [] for source, timestamp in self.__active_ssrc.items(): if timestamp >= cutoff: sources.append( RTCRtpSynchronizationSource(source=source, timestamp=timestamp) ) return sources async def receive(self, parameters: RTCRtpReceiveParameters) -> None: """ Attempt to set the parameters controlling the receiving of media. :param parameters: The :class:`RTCRtpParameters` for the receiver. """ if not self.__started: for codec in parameters.codecs: self.__codecs[codec.payloadType] = codec for encoding in parameters.encodings: if encoding.rtx: self.__rtx_ssrc[encoding.rtx.ssrc] = encoding.ssrc # start decoder thread self.__decoder_thread = threading.Thread( target=decoder_worker, name=self.__kind + "-decoder", args=( asyncio.get_event_loop(), self.__decoder_queue, self._track._queue, ), ) self.__decoder_thread.start() self.__transport._register_rtp_receiver(self, parameters) self.__rtcp_task = asyncio.ensure_future(self._run_rtcp()) self.__started = True def setTransport(self, transport: RTCDtlsTransport) -> None: self.__transport = transport async def stop(self) -> None: """ Irreversibly stop the receiver. """ if self.__started: self.__transport._unregister_rtp_receiver(self) self.__stop_decoder() # shutdown RTCP task await self.__rtcp_started.wait() self.__rtcp_task.cancel() await self.__rtcp_exited.wait() def _handle_disconnect(self) -> None: self.__stop_decoder() async def _handle_rtcp_packet(self, packet: AnyRtcpPacket) -> None: self.__log_debug("< %s", packet) if isinstance(packet, RtcpSrPacket): self.__stats.add( RTCRemoteOutboundRtpStreamStats( # RTCStats timestamp=clock.current_datetime(), type="remote-outbound-rtp", id=f"remote-outbound-rtp_{id(self)}", # RTCStreamStats ssrc=packet.ssrc, kind=self.__kind, transportId=self.transport._stats_id, # RTCSentRtpStreamStats packetsSent=packet.sender_info.packet_count, bytesSent=packet.sender_info.octet_count, # RTCRemoteOutboundRtpStreamStats remoteTimestamp=clock.datetime_from_ntp( packet.sender_info.ntp_timestamp ), ) ) self.__lsr[packet.ssrc] = ( (packet.sender_info.ntp_timestamp) >> 16 ) & 0xFFFFFFFF self.__lsr_time[packet.ssrc] = time.time() elif isinstance(packet, RtcpByePacket): self.__stop_decoder() async def _handle_rtp_packet(self, packet: RtpPacket, arrival_time_ms: int) -> None: """ Handle an incoming RTP packet. """ self.__log_debug("< %s", packet) # If the receiver is disabled, discard the packet. if not self._enabled: return # feed bitrate estimator if self.__remote_bitrate_estimator is not None: if packet.extensions.abs_send_time is not None: remb = self.__remote_bitrate_estimator.add( abs_send_time=packet.extensions.abs_send_time, arrival_time_ms=arrival_time_ms, payload_size=len(packet.payload) + packet.padding_size, ssrc=packet.ssrc, ) if self.__rtcp_ssrc is not None and remb is not None: # send Receiver Estimated Maximum Bitrate feedback rtcp_packet = RtcpPsfbPacket( fmt=RTCP_PSFB_APP, ssrc=self.__rtcp_ssrc, media_ssrc=0, fci=pack_remb_fci(*remb), ) await self._send_rtcp(rtcp_packet) # keep track of sources self.__active_ssrc[packet.ssrc] = clock.current_datetime() # check the codec is known codec = self.__codecs.get(packet.payload_type) if codec is None: self.__log_debug( "x RTP packet with unknown payload type %d", packet.payload_type ) return # feed RTCP statistics if packet.ssrc not in self.__remote_streams: self.__remote_streams[packet.ssrc] = StreamStatistics(codec.clockRate) self.__remote_streams[packet.ssrc].add(packet) # unwrap retransmission packet if is_rtx(codec): original_ssrc = self.__rtx_ssrc.get(packet.ssrc) if original_ssrc is None: self.__log_debug("x RTX packet from unknown SSRC %d", packet.ssrc) return if len(packet.payload) < 2: return codec = self.__codecs[codec.parameters["apt"]] packet = unwrap_rtx( packet, payload_type=codec.payloadType, ssrc=original_ssrc ) # send NACKs for any missing any packets if self.__nack_generator is not None and self.__nack_generator.add(packet): await self._send_rtcp_nack( packet.ssrc, sorted(self.__nack_generator.missing) ) # parse codec-specific information try: if packet.payload: packet._data = depayload(codec, packet.payload) # type: ignore else: packet._data = b"" # type: ignore except ValueError as exc: self.__log_debug("x RTP payload parsing failed: %s", exc) return # try to re-assemble encoded frame pli_flag, encoded_frame = self.__jitter_buffer.add(packet) # check if the PLI should be sent if pli_flag: await self._send_rtcp_pli(packet.ssrc) # if we have a complete encoded frame, decode it if encoded_frame is not None and self.__decoder_thread: encoded_frame.timestamp = self.__timestamp_mapper.map( encoded_frame.timestamp ) self.__decoder_queue.put((codec, encoded_frame)) async def _run_rtcp(self) -> None: self.__log_debug("- RTCP started") self.__rtcp_started.set() try: while True: # The interval between RTCP packets is varied randomly over the # range [0.5, 1.5] times the calculated interval. await asyncio.sleep(0.5 + random.random()) # RTCP RR reports = [] for ssrc, stream in self.__remote_streams.items(): lsr = 0 dlsr = 0 if ssrc in self.__lsr: lsr = self.__lsr[ssrc] delay = time.time() - self.__lsr_time[ssrc] if delay > 0 and delay < 65536: dlsr = int(delay * 65536) reports.append( RtcpReceiverInfo( ssrc=ssrc, fraction_lost=stream.fraction_lost, packets_lost=stream.packets_lost, highest_sequence=stream.max_seq, jitter=stream.jitter, lsr=lsr, dlsr=dlsr, ) ) if self.__rtcp_ssrc is not None and reports: packet = RtcpRrPacket(ssrc=self.__rtcp_ssrc, reports=reports) await self._send_rtcp(packet) except asyncio.CancelledError: pass self.__log_debug("- RTCP finished") self.__rtcp_exited.set() async def _send_rtcp(self, packet) -> None: self.__log_debug("> %s", packet) try: await self.transport._send_rtp(bytes(packet)) except ConnectionError: pass async def _send_rtcp_nack(self, media_ssrc: int, lost: List[int]) -> None: """ Send an RTCP packet to report missing RTP packets. """ if self.__rtcp_ssrc is not None: packet = RtcpRtpfbPacket( fmt=RTCP_RTPFB_NACK, ssrc=self.__rtcp_ssrc, media_ssrc=media_ssrc ) packet.lost = lost await self._send_rtcp(packet) async def _send_rtcp_pli(self, media_ssrc: int) -> None: """ Send an RTCP packet to report picture loss. """ if self.__rtcp_ssrc is not None: packet = RtcpPsfbPacket( fmt=RTCP_PSFB_PLI, ssrc=self.__rtcp_ssrc, media_ssrc=media_ssrc ) await self._send_rtcp(packet) def _set_rtcp_ssrc(self, ssrc: int) -> None: self.__rtcp_ssrc = ssrc def __stop_decoder(self) -> None: """ Stop the decoder thread, which will in turn stop the track. """ if self.__decoder_thread: self.__decoder_queue.put(None) self.__decoder_thread.join() self.__decoder_thread = None
(kind: str, transport: aiortc.rtcdtlstransport.RTCDtlsTransport) -> None
718,946
aiortc.rtcrtpreceiver
__stop_decoder
Stop the decoder thread, which will in turn stop the track.
def __stop_decoder(self) -> None: """ Stop the decoder thread, which will in turn stop the track. """ if self.__decoder_thread: self.__decoder_queue.put(None) self.__decoder_thread.join() self.__decoder_thread = None
(self) -> NoneType
718,947
aiortc.rtcrtpreceiver
__init__
null
def __init__(self, kind: str, transport: RTCDtlsTransport) -> None: if transport.state == "closed": raise InvalidStateError self._enabled = True self.__active_ssrc: Dict[int, datetime.datetime] = {} self.__codecs: Dict[int, RTCRtpCodecParameters] = {} self.__decoder_queue: queue.Queue = queue.Queue() self.__decoder_thread: Optional[threading.Thread] = None self.__kind = kind if kind == "audio": self.__jitter_buffer = JitterBuffer(capacity=16, prefetch=4) self.__nack_generator = None self.__remote_bitrate_estimator = None else: self.__jitter_buffer = JitterBuffer(capacity=128, is_video=True) self.__nack_generator = NackGenerator() self.__remote_bitrate_estimator = RemoteBitrateEstimator() self._track: Optional[RemoteStreamTrack] = None self.__rtcp_exited = asyncio.Event() self.__rtcp_started = asyncio.Event() self.__rtcp_task: Optional[asyncio.Future[None]] = None self.__rtx_ssrc: Dict[int, int] = {} self.__started = False self.__stats = RTCStatsReport() self.__timestamp_mapper = TimestampMapper() self.__transport = transport # RTCP self.__lsr: Dict[int, int] = {} self.__lsr_time: Dict[int, float] = {} self.__remote_streams: Dict[int, StreamStatistics] = {} self.__rtcp_ssrc: Optional[int] = None # logging self.__log_debug: Callable[..., None] = lambda *args: None if logger.isEnabledFor(logging.DEBUG): self.__log_debug = lambda msg, *args: logger.debug( f"RTCRtpReceiver(%s) {msg}", self.__kind, *args )
(self, kind: str, transport: aiortc.rtcdtlstransport.RTCDtlsTransport) -> NoneType
718,948
aiortc.rtcrtpreceiver
_handle_disconnect
null
def _handle_disconnect(self) -> None: self.__stop_decoder()
(self) -> NoneType
718,950
aiortc.rtcrtpreceiver
_handle_rtp_packet
Handle an incoming RTP packet.
def _handle_disconnect(self) -> None: self.__stop_decoder()
(self, packet: aiortc.rtp.RtpPacket, arrival_time_ms: int) -> NoneType
718,953
aiortc.rtcrtpreceiver
_send_rtcp_nack
Send an RTCP packet to report missing RTP packets.
def _handle_disconnect(self) -> None: self.__stop_decoder()
(self, media_ssrc: int, lost: List[int]) -> NoneType
718,954
aiortc.rtcrtpreceiver
_send_rtcp_pli
Send an RTCP packet to report picture loss.
def _handle_disconnect(self) -> None: self.__stop_decoder()
(self, media_ssrc: int) -> NoneType
718,955
aiortc.rtcrtpreceiver
_set_rtcp_ssrc
null
def _set_rtcp_ssrc(self, ssrc: int) -> None: self.__rtcp_ssrc = ssrc
(self, ssrc: int) -> NoneType
718,956
aiortc.rtcrtpreceiver
getStats
Returns statistics about the RTP receiver. :rtype: :class:`RTCStatsReport`
@classmethod def getCapabilities(self, kind) -> Optional[RTCRtpCapabilities]: """ Returns the most optimistic view of the system's capabilities for receiving media of the given `kind`. :rtype: :class:`RTCRtpCapabilities` """ return get_capabilities(kind)
(self) -> aiortc.stats.RTCStatsReport
718,957
aiortc.rtcrtpreceiver
getSynchronizationSources
Returns a :class:`RTCRtpSynchronizationSource` for each unique SSRC identifier received in the last 10 seconds.
def getSynchronizationSources(self) -> List[RTCRtpSynchronizationSource]: """ Returns a :class:`RTCRtpSynchronizationSource` for each unique SSRC identifier received in the last 10 seconds. """ cutoff = clock.current_datetime() - datetime.timedelta(seconds=10) sources = [] for source, timestamp in self.__active_ssrc.items(): if timestamp >= cutoff: sources.append( RTCRtpSynchronizationSource(source=source, timestamp=timestamp) ) return sources
(self) -> List[aiortc.rtcrtpreceiver.RTCRtpSynchronizationSource]
718,958
aiortc.rtcrtpreceiver
receive
Attempt to set the parameters controlling the receiving of media. :param parameters: The :class:`RTCRtpParameters` for the receiver.
def getSynchronizationSources(self) -> List[RTCRtpSynchronizationSource]: """ Returns a :class:`RTCRtpSynchronizationSource` for each unique SSRC identifier received in the last 10 seconds. """ cutoff = clock.current_datetime() - datetime.timedelta(seconds=10) sources = [] for source, timestamp in self.__active_ssrc.items(): if timestamp >= cutoff: sources.append( RTCRtpSynchronizationSource(source=source, timestamp=timestamp) ) return sources
(self, parameters: aiortc.rtcrtpparameters.RTCRtpReceiveParameters) -> NoneType
718,959
aiortc.rtcrtpreceiver
setTransport
null
def setTransport(self, transport: RTCDtlsTransport) -> None: self.__transport = transport
(self, transport: aiortc.rtcdtlstransport.RTCDtlsTransport) -> NoneType
718,960
aiortc.rtcrtpreceiver
stop
Irreversibly stop the receiver.
def setTransport(self, transport: RTCDtlsTransport) -> None: self.__transport = transport
(self) -> NoneType
718,961
aiortc.rtcrtpsender
RTCRtpSender
The :class:`RTCRtpSender` interface provides the ability to control and obtain details about how a particular :class:`MediaStreamTrack` is encoded and sent to a remote peer. :param trackOrKind: Either a :class:`MediaStreamTrack` instance or a media kind (`'audio'` or `'video'`). :param transport: An :class:`RTCDtlsTransport`.
class RTCRtpSender: """ The :class:`RTCRtpSender` interface provides the ability to control and obtain details about how a particular :class:`MediaStreamTrack` is encoded and sent to a remote peer. :param trackOrKind: Either a :class:`MediaStreamTrack` instance or a media kind (`'audio'` or `'video'`). :param transport: An :class:`RTCDtlsTransport`. """ def __init__(self, trackOrKind: Union[MediaStreamTrack, str], transport) -> None: if transport.state == "closed": raise InvalidStateError if isinstance(trackOrKind, MediaStreamTrack): self.__kind = trackOrKind.kind self.replaceTrack(trackOrKind) else: self.__kind = trackOrKind self.replaceTrack(None) self.__cname: Optional[str] = None self._ssrc = random32() self._rtx_ssrc = random32() # FIXME: how should this be initialised? self._stream_id = str(uuid.uuid4()) self._enabled = True self.__encoder: Optional[Encoder] = None self.__force_keyframe = False self.__loop = asyncio.get_event_loop() self.__mid: Optional[str] = None self.__rtp_exited = asyncio.Event() self.__rtp_header_extensions_map = rtp.HeaderExtensionsMap() self.__rtp_started = asyncio.Event() self.__rtp_task: Optional[asyncio.Future[None]] = None self.__rtp_history: Dict[int, RtpPacket] = {} self.__rtcp_exited = asyncio.Event() self.__rtcp_started = asyncio.Event() self.__rtcp_task: Optional[asyncio.Future[None]] = None self.__rtx_payload_type: Optional[int] = None self.__rtx_sequence_number = random16() self.__started = False self.__stats = RTCStatsReport() self.__transport = transport # stats self.__lsr: Optional[int] = None self.__lsr_time: Optional[float] = None self.__ntp_timestamp = 0 self.__rtp_timestamp = 0 self.__octet_count = 0 self.__packet_count = 0 self.__rtt = None # logging self.__log_debug: Callable[..., None] = lambda *args: None if logger.isEnabledFor(logging.DEBUG): self.__log_debug = lambda msg, *args: logger.debug( f"RTCRtpSender(%s) {msg}", self.__kind, *args ) @property def kind(self): return self.__kind @property def track(self) -> MediaStreamTrack: """ The :class:`MediaStreamTrack` which is being handled by the sender. """ return self.__track @property def transport(self): """ The :class:`RTCDtlsTransport` over which media data for the track is transmitted. """ return self.__transport @classmethod def getCapabilities(self, kind): """ Returns the most optimistic view of the system's capabilities for sending media of the given `kind`. :rtype: :class:`RTCRtpCapabilities` """ return get_capabilities(kind) async def getStats(self) -> RTCStatsReport: """ Returns statistics about the RTP sender. :rtype: :class:`RTCStatsReport` """ self.__stats.add( RTCOutboundRtpStreamStats( # RTCStats timestamp=clock.current_datetime(), type="outbound-rtp", id="outbound-rtp_" + str(id(self)), # RTCStreamStats ssrc=self._ssrc, kind=self.__kind, transportId=self.transport._stats_id, # RTCSentRtpStreamStats packetsSent=self.__packet_count, bytesSent=self.__octet_count, # RTCOutboundRtpStreamStats trackId=str(id(self.track)), ) ) self.__stats.update(self.transport._get_stats()) return self.__stats def replaceTrack(self, track: Optional[MediaStreamTrack]) -> None: self.__track = track if track is not None: self._track_id = track.id else: self._track_id = str(uuid.uuid4()) def setTransport(self, transport) -> None: self.__transport = transport async def send(self, parameters: RTCRtpSendParameters) -> None: """ Attempt to set the parameters controlling the sending of media. :param parameters: The :class:`RTCRtpSendParameters` for the sender. """ if not self.__started: self.__cname = parameters.rtcp.cname self.__mid = parameters.muxId # make note of the RTP header extension IDs self.__transport._register_rtp_sender(self, parameters) self.__rtp_header_extensions_map.configure(parameters) # make note of RTX payload type for codec in parameters.codecs: if ( is_rtx(codec) and codec.parameters["apt"] == parameters.codecs[0].payloadType ): self.__rtx_payload_type = codec.payloadType break self.__rtp_task = asyncio.ensure_future(self._run_rtp(parameters.codecs[0])) self.__rtcp_task = asyncio.ensure_future(self._run_rtcp()) self.__started = True async def stop(self): """ Irreversibly stop the sender. """ if self.__started: self.__transport._unregister_rtp_sender(self) # shutdown RTP and RTCP tasks await asyncio.gather(self.__rtp_started.wait(), self.__rtcp_started.wait()) self.__rtp_task.cancel() self.__rtcp_task.cancel() await asyncio.gather(self.__rtp_exited.wait(), self.__rtcp_exited.wait()) async def _handle_rtcp_packet(self, packet): if isinstance(packet, (RtcpRrPacket, RtcpSrPacket)): for report in filter(lambda x: x.ssrc == self._ssrc, packet.reports): # estimate round-trip time if self.__lsr == report.lsr and report.dlsr: rtt = time.time() - self.__lsr_time - (report.dlsr / 65536) if self.__rtt is None: self.__rtt = rtt else: self.__rtt = RTT_ALPHA * self.__rtt + (1 - RTT_ALPHA) * rtt self.__stats.add( RTCRemoteInboundRtpStreamStats( # RTCStats timestamp=clock.current_datetime(), type="remote-inbound-rtp", id="remote-inbound-rtp_" + str(id(self)), # RTCStreamStats ssrc=packet.ssrc, kind=self.__kind, transportId=self.transport._stats_id, # RTCReceivedRtpStreamStats packetsReceived=self.__packet_count - report.packets_lost, packetsLost=report.packets_lost, jitter=report.jitter, # RTCRemoteInboundRtpStreamStats roundTripTime=self.__rtt, fractionLost=report.fraction_lost, ) ) elif isinstance(packet, RtcpRtpfbPacket) and packet.fmt == RTCP_RTPFB_NACK: for seq in packet.lost: await self._retransmit(seq) elif isinstance(packet, RtcpPsfbPacket) and packet.fmt == RTCP_PSFB_PLI: self._send_keyframe() elif isinstance(packet, RtcpPsfbPacket) and packet.fmt == RTCP_PSFB_APP: try: bitrate, ssrcs = unpack_remb_fci(packet.fci) if self._ssrc in ssrcs: self.__log_debug( "- receiver estimated maximum bitrate %d bps", bitrate ) if self.__encoder and hasattr(self.__encoder, "target_bitrate"): self.__encoder.target_bitrate = bitrate except ValueError: pass async def _next_encoded_frame(self, codec: RTCRtpCodecParameters): # get [Frame|Packet] data = await self.__track.recv() # If the sender is disabled, drop the frame instead of encoding it. # We still want to read from the track in order to avoid frames # accumulating in memory. if not self._enabled: return None audio_level = None if self.__encoder is None: self.__encoder = get_encoder(codec) if isinstance(data, Frame): # encode frame if isinstance(data, AudioFrame): audio_level = rtp.compute_audio_level_dbov(data) force_keyframe = self.__force_keyframe self.__force_keyframe = False payloads, timestamp = await self.__loop.run_in_executor( None, self.__encoder.encode, data, force_keyframe ) else: payloads, timestamp = self.__encoder.pack(data) return RTCEncodedFrame(payloads, timestamp, audio_level) async def _retransmit(self, sequence_number: int) -> None: """ Retransmit an RTP packet which was reported as lost. """ packet = self.__rtp_history.get(sequence_number % RTP_HISTORY_SIZE) if packet and packet.sequence_number == sequence_number: if self.__rtx_payload_type is not None: packet = wrap_rtx( packet, payload_type=self.__rtx_payload_type, sequence_number=self.__rtx_sequence_number, ssrc=self._rtx_ssrc, ) self.__rtx_sequence_number = uint16_add(self.__rtx_sequence_number, 1) self.__log_debug("> %s", packet) packet_bytes = packet.serialize(self.__rtp_header_extensions_map) await self.transport._send_rtp(packet_bytes) def _send_keyframe(self) -> None: """ Request the next frame to be a keyframe. """ self.__force_keyframe = True async def _run_rtp(self, codec: RTCRtpCodecParameters) -> None: self.__log_debug("- RTP started") self.__rtp_started.set() sequence_number = random16() timestamp_origin = random32() try: while True: if not self.__track: await asyncio.sleep(0.02) continue # Fetch the next encoded frame. This can be `None` if the sender # is disabled, in which case we just continue the loop. enc_frame = await self._next_encoded_frame(codec) if enc_frame is None: continue timestamp = uint32_add(timestamp_origin, enc_frame.timestamp) for i, payload in enumerate(enc_frame.payloads): packet = RtpPacket( payload_type=codec.payloadType, sequence_number=sequence_number, timestamp=timestamp, ) packet.ssrc = self._ssrc packet.payload = payload packet.marker = (i == len(enc_frame.payloads) - 1) and 1 or 0 # set header extensions packet.extensions.abs_send_time = ( clock.current_ntp_time() >> 14 ) & 0x00FFFFFF packet.extensions.mid = self.__mid if enc_frame.audio_level is not None: packet.extensions.audio_level = (False, -enc_frame.audio_level) # send packet self.__log_debug("> %s", packet) self.__rtp_history[packet.sequence_number % RTP_HISTORY_SIZE] = ( packet ) packet_bytes = packet.serialize(self.__rtp_header_extensions_map) await self.transport._send_rtp(packet_bytes) self.__ntp_timestamp = clock.current_ntp_time() self.__rtp_timestamp = packet.timestamp self.__octet_count += len(payload) self.__packet_count += 1 sequence_number = uint16_add(sequence_number, 1) except (asyncio.CancelledError, ConnectionError, MediaStreamError): pass except Exception: # we *need* to set __rtp_exited, otherwise RTCRtpSender.stop() will hang, # so issue a warning if we hit an unexpected exception self.__log_warning(traceback.format_exc()) # stop track if self.__track: self.__track.stop() self.__track = None # release encoder if self.__encoder: del self.__encoder self.__log_debug("- RTP finished") self.__rtp_exited.set() async def _run_rtcp(self) -> None: self.__log_debug("- RTCP started") self.__rtcp_started.set() try: while True: # The interval between RTCP packets is varied randomly over the # range [0.5, 1.5] times the calculated interval. await asyncio.sleep(0.5 + random.random()) # RTCP SR packets: List[AnyRtcpPacket] = [ RtcpSrPacket( ssrc=self._ssrc, sender_info=RtcpSenderInfo( ntp_timestamp=self.__ntp_timestamp, rtp_timestamp=self.__rtp_timestamp, packet_count=self.__packet_count, octet_count=self.__octet_count, ), ) ] self.__lsr = ((self.__ntp_timestamp) >> 16) & 0xFFFFFFFF self.__lsr_time = time.time() # RTCP SDES if self.__cname is not None: packets.append( RtcpSdesPacket( chunks=[ RtcpSourceInfo( ssrc=self._ssrc, items=[(1, self.__cname.encode("utf8"))], ) ] ) ) await self._send_rtcp(packets) except asyncio.CancelledError: pass # RTCP BYE packet = RtcpByePacket(sources=[self._ssrc]) await self._send_rtcp([packet]) self.__log_debug("- RTCP finished") self.__rtcp_exited.set() async def _send_rtcp(self, packets: List[AnyRtcpPacket]) -> None: payload = b"" for packet in packets: self.__log_debug("> %s", packet) payload += bytes(packet) try: await self.transport._send_rtp(payload) except ConnectionError: pass def __log_warning(self, msg: str, *args) -> None: logger.warning(f"RTCRtpsender(%s) {msg}", self.__kind, *args)
(trackOrKind: Union[aiortc.mediastreams.MediaStreamTrack, str], transport) -> None
718,962
aiortc.rtcrtpsender
__log_warning
null
def __log_warning(self, msg: str, *args) -> None: logger.warning(f"RTCRtpsender(%s) {msg}", self.__kind, *args)
(self, msg: str, *args) -> NoneType
718,963
aiortc.rtcrtpsender
__init__
null
def __init__(self, trackOrKind: Union[MediaStreamTrack, str], transport) -> None: if transport.state == "closed": raise InvalidStateError if isinstance(trackOrKind, MediaStreamTrack): self.__kind = trackOrKind.kind self.replaceTrack(trackOrKind) else: self.__kind = trackOrKind self.replaceTrack(None) self.__cname: Optional[str] = None self._ssrc = random32() self._rtx_ssrc = random32() # FIXME: how should this be initialised? self._stream_id = str(uuid.uuid4()) self._enabled = True self.__encoder: Optional[Encoder] = None self.__force_keyframe = False self.__loop = asyncio.get_event_loop() self.__mid: Optional[str] = None self.__rtp_exited = asyncio.Event() self.__rtp_header_extensions_map = rtp.HeaderExtensionsMap() self.__rtp_started = asyncio.Event() self.__rtp_task: Optional[asyncio.Future[None]] = None self.__rtp_history: Dict[int, RtpPacket] = {} self.__rtcp_exited = asyncio.Event() self.__rtcp_started = asyncio.Event() self.__rtcp_task: Optional[asyncio.Future[None]] = None self.__rtx_payload_type: Optional[int] = None self.__rtx_sequence_number = random16() self.__started = False self.__stats = RTCStatsReport() self.__transport = transport # stats self.__lsr: Optional[int] = None self.__lsr_time: Optional[float] = None self.__ntp_timestamp = 0 self.__rtp_timestamp = 0 self.__octet_count = 0 self.__packet_count = 0 self.__rtt = None # logging self.__log_debug: Callable[..., None] = lambda *args: None if logger.isEnabledFor(logging.DEBUG): self.__log_debug = lambda msg, *args: logger.debug( f"RTCRtpSender(%s) {msg}", self.__kind, *args )
(self, trackOrKind: Union[aiortc.mediastreams.MediaStreamTrack, str], transport) -> NoneType
718,964
aiortc.rtcrtpsender
_handle_rtcp_packet
null
def setTransport(self, transport) -> None: self.__transport = transport
(self, packet)
718,965
aiortc.rtcrtpsender
_next_encoded_frame
null
for report in filter(lambda x: x.ssrc == self._ssrc, packet.reports):
(self, codec: aiortc.rtcrtpparameters.RTCRtpCodecParameters)
718,966
aiortc.rtcrtpsender
_retransmit
Retransmit an RTP packet which was reported as lost.
for report in filter(lambda x: x.ssrc == self._ssrc, packet.reports):
(self, sequence_number: int) -> NoneType
718,967
aiortc.rtcrtpsender
_run_rtcp
null
def _send_keyframe(self) -> None: """ Request the next frame to be a keyframe. """ self.__force_keyframe = True
(self) -> NoneType
718,969
aiortc.rtcrtpsender
_send_keyframe
Request the next frame to be a keyframe.
def _send_keyframe(self) -> None: """ Request the next frame to be a keyframe. """ self.__force_keyframe = True
(self) -> NoneType
718,971
aiortc.rtcrtpsender
getStats
Returns statistics about the RTP sender. :rtype: :class:`RTCStatsReport`
@classmethod def getCapabilities(self, kind): """ Returns the most optimistic view of the system's capabilities for sending media of the given `kind`. :rtype: :class:`RTCRtpCapabilities` """ return get_capabilities(kind)
(self) -> aiortc.stats.RTCStatsReport
718,972
aiortc.rtcrtpsender
replaceTrack
null
def replaceTrack(self, track: Optional[MediaStreamTrack]) -> None: self.__track = track if track is not None: self._track_id = track.id else: self._track_id = str(uuid.uuid4())
(self, track: Optional[aiortc.mediastreams.MediaStreamTrack]) -> NoneType
718,973
aiortc.rtcrtpsender
send
Attempt to set the parameters controlling the sending of media. :param parameters: The :class:`RTCRtpSendParameters` for the sender.
def setTransport(self, transport) -> None: self.__transport = transport
(self, parameters: aiortc.rtcrtpparameters.RTCRtpSendParameters) -> NoneType
718,975
aiortc.rtcrtpsender
stop
Irreversibly stop the sender.
def setTransport(self, transport) -> None: self.__transport = transport
(self)
718,976
aiortc.rtcrtpreceiver
RTCRtpSynchronizationSource
The :class:`RTCRtpSynchronizationSource` dictionary contains information about a synchronization source (SSRC).
class RTCRtpSynchronizationSource: """ The :class:`RTCRtpSynchronizationSource` dictionary contains information about a synchronization source (SSRC). """ timestamp: datetime.datetime "The timestamp associated with this source." source: int "The SSRC identifier associated with this source."
(timestamp: datetime.datetime, source: int) -> None
718,980
aiortc.rtcrtptransceiver
RTCRtpTransceiver
The RTCRtpTransceiver interface describes a permanent pairing of an :class:`RTCRtpSender` and an :class:`RTCRtpReceiver`, along with some shared state.
class RTCRtpTransceiver: """ The RTCRtpTransceiver interface describes a permanent pairing of an :class:`RTCRtpSender` and an :class:`RTCRtpReceiver`, along with some shared state. """ def __init__( self, kind: str, receiver: RTCRtpReceiver, sender: RTCRtpSender, direction: str = "sendrecv", ): self.__currentDirection: Optional[str] = None self.__direction = direction self.__kind = kind self.__mid: Optional[str] = None self.__mline_index: Optional[int] = None self.__receiver = receiver self.__sender = sender self.__stopped = False self._offerDirection: Optional[str] = None self._preferred_codecs: List[RTCRtpCodecCapability] = [] self._transport: RTCDtlsTransport = None # FIXME: this is only used by RTCPeerConnection self._bundled = False self._codecs: List[RTCRtpCodecParameters] = [] self._headerExtensions: List[RTCRtpHeaderExtensionParameters] = [] @property def currentDirection(self) -> Optional[str]: """ The currently negotiated direction of the transceiver. One of `'sendrecv'`, `'sendonly'`, `'recvonly'`, `'inactive'` or `None`. """ return self.__currentDirection @property def direction(self) -> str: """ The preferred direction of the transceiver, which will be used in :meth:`RTCPeerConnection.createOffer` and :meth:`RTCPeerConnection.createAnswer`. One of `'sendrecv'`, `'sendonly'`, `'recvonly'` or `'inactive'`. """ return self.__direction @direction.setter def direction(self, direction: str) -> None: assert direction in DIRECTIONS self.__direction = direction @property def kind(self) -> str: return self.__kind @property def mid(self) -> Optional[str]: return self.__mid @property def receiver(self) -> RTCRtpReceiver: """ The :class:`RTCRtpReceiver` that handles receiving and decoding incoming media. """ return self.__receiver @property def sender(self) -> RTCRtpSender: """ The :class:`RTCRtpSender` responsible for encoding and sending data to the remote peer. """ return self.__sender @property def stopped(self) -> bool: return self.__stopped def setCodecPreferences(self, codecs: List[RTCRtpCodecCapability]) -> None: """ Override the default codec preferences. See :meth:`RTCRtpSender.getCapabilities` and :meth:`RTCRtpReceiver.getCapabilities` for the supported codecs. :param codecs: A list of :class:`RTCRtpCodecCapability`, in decreasing order of preference. If empty, restores the default preferences. """ if not codecs: self._preferred_codecs = [] capabilities = get_capabilities(self.kind).codecs unique: List[RTCRtpCodecCapability] = [] for codec in reversed(codecs): if codec not in capabilities: raise ValueError("Codec is not in capabilities") if codec not in unique: unique.insert(0, codec) self._preferred_codecs = unique async def stop(self): """ Permanently stops the :class:`RTCRtpTransceiver`. """ await self.__receiver.stop() await self.__sender.stop() self.__stopped = True def _setCurrentDirection(self, direction: str) -> None: self.__currentDirection = direction if direction == "sendrecv": self.__sender._enabled = True self.__receiver._enabled = True elif direction == "sendonly": self.__sender._enabled = True self.__receiver._enabled = False elif direction == "recvonly": self.__sender._enabled = False self.__receiver._enabled = True elif direction == "inactive": self.__sender._enabled = False self.__receiver._enabled = False def _set_mid(self, mid: str) -> None: self.__mid = mid def _get_mline_index(self) -> Optional[int]: return self.__mline_index def _set_mline_index(self, idx: int) -> None: self.__mline_index = idx
(kind: str, receiver: aiortc.rtcrtpreceiver.RTCRtpReceiver, sender: aiortc.rtcrtpsender.RTCRtpSender, direction: str = 'sendrecv')
718,981
aiortc.rtcrtptransceiver
__init__
null
def __init__( self, kind: str, receiver: RTCRtpReceiver, sender: RTCRtpSender, direction: str = "sendrecv", ): self.__currentDirection: Optional[str] = None self.__direction = direction self.__kind = kind self.__mid: Optional[str] = None self.__mline_index: Optional[int] = None self.__receiver = receiver self.__sender = sender self.__stopped = False self._offerDirection: Optional[str] = None self._preferred_codecs: List[RTCRtpCodecCapability] = [] self._transport: RTCDtlsTransport = None # FIXME: this is only used by RTCPeerConnection self._bundled = False self._codecs: List[RTCRtpCodecParameters] = [] self._headerExtensions: List[RTCRtpHeaderExtensionParameters] = []
(self, kind: str, receiver: aiortc.rtcrtpreceiver.RTCRtpReceiver, sender: aiortc.rtcrtpsender.RTCRtpSender, direction: str = 'sendrecv')
718,982
aiortc.rtcrtptransceiver
_get_mline_index
null
def _get_mline_index(self) -> Optional[int]: return self.__mline_index
(self) -> Optional[int]
718,983
aiortc.rtcrtptransceiver
_setCurrentDirection
null
def _setCurrentDirection(self, direction: str) -> None: self.__currentDirection = direction if direction == "sendrecv": self.__sender._enabled = True self.__receiver._enabled = True elif direction == "sendonly": self.__sender._enabled = True self.__receiver._enabled = False elif direction == "recvonly": self.__sender._enabled = False self.__receiver._enabled = True elif direction == "inactive": self.__sender._enabled = False self.__receiver._enabled = False
(self, direction: str) -> NoneType
718,984
aiortc.rtcrtptransceiver
_set_mid
null
def _set_mid(self, mid: str) -> None: self.__mid = mid
(self, mid: str) -> NoneType
718,985
aiortc.rtcrtptransceiver
_set_mline_index
null
def _set_mline_index(self, idx: int) -> None: self.__mline_index = idx
(self, idx: int) -> NoneType
718,986
aiortc.rtcrtptransceiver
setCodecPreferences
Override the default codec preferences. See :meth:`RTCRtpSender.getCapabilities` and :meth:`RTCRtpReceiver.getCapabilities` for the supported codecs. :param codecs: A list of :class:`RTCRtpCodecCapability`, in decreasing order of preference. If empty, restores the default preferences.
def setCodecPreferences(self, codecs: List[RTCRtpCodecCapability]) -> None: """ Override the default codec preferences. See :meth:`RTCRtpSender.getCapabilities` and :meth:`RTCRtpReceiver.getCapabilities` for the supported codecs. :param codecs: A list of :class:`RTCRtpCodecCapability`, in decreasing order of preference. If empty, restores the default preferences. """ if not codecs: self._preferred_codecs = [] capabilities = get_capabilities(self.kind).codecs unique: List[RTCRtpCodecCapability] = [] for codec in reversed(codecs): if codec not in capabilities: raise ValueError("Codec is not in capabilities") if codec not in unique: unique.insert(0, codec) self._preferred_codecs = unique
(self, codecs: List[aiortc.rtcrtpparameters.RTCRtpCodecCapability]) -> NoneType
718,987
aiortc.rtcrtptransceiver
stop
Permanently stops the :class:`RTCRtpTransceiver`.
def setCodecPreferences(self, codecs: List[RTCRtpCodecCapability]) -> None: """ Override the default codec preferences. See :meth:`RTCRtpSender.getCapabilities` and :meth:`RTCRtpReceiver.getCapabilities` for the supported codecs. :param codecs: A list of :class:`RTCRtpCodecCapability`, in decreasing order of preference. If empty, restores the default preferences. """ if not codecs: self._preferred_codecs = [] capabilities = get_capabilities(self.kind).codecs unique: List[RTCRtpCodecCapability] = [] for codec in reversed(codecs): if codec not in capabilities: raise ValueError("Codec is not in capabilities") if codec not in unique: unique.insert(0, codec) self._preferred_codecs = unique
(self)
718,988
aiortc.rtcsctptransport
RTCSctpCapabilities
The :class:`RTCSctpCapabilities` dictionary provides information about the capabilities of the :class:`RTCSctpTransport`.
class RTCSctpCapabilities: """ The :class:`RTCSctpCapabilities` dictionary provides information about the capabilities of the :class:`RTCSctpTransport`. """ maxMessageSize: int """ The maximum size of data that the implementation can send or 0 if the implementation can handle messages of any size. """
(maxMessageSize: int) -> None
718,989
aiortc.rtcsctptransport
__eq__
null
import asyncio import enum import hmac import logging import math import os import time from collections import deque from dataclasses import dataclass, field from struct import pack, unpack_from from typing import ( Any, Callable, Deque, Dict, Iterator, List, Optional, Set, Tuple, cast, no_type_check, ) from google_crc32c import value as crc32c from pyee.asyncio import AsyncIOEventEmitter from .exceptions import InvalidStateError from .rtcdatachannel import RTCDataChannel, RTCDataChannelParameters from .rtcdtlstransport import RTCDtlsTransport from .utils import random32, uint16_add, uint16_gt, uint32_gt, uint32_gte logger = logging.getLogger(__name__) # local constants COOKIE_LENGTH = 24 COOKIE_LIFETIME = 60 MAX_STREAMS = 65535 USERDATA_MAX_LENGTH = 1200 # protocol constants SCTP_CAUSE_INVALID_STREAM = 0x0001 SCTP_CAUSE_STALE_COOKIE = 0x0003 SCTP_DATA_LAST_FRAG = 0x01 SCTP_DATA_FIRST_FRAG = 0x02 SCTP_DATA_UNORDERED = 0x04 SCTP_MAX_ASSOCIATION_RETRANS = 10 SCTP_MAX_BURST = 4 SCTP_MAX_INIT_RETRANS = 8 SCTP_RTO_ALPHA = 1 / 8 SCTP_RTO_BETA = 1 / 4 SCTP_RTO_INITIAL = 3.0 SCTP_RTO_MIN = 1 SCTP_RTO_MAX = 60 SCTP_TSN_MODULO = 2**32 RECONFIG_MAX_STREAMS = 135 # parameters SCTP_STATE_COOKIE = 0x0007 SCTP_STR_RESET_OUT_REQUEST = 0x000D SCTP_STR_RESET_RESPONSE = 0x0010 SCTP_STR_RESET_ADD_OUT_STREAMS = 0x0011 SCTP_SUPPORTED_CHUNK_EXT = 0x8008 SCTP_PRSCTP_SUPPORTED = 0xC000 # data channel constants DATA_CHANNEL_ACK = 2 DATA_CHANNEL_OPEN = 3 DATA_CHANNEL_RELIABLE = 0x00 DATA_CHANNEL_PARTIAL_RELIABLE_REXMIT = 0x01 DATA_CHANNEL_PARTIAL_RELIABLE_TIMED = 0x02 DATA_CHANNEL_RELIABLE_UNORDERED = 0x80 DATA_CHANNEL_PARTIAL_RELIABLE_REXMIT_UNORDERED = 0x81 DATA_CHANNEL_PARTIAL_RELIABLE_TIMED_UNORDERED = 0x82 WEBRTC_DCEP = 50 WEBRTC_STRING = 51 WEBRTC_BINARY = 53 WEBRTC_STRING_EMPTY = 56 WEBRTC_BINARY_EMPTY = 57 def chunk_type(chunk) -> str: return chunk.__class__.__name__
(self, other)
718,991
aiortc.rtcsctptransport
__repr__
null
@property def body(self) -> bytes: # type: ignore body = pack("!L", self.cumulative_tsn) for stream_id, stream_seq in self.streams: body += pack("!HH", stream_id, stream_seq) return body
(self)
718,992
aiortc.rtcsctptransport
RTCSctpTransport
The :class:`RTCSctpTransport` interface includes information relating to Stream Control Transmission Protocol (SCTP) transport. :param transport: An :class:`RTCDtlsTransport`.
class RTCSctpTransport(AsyncIOEventEmitter): """ The :class:`RTCSctpTransport` interface includes information relating to Stream Control Transmission Protocol (SCTP) transport. :param transport: An :class:`RTCDtlsTransport`. """ def __init__(self, transport: RTCDtlsTransport, port: int = 5000) -> None: if transport.state == "closed": raise InvalidStateError super().__init__() self._association_state = self.State.CLOSED self.__log_debug: Callable[..., None] = lambda *args: None self.__started = False self.__state = "new" self.__transport = transport self._loop = asyncio.get_event_loop() self._hmac_key = os.urandom(16) self._local_partial_reliability = True self._local_port = port self._local_verification_tag = random32() self._remote_extensions: List[int] = [] self._remote_partial_reliability = False self._remote_port: Optional[int] = None self._remote_verification_tag = 0 # inbound self._advertised_rwnd = 1024 * 1024 self._inbound_streams: Dict[int, InboundStream] = {} self._inbound_streams_count = 0 self._inbound_streams_max = MAX_STREAMS self._last_received_tsn: Optional[int] = None self._sack_duplicates: List[int] = [] self._sack_misordered: Set[int] = set() self._sack_needed = False # outbound self._cwnd = 3 * USERDATA_MAX_LENGTH self._fast_recovery_exit = None self._fast_recovery_transmit = False self._forward_tsn_chunk: Optional[ForwardTsnChunk] = None self._flight_size = 0 self._local_tsn = random32() self._last_sacked_tsn = tsn_minus_one(self._local_tsn) self._advanced_peer_ack_tsn = tsn_minus_one(self._local_tsn) self._outbound_queue: Deque[DataChunk] = deque() self._outbound_stream_seq: Dict[int, int] = {} self._outbound_streams_count = MAX_STREAMS self._partial_bytes_acked = 0 self._sent_queue: Deque[DataChunk] = deque() # reconfiguration self._reconfig_queue: List[int] = [] self._reconfig_request = None self._reconfig_request_seq = self._local_tsn self._reconfig_response_seq = 0 # rtt calculation self._srtt: Optional[float] = None self._rttvar: Optional[float] = None # timers self._rto = SCTP_RTO_INITIAL self._t1_chunk: Optional[Chunk] = None self._t1_failures = 0 self._t1_handle: Optional[asyncio.TimerHandle] = None self._t2_chunk: Optional[Chunk] = None self._t2_failures = 0 self._t2_handle: Optional[asyncio.TimerHandle] = None self._t3_handle: Optional[asyncio.TimerHandle] = None # data channels self._data_channel_id: Optional[int] = None self._data_channel_queue: Deque[Tuple[RTCDataChannel, int, bytes]] = deque() self._data_channels: Dict[int, RTCDataChannel] = {} # FIXME: this is only used by RTCPeerConnection self._bundled = False self.mid: Optional[str] = None @property def is_server(self) -> bool: return self.transport.transport.role != "controlling" @property def maxChannels(self) -> Optional[int]: """ The maximum number of :class:`RTCDataChannel` that can be used simultaneously. """ if self._inbound_streams_count: return min(self._inbound_streams_count, self._outbound_streams_count) return None @property def port(self) -> int: """ The local SCTP port number used for data channels. """ return self._local_port @property def state(self) -> str: """ The current state of the SCTP transport. """ return self.__state @property def transport(self): """ The :class:`RTCDtlsTransport` over which SCTP data is transmitted. """ return self.__transport @classmethod def getCapabilities(cls) -> RTCSctpCapabilities: """ Retrieve the capabilities of the transport. :rtype: RTCSctpCapabilities """ return RTCSctpCapabilities(maxMessageSize=65536) def setTransport(self, transport) -> None: self.__transport = transport async def start(self, remoteCaps: RTCSctpCapabilities, remotePort: int) -> None: """ Start the transport. """ if not self.__started: self.__started = True self.__state = "connecting" self._remote_port = remotePort # configure logging if logger.isEnabledFor(logging.DEBUG): prefix = "RTCSctpTransport(%s) " % ( self.is_server and "server" or "client" ) self.__log_debug = lambda msg, *args: logger.debug(prefix + msg, *args) # initialise local channel ID counter # one side should be using even IDs, the other odd IDs if self.is_server: self._data_channel_id = 0 else: self._data_channel_id = 1 self.__transport._register_data_receiver(self) if not self.is_server: await self._init() async def stop(self) -> None: """ Stop the transport. """ if self._association_state != self.State.CLOSED: await self._abort() self.__transport._unregister_data_receiver(self) self._set_state(self.State.CLOSED) async def _abort(self) -> None: """ Abort the association. """ chunk = AbortChunk() try: await self._send_chunk(chunk) except ConnectionError: pass async def _init(self) -> None: """ Initialize the association. """ chunk = InitChunk() chunk.initiate_tag = self._local_verification_tag chunk.advertised_rwnd = self._advertised_rwnd chunk.outbound_streams = self._outbound_streams_count chunk.inbound_streams = self._inbound_streams_max chunk.initial_tsn = self._local_tsn self._set_extensions(chunk.params) await self._send_chunk(chunk) # start T1 timer and enter COOKIE-WAIT state self._t1_start(chunk) self._set_state(self.State.COOKIE_WAIT) def _flight_size_decrease(self, chunk: DataChunk) -> None: self._flight_size = max(0, self._flight_size - chunk._book_size) # type: ignore def _flight_size_increase(self, chunk: DataChunk) -> None: self._flight_size += chunk._book_size # type: ignore def _get_extensions(self, params: List[Tuple[int, bytes]]) -> None: """ Gets what extensions are supported by the remote party. """ for k, v in params: if k == SCTP_PRSCTP_SUPPORTED: self._remote_partial_reliability = True elif k == SCTP_SUPPORTED_CHUNK_EXT: self._remote_extensions = list(v) def _set_extensions(self, params: List[Tuple[int, bytes]]) -> None: """ Sets what extensions are supported by the local party. """ extensions = [] if self._local_partial_reliability: params.append((SCTP_PRSCTP_SUPPORTED, b"")) extensions.append(ForwardTsnChunk.type) extensions.append(ReconfigChunk.type) params.append((SCTP_SUPPORTED_CHUNK_EXT, bytes(extensions))) def _get_inbound_stream(self, stream_id: int) -> InboundStream: """ Get or create the inbound stream with the specified ID. """ if stream_id not in self._inbound_streams: self._inbound_streams[stream_id] = InboundStream() return self._inbound_streams[stream_id] def _get_timestamp(self) -> int: return int(time.time()) async def _handle_data(self, data): """ Handle data received from the network. """ try: _, _, verification_tag, chunks = parse_packet(data) except ValueError: return # is this an init? init_chunk = len([x for x in chunks if isinstance(x, InitChunk)]) if init_chunk: assert len(chunks) == 1 expected_tag = 0 else: expected_tag = self._local_verification_tag # verify tag if verification_tag != expected_tag: self.__log_debug( "Bad verification tag %d vs %d", verification_tag, expected_tag ) return # handle chunks for chunk in chunks: await self._receive_chunk(chunk) # send SACK if needed if self._sack_needed: await self._send_sack() @no_type_check def _maybe_abandon(self, chunk: DataChunk) -> bool: """ Determine if a chunk needs to be marked as abandoned. If it does, it marks the chunk and any other chunk belong to the same message as abandoned. """ if chunk._abandoned: return True abandon = ( chunk._max_retransmits is not None and chunk._sent_count > chunk._max_retransmits ) or (chunk._expiry is not None and chunk._expiry < time.time()) if not abandon: return False chunk_pos = self._sent_queue.index(chunk) for pos in range(chunk_pos, -1, -1): ochunk = self._sent_queue[pos] ochunk._abandoned = True ochunk._retransmit = False if ochunk.flags & SCTP_DATA_FIRST_FRAG: break for pos in range(chunk_pos, len(self._sent_queue)): ochunk = self._sent_queue[pos] ochunk._abandoned = True ochunk._retransmit = False if ochunk.flags & SCTP_DATA_LAST_FRAG: break return True def _mark_received(self, tsn: int) -> bool: """ Mark an incoming data TSN as received. """ # it's a duplicate if uint32_gte(self._last_received_tsn, tsn) or tsn in self._sack_misordered: self._sack_duplicates.append(tsn) return True # consolidate misordered entries self._sack_misordered.add(tsn) for tsn in sorted(self._sack_misordered): if tsn == tsn_plus_one(self._last_received_tsn): self._last_received_tsn = tsn else: break # filter out obsolete entries def is_obsolete(x): return uint32_gt(x, self._last_received_tsn) self._sack_duplicates = list(filter(is_obsolete, self._sack_duplicates)) self._sack_misordered = set(filter(is_obsolete, self._sack_misordered)) return False async def _receive(self, stream_id: int, pp_id: int, data: bytes) -> None: """ Receive data stream -> ULP. """ await self._data_channel_receive(stream_id, pp_id, data) async def _receive_chunk(self, chunk): """ Handle an incoming chunk. """ self.__log_debug("< %s", chunk) # common if isinstance(chunk, DataChunk): await self._receive_data_chunk(chunk) elif isinstance(chunk, SackChunk): await self._receive_sack_chunk(chunk) elif isinstance(chunk, ForwardTsnChunk): await self._receive_forward_tsn_chunk(chunk) elif isinstance(chunk, HeartbeatChunk): ack = HeartbeatAckChunk() ack.params = chunk.params await self._send_chunk(ack) elif isinstance(chunk, AbortChunk): self.__log_debug("x Association was aborted by remote party") self._set_state(self.State.CLOSED) elif isinstance(chunk, ShutdownChunk): self._t2_cancel() self._set_state(self.State.SHUTDOWN_RECEIVED) ack = ShutdownAckChunk() await self._send_chunk(ack) self._t2_start(ack) self._set_state(self.State.SHUTDOWN_ACK_SENT) elif ( isinstance(chunk, ShutdownCompleteChunk) and self._association_state == self.State.SHUTDOWN_ACK_SENT ): self._t2_cancel() self._set_state(self.State.CLOSED) elif ( isinstance(chunk, ReconfigChunk) and self._association_state == self.State.ESTABLISHED ): for param in chunk.params: cls = RECONFIG_PARAM_TYPES.get(param[0]) if cls: await self._receive_reconfig_param(cls.parse(param[1])) # server elif isinstance(chunk, InitChunk) and self.is_server: self._last_received_tsn = tsn_minus_one(chunk.initial_tsn) self._reconfig_response_seq = tsn_minus_one(chunk.initial_tsn) self._remote_verification_tag = chunk.initiate_tag self._ssthresh = chunk.advertised_rwnd self._get_extensions(chunk.params) self.__log_debug( "- Peer supports %d outbound streams, %d max inbound streams", chunk.outbound_streams, chunk.inbound_streams, ) self._inbound_streams_count = min( chunk.outbound_streams, self._inbound_streams_max ) self._outbound_streams_count = min( self._outbound_streams_count, chunk.inbound_streams ) ack = InitAckChunk() ack.initiate_tag = self._local_verification_tag ack.advertised_rwnd = self._advertised_rwnd ack.outbound_streams = self._outbound_streams_count ack.inbound_streams = self._inbound_streams_max ack.initial_tsn = self._local_tsn self._set_extensions(ack.params) # generate state cookie cookie = pack("!L", self._get_timestamp()) cookie += hmac.new(self._hmac_key, cookie, "sha1").digest() ack.params.append((SCTP_STATE_COOKIE, cookie)) await self._send_chunk(ack) elif isinstance(chunk, CookieEchoChunk) and self.is_server: # check state cookie MAC cookie = chunk.body if ( len(cookie) != COOKIE_LENGTH or hmac.new(self._hmac_key, cookie[0:4], "sha1").digest() != cookie[4:] ): self.__log_debug("x State cookie is invalid") return # check state cookie lifetime now = self._get_timestamp() stamp = unpack_from("!L", cookie)[0] if stamp < now - COOKIE_LIFETIME or stamp > now: self.__log_debug("x State cookie has expired") error = ErrorChunk() error.params.append((SCTP_CAUSE_STALE_COOKIE, b"\x00" * 8)) await self._send_chunk(error) return ack = CookieAckChunk() await self._send_chunk(ack) self._set_state(self.State.ESTABLISHED) # client elif ( isinstance(chunk, InitAckChunk) and self._association_state == self.State.COOKIE_WAIT ): # cancel T1 timer and process chunk self._t1_cancel() self._last_received_tsn = tsn_minus_one(chunk.initial_tsn) self._reconfig_response_seq = tsn_minus_one(chunk.initial_tsn) self._remote_verification_tag = chunk.initiate_tag self._ssthresh = chunk.advertised_rwnd self._get_extensions(chunk.params) self.__log_debug( "- Peer supports %d outbound streams, %d max inbound streams", chunk.outbound_streams, chunk.inbound_streams, ) self._inbound_streams_count = min( chunk.outbound_streams, self._inbound_streams_max ) self._outbound_streams_count = min( self._outbound_streams_count, chunk.inbound_streams ) echo = CookieEchoChunk() for k, v in chunk.params: if k == SCTP_STATE_COOKIE: echo.body = v break await self._send_chunk(echo) # start T1 timer and enter COOKIE-ECHOED state self._t1_start(echo) self._set_state(self.State.COOKIE_ECHOED) elif ( isinstance(chunk, CookieAckChunk) and self._association_state == self.State.COOKIE_ECHOED ): # cancel T1 timer and enter ESTABLISHED state self._t1_cancel() self._set_state(self.State.ESTABLISHED) elif isinstance(chunk, ErrorChunk) and self._association_state in [ self.State.COOKIE_WAIT, self.State.COOKIE_ECHOED, ]: self._t1_cancel() self._set_state(self.State.CLOSED) self.__log_debug("x Could not establish association") return async def _receive_data_chunk(self, chunk: DataChunk) -> None: """ Handle a DATA chunk. """ self._sack_needed = True # mark as received if self._mark_received(chunk.tsn): return # find stream inbound_stream = self._get_inbound_stream(chunk.stream_id) # defragment data inbound_stream.add_chunk(chunk) self._advertised_rwnd -= len(chunk.user_data) for message in inbound_stream.pop_messages(): self._advertised_rwnd += len(message[2]) await self._receive(*message) async def _receive_forward_tsn_chunk(self, chunk: ForwardTsnChunk) -> None: """ Handle a FORWARD TSN chunk. """ self._sack_needed = True # it's a duplicate if uint32_gte(self._last_received_tsn, chunk.cumulative_tsn): return def is_obsolete(x): return uint32_gt(x, self._last_received_tsn) # advance cumulative TSN self._last_received_tsn = chunk.cumulative_tsn self._sack_misordered = set(filter(is_obsolete, self._sack_misordered)) for tsn in sorted(self._sack_misordered): if tsn == tsn_plus_one(self._last_received_tsn): self._last_received_tsn = tsn else: break # filter out obsolete entries self._sack_duplicates = list(filter(is_obsolete, self._sack_duplicates)) self._sack_misordered = set(filter(is_obsolete, self._sack_misordered)) # update reassembly for stream_id, stream_seq in chunk.streams: inbound_stream = self._get_inbound_stream(stream_id) # advance sequence number and perform delivery inbound_stream.sequence_number = uint16_add(stream_seq, 1) for message in inbound_stream.pop_messages(): self._advertised_rwnd += len(message[2]) await self._receive(*message) # prune obsolete chunks for stream_id, inbound_stream in self._inbound_streams.items(): self._advertised_rwnd += inbound_stream.prune_chunks( self._last_received_tsn ) @no_type_check async def _receive_sack_chunk(self, chunk: SackChunk) -> None: """ Handle a SACK chunk. """ if uint32_gt(self._last_sacked_tsn, chunk.cumulative_tsn): return received_time = time.time() self._last_sacked_tsn = chunk.cumulative_tsn cwnd_fully_utilized = self._flight_size >= self._cwnd done = 0 done_bytes = 0 # handle acknowledged data while self._sent_queue and uint32_gte( self._last_sacked_tsn, self._sent_queue[0].tsn ): schunk = self._sent_queue.popleft() done += 1 if not schunk._acked: done_bytes += schunk._book_size self._flight_size_decrease(schunk) # update RTO estimate if done == 1 and schunk._sent_count == 1: self._update_rto(received_time - schunk._sent_time) # handle gap blocks loss = False if chunk.gaps: seen = set() for gap in chunk.gaps: for pos in range(gap[0], gap[1] + 1): highest_seen_tsn = (chunk.cumulative_tsn + pos) % SCTP_TSN_MODULO seen.add(highest_seen_tsn) # determined Highest TSN Newly Acked (HTNA) highest_newly_acked = chunk.cumulative_tsn for schunk in self._sent_queue: if uint32_gt(schunk.tsn, highest_seen_tsn): break if schunk.tsn in seen and not schunk._acked: done_bytes += schunk._book_size schunk._acked = True self._flight_size_decrease(schunk) highest_newly_acked = schunk.tsn # strike missing chunks prior to HTNA for schunk in self._sent_queue: if uint32_gt(schunk.tsn, highest_newly_acked): break if schunk.tsn not in seen: schunk._misses += 1 if schunk._misses == 3: schunk._misses = 0 if not self._maybe_abandon(schunk): schunk._retransmit = True schunk._acked = False self._flight_size_decrease(schunk) loss = True # adjust congestion window if self._fast_recovery_exit is None: if done and cwnd_fully_utilized: if self._cwnd <= self._ssthresh: # slow start self._cwnd += min(done_bytes, USERDATA_MAX_LENGTH) else: # congestion avoidance self._partial_bytes_acked += done_bytes if self._partial_bytes_acked >= self._cwnd: self._partial_bytes_acked -= self._cwnd self._cwnd += USERDATA_MAX_LENGTH if loss: self._ssthresh = max(self._cwnd // 2, 4 * USERDATA_MAX_LENGTH) self._cwnd = self._ssthresh self._partial_bytes_acked = 0 self._fast_recovery_exit = self._sent_queue[-1].tsn self._fast_recovery_transmit = True elif uint32_gte(chunk.cumulative_tsn, self._fast_recovery_exit): self._fast_recovery_exit = None if not self._sent_queue: # there is no outstanding data, stop T3 self._t3_cancel() elif done: # the earliest outstanding chunk was acknowledged, restart T3 self._t3_restart() self._update_advanced_peer_ack_point() await self._data_channel_flush() await self._transmit() async def _receive_reconfig_param(self, param): """ Handle a RE-CONFIG parameter. """ self.__log_debug("<< %s", param) if isinstance(param, StreamResetOutgoingParam): # mark closed inbound streams for stream_id in param.streams: self._inbound_streams.pop(stream_id, None) # close data channel channel = self._data_channels.get(stream_id) if channel: self._data_channel_close(channel) # send response response_param = StreamResetResponseParam( response_sequence=param.request_sequence, result=1 ) self._reconfig_response_seq = param.request_sequence await self._send_reconfig_param(response_param) elif isinstance(param, StreamAddOutgoingParam): # increase inbound streams self._inbound_streams_count += param.new_streams # send response response_param = StreamResetResponseParam( response_sequence=param.request_sequence, result=1 ) self._reconfig_response_seq = param.request_sequence await self._send_reconfig_param(response_param) elif isinstance(param, StreamResetResponseParam): if ( self._reconfig_request and param.response_sequence == self._reconfig_request.request_sequence ): # mark closed streams for stream_id in self._reconfig_request.streams: self._outbound_stream_seq.pop(stream_id, None) self._data_channel_closed(stream_id) self._reconfig_request = None await self._transmit_reconfig() @no_type_check async def _send( self, stream_id: int, pp_id: int, user_data: bytes, expiry: Optional[float] = None, max_retransmits: Optional[int] = None, ordered: bool = True, ) -> None: """ Send data ULP -> stream. """ if ordered: stream_seq = self._outbound_stream_seq.get(stream_id, 0) else: stream_seq = 0 fragments = math.ceil(len(user_data) / USERDATA_MAX_LENGTH) pos = 0 for fragment in range(0, fragments): chunk = DataChunk() chunk.flags = 0 if not ordered: chunk.flags = SCTP_DATA_UNORDERED if fragment == 0: chunk.flags |= SCTP_DATA_FIRST_FRAG if fragment == fragments - 1: chunk.flags |= SCTP_DATA_LAST_FRAG chunk.tsn = self._local_tsn chunk.stream_id = stream_id chunk.stream_seq = stream_seq chunk.protocol = pp_id chunk.user_data = user_data[pos : pos + USERDATA_MAX_LENGTH] # FIXME: dynamically added attributes, mypy can't handle them # initialize counters chunk._abandoned = False chunk._acked = False chunk._book_size = len(chunk.user_data) chunk._expiry = expiry chunk._max_retransmits = max_retransmits chunk._misses = 0 chunk._retransmit = False chunk._sent_count = 0 chunk._sent_time = None pos += USERDATA_MAX_LENGTH self._local_tsn = tsn_plus_one(self._local_tsn) self._outbound_queue.append(chunk) if ordered: self._outbound_stream_seq[stream_id] = uint16_add(stream_seq, 1) # transmit outbound data await self._transmit() async def _send_chunk(self, chunk: Chunk) -> None: """ Transmit a chunk (no bundling for now). """ self.__log_debug("> %s", chunk) await self.__transport._send_data( serialize_packet( self._local_port, self._remote_port, self._remote_verification_tag, chunk, ) ) async def _send_reconfig_param(self, param): chunk = ReconfigChunk() for k, cls in RECONFIG_PARAM_TYPES.items(): if isinstance(param, cls): param_type = k break chunk.params.append((param_type, bytes(param))) self.__log_debug(">> %s", param) await self._send_chunk(chunk) async def _send_sack(self): """ Build and send a selective acknowledgement (SACK) chunk. """ gaps = [] gap_next = None for tsn in sorted(self._sack_misordered): pos = (tsn - self._last_received_tsn) % SCTP_TSN_MODULO if tsn == gap_next: gaps[-1][1] = pos else: gaps.append([pos, pos]) gap_next = tsn_plus_one(tsn) sack = SackChunk() sack.cumulative_tsn = self._last_received_tsn sack.advertised_rwnd = max(0, self._advertised_rwnd) sack.duplicates = self._sack_duplicates[:] sack.gaps = [tuple(x) for x in gaps] await self._send_chunk(sack) self._sack_duplicates.clear() self._sack_needed = False def _set_state(self, state) -> None: """ Transition the SCTP association to a new state. """ if state != self._association_state: self.__log_debug("- %s -> %s", self._association_state, state) self._association_state = state if state == self.State.ESTABLISHED: self.__state = "connected" for channel in list(self._data_channels.values()): if channel.negotiated and channel.readyState != "open": channel._setReadyState("open") asyncio.ensure_future(self._data_channel_flush()) elif state == self.State.CLOSED: self._t1_cancel() self._t2_cancel() self._t3_cancel() self.__state = "closed" # close data channels for stream_id in list(self._data_channels.keys()): self._data_channel_closed(stream_id) # no more events will be emitted, so remove all event listeners # to facilitate garbage collection. self.remove_all_listeners() # timers def _t1_cancel(self) -> None: if self._t1_handle is not None: self.__log_debug("- T1(%s) cancel", chunk_type(self._t1_chunk)) self._t1_handle.cancel() self._t1_handle = None self._t1_chunk = None def _t1_expired(self) -> None: self._t1_failures += 1 self._t1_handle = None self.__log_debug( "x T1(%s) expired %d", chunk_type(self._t1_chunk), self._t1_failures ) if self._t1_failures > SCTP_MAX_INIT_RETRANS: self._set_state(self.State.CLOSED) else: asyncio.ensure_future(self._send_chunk(self._t1_chunk)) self._t1_handle = self._loop.call_later(self._rto, self._t1_expired) def _t1_start(self, chunk: Chunk) -> None: assert self._t1_handle is None self._t1_chunk = chunk self._t1_failures = 0 self.__log_debug("- T1(%s) start", chunk_type(self._t1_chunk)) self._t1_handle = self._loop.call_later(self._rto, self._t1_expired) def _t2_cancel(self) -> None: if self._t2_handle is not None: self.__log_debug("- T2(%s) cancel", chunk_type(self._t2_chunk)) self._t2_handle.cancel() self._t2_handle = None self._t2_chunk = None def _t2_expired(self) -> None: self._t2_failures += 1 self._t2_handle = None self.__log_debug( "x T2(%s) expired %d", chunk_type(self._t2_chunk), self._t2_failures ) if self._t2_failures > SCTP_MAX_ASSOCIATION_RETRANS: self._set_state(self.State.CLOSED) else: asyncio.ensure_future(self._send_chunk(self._t2_chunk)) self._t2_handle = self._loop.call_later(self._rto, self._t2_expired) def _t2_start(self, chunk) -> None: assert self._t2_handle is None self._t2_chunk = chunk self._t2_failures = 0 self.__log_debug("- T2(%s) start", chunk_type(self._t2_chunk)) self._t2_handle = self._loop.call_later(self._rto, self._t2_expired) @no_type_check def _t3_expired(self) -> None: self._t3_handle = None self.__log_debug("x T3 expired") # mark retransmit or abandoned chunks for chunk in self._sent_queue: if not self._maybe_abandon(chunk): chunk._retransmit = True self._update_advanced_peer_ack_point() # adjust congestion window self._fast_recovery_exit = None self._flight_size = 0 self._partial_bytes_acked = 0 self._ssthresh = max(self._cwnd // 2, 4 * USERDATA_MAX_LENGTH) self._cwnd = USERDATA_MAX_LENGTH asyncio.ensure_future(self._transmit()) def _t3_restart(self) -> None: self.__log_debug("- T3 restart") if self._t3_handle is not None: self._t3_handle.cancel() self._t3_handle = None self._t3_handle = self._loop.call_later(self._rto, self._t3_expired) def _t3_start(self) -> None: assert self._t3_handle is None self.__log_debug("- T3 start") self._t3_handle = self._loop.call_later(self._rto, self._t3_expired) def _t3_cancel(self) -> None: if self._t3_handle is not None: self.__log_debug("- T3 cancel") self._t3_handle.cancel() self._t3_handle = None @no_type_check async def _transmit(self) -> None: """ Transmit outbound data. """ # send FORWARD TSN if self._forward_tsn_chunk is not None: await self._send_chunk(self._forward_tsn_chunk) self._forward_tsn_chunk = None # ensure T3 is running if not self._t3_handle: self._t3_start() # limit burst size if self._fast_recovery_exit is not None: burst_size = 2 * USERDATA_MAX_LENGTH else: burst_size = 4 * USERDATA_MAX_LENGTH cwnd = min(self._flight_size + burst_size, self._cwnd) # retransmit retransmit_earliest = True for chunk in self._sent_queue: if chunk._retransmit: if self._fast_recovery_transmit: self._fast_recovery_transmit = False elif self._flight_size >= cwnd: return self._flight_size_increase(chunk) chunk._misses = 0 chunk._retransmit = False chunk._sent_count += 1 await self._send_chunk(chunk) if retransmit_earliest: # restart the T3 timer as the earliest outstanding TSN # is being retransmitted self._t3_restart() retransmit_earliest = False while self._outbound_queue and self._flight_size < cwnd: chunk = self._outbound_queue.popleft() self._sent_queue.append(chunk) self._flight_size_increase(chunk) # update counters chunk._sent_count += 1 chunk._sent_time = time.time() await self._send_chunk(chunk) if not self._t3_handle: self._t3_start() async def _transmit_reconfig(self): if ( self._association_state == self.State.ESTABLISHED and self._reconfig_queue and not self._reconfig_request ): streams = self._reconfig_queue[0:RECONFIG_MAX_STREAMS] self._reconfig_queue = self._reconfig_queue[RECONFIG_MAX_STREAMS:] param = StreamResetOutgoingParam( request_sequence=self._reconfig_request_seq, response_sequence=self._reconfig_response_seq, last_tsn=tsn_minus_one(self._local_tsn), streams=streams, ) self._reconfig_request = param self._reconfig_request_seq = tsn_plus_one(self._reconfig_request_seq) await self._send_reconfig_param(param) @no_type_check def _update_advanced_peer_ack_point(self) -> None: """ Try to advance "Advanced.Peer.Ack.Point" according to RFC 3758. """ if uint32_gt(self._last_sacked_tsn, self._advanced_peer_ack_tsn): self._advanced_peer_ack_tsn = self._last_sacked_tsn done = 0 streams = {} while self._sent_queue and self._sent_queue[0]._abandoned: chunk = self._sent_queue.popleft() self._advanced_peer_ack_tsn = chunk.tsn done += 1 if not (chunk.flags & SCTP_DATA_UNORDERED): streams[chunk.stream_id] = chunk.stream_seq if done: # build FORWARD TSN self._forward_tsn_chunk = ForwardTsnChunk() self._forward_tsn_chunk.cumulative_tsn = self._advanced_peer_ack_tsn self._forward_tsn_chunk.streams = list(streams.items()) def _update_rto(self, R: float) -> None: """ Update RTO given a new roundtrip measurement R. """ if self._srtt is None: self._rttvar = R / 2 self._srtt = R else: self._rttvar = (1 - SCTP_RTO_BETA) * self._rttvar + SCTP_RTO_BETA * abs( self._srtt - R ) self._srtt = (1 - SCTP_RTO_ALPHA) * self._srtt + SCTP_RTO_ALPHA * R self._rto = max(SCTP_RTO_MIN, min(self._srtt + 4 * self._rttvar, SCTP_RTO_MAX)) def _data_channel_close(self, channel, transmit=True): """ Request closing the datachannel by sending an Outgoing Stream Reset Request. """ if channel.readyState not in ["closing", "closed"]: channel._setReadyState("closing") if self._association_state == self.State.ESTABLISHED: # queue a stream reset self._reconfig_queue.append(channel.id) if len(self._reconfig_queue) == 1: asyncio.ensure_future(self._transmit_reconfig()) else: # remove any queued messages for the datachannel new_queue = deque() for queue_item in self._data_channel_queue: if queue_item[0] != channel: new_queue.append(queue_item) self._data_channel_queue = new_queue # mark the datachannel as closed if channel.id is not None: self._data_channels.pop(channel.id) channel._setReadyState("closed") def _data_channel_closed(self, stream_id: int) -> None: channel = self._data_channels.pop(stream_id) channel._setReadyState("closed") async def _data_channel_flush(self) -> None: """ Try to flush buffered data to the SCTP layer. We wait until the association is established, as we need to know whether we are a client or a server to correctly assign an odd/even ID to the data channels. """ if self._association_state != self.State.ESTABLISHED: return while self._data_channel_queue and not self._outbound_queue: channel, protocol, user_data = self._data_channel_queue.popleft() # register channel if necessary stream_id = channel.id if stream_id is None: stream_id = self._data_channel_id while stream_id in self._data_channels: stream_id += 2 self._data_channels[stream_id] = channel channel._setId(stream_id) # send data if protocol == WEBRTC_DCEP: await self._send(stream_id, protocol, user_data) else: if channel.maxPacketLifeTime: expiry = time.time() + (channel.maxPacketLifeTime / 1000) else: expiry = None await self._send( stream_id, protocol, user_data, expiry=expiry, max_retransmits=channel.maxRetransmits, ordered=channel.ordered, ) channel._addBufferedAmount(-len(user_data)) def _data_channel_add_negotiated(self, channel: RTCDataChannel) -> None: if channel.id in self._data_channels: raise ValueError(f"Data channel with ID {channel.id} already registered") self._data_channels[channel.id] = channel if self._association_state == self.State.ESTABLISHED: channel._setReadyState("open") def _data_channel_open(self, channel: RTCDataChannel) -> None: if channel.id is not None: if channel.id in self._data_channels: raise ValueError( f"Data channel with ID {channel.id} already registered" ) else: self._data_channels[channel.id] = channel channel_type = DATA_CHANNEL_RELIABLE priority = 0 reliability = 0 if not channel.ordered: channel_type |= 0x80 if channel.maxRetransmits is not None: channel_type |= 1 reliability = channel.maxRetransmits elif channel.maxPacketLifeTime is not None: channel_type |= 2 reliability = channel.maxPacketLifeTime data = pack( "!BBHLHH", DATA_CHANNEL_OPEN, channel_type, priority, reliability, len(channel.label), len(channel.protocol), ) data += channel.label.encode("utf8") data += channel.protocol.encode("utf8") self._data_channel_queue.append((channel, WEBRTC_DCEP, data)) asyncio.ensure_future(self._data_channel_flush()) async def _data_channel_receive( self, stream_id: int, pp_id: int, data: bytes ) -> None: if pp_id == WEBRTC_DCEP and len(data): msg_type = data[0] if msg_type == DATA_CHANNEL_OPEN and len(data) >= 12: # we should not receive an open for an existing channel assert stream_id not in self._data_channels ( msg_type, channel_type, priority, reliability, label_length, protocol_length, ) = unpack_from("!BBHLHH", data) pos = 12 label = data[pos : pos + label_length].decode("utf8") pos += label_length protocol = data[pos : pos + protocol_length].decode("utf8") # check channel type maxPacketLifeTime = None maxRetransmits = None if (channel_type & 0x03) == 1: maxRetransmits = reliability elif (channel_type & 0x03) == 2: maxPacketLifeTime = reliability # register channel parameters = RTCDataChannelParameters( label=label, ordered=(channel_type & 0x80) == 0, maxPacketLifeTime=maxPacketLifeTime, maxRetransmits=maxRetransmits, protocol=protocol, id=stream_id, ) channel = RTCDataChannel(self, parameters, False) channel._setReadyState("open") self._data_channels[stream_id] = channel # send ack self._data_channel_queue.append( (channel, WEBRTC_DCEP, pack("!B", DATA_CHANNEL_ACK)) ) await self._data_channel_flush() # emit channel self.emit("datachannel", channel) elif msg_type == DATA_CHANNEL_ACK: assert stream_id in self._data_channels channel = self._data_channels[stream_id] channel._setReadyState("open") elif pp_id == WEBRTC_STRING and stream_id in self._data_channels: # emit message self._data_channels[stream_id].emit("message", data.decode("utf8")) elif pp_id == WEBRTC_STRING_EMPTY and stream_id in self._data_channels: # emit message self._data_channels[stream_id].emit("message", "") elif pp_id == WEBRTC_BINARY and stream_id in self._data_channels: # emit message self._data_channels[stream_id].emit("message", data) elif pp_id == WEBRTC_BINARY_EMPTY and stream_id in self._data_channels: # emit message self._data_channels[stream_id].emit("message", b"") def _data_channel_send(self, channel: RTCDataChannel, data: bytes) -> None: if data == "": pp_id, user_data = WEBRTC_STRING_EMPTY, b"\x00" elif isinstance(data, str): pp_id, user_data = WEBRTC_STRING, data.encode("utf8") elif data == b"": pp_id, user_data = WEBRTC_BINARY_EMPTY, b"\x00" else: pp_id, user_data = WEBRTC_BINARY, data channel._addBufferedAmount(len(user_data)) self._data_channel_queue.append((channel, pp_id, user_data)) asyncio.ensure_future(self._data_channel_flush()) class State(enum.Enum): CLOSED = 1 COOKIE_WAIT = 2 COOKIE_ECHOED = 3 ESTABLISHED = 4 SHUTDOWN_PENDING = 5 SHUTDOWN_SENT = 6 SHUTDOWN_RECEIVED = 7 SHUTDOWN_ACK_SENT = 8
(transport: aiortc.rtcdtlstransport.RTCDtlsTransport, port: int = 5000) -> None
718,994
aiortc.rtcsctptransport
__init__
null
def __init__(self, transport: RTCDtlsTransport, port: int = 5000) -> None: if transport.state == "closed": raise InvalidStateError super().__init__() self._association_state = self.State.CLOSED self.__log_debug: Callable[..., None] = lambda *args: None self.__started = False self.__state = "new" self.__transport = transport self._loop = asyncio.get_event_loop() self._hmac_key = os.urandom(16) self._local_partial_reliability = True self._local_port = port self._local_verification_tag = random32() self._remote_extensions: List[int] = [] self._remote_partial_reliability = False self._remote_port: Optional[int] = None self._remote_verification_tag = 0 # inbound self._advertised_rwnd = 1024 * 1024 self._inbound_streams: Dict[int, InboundStream] = {} self._inbound_streams_count = 0 self._inbound_streams_max = MAX_STREAMS self._last_received_tsn: Optional[int] = None self._sack_duplicates: List[int] = [] self._sack_misordered: Set[int] = set() self._sack_needed = False # outbound self._cwnd = 3 * USERDATA_MAX_LENGTH self._fast_recovery_exit = None self._fast_recovery_transmit = False self._forward_tsn_chunk: Optional[ForwardTsnChunk] = None self._flight_size = 0 self._local_tsn = random32() self._last_sacked_tsn = tsn_minus_one(self._local_tsn) self._advanced_peer_ack_tsn = tsn_minus_one(self._local_tsn) self._outbound_queue: Deque[DataChunk] = deque() self._outbound_stream_seq: Dict[int, int] = {} self._outbound_streams_count = MAX_STREAMS self._partial_bytes_acked = 0 self._sent_queue: Deque[DataChunk] = deque() # reconfiguration self._reconfig_queue: List[int] = [] self._reconfig_request = None self._reconfig_request_seq = self._local_tsn self._reconfig_response_seq = 0 # rtt calculation self._srtt: Optional[float] = None self._rttvar: Optional[float] = None # timers self._rto = SCTP_RTO_INITIAL self._t1_chunk: Optional[Chunk] = None self._t1_failures = 0 self._t1_handle: Optional[asyncio.TimerHandle] = None self._t2_chunk: Optional[Chunk] = None self._t2_failures = 0 self._t2_handle: Optional[asyncio.TimerHandle] = None self._t3_handle: Optional[asyncio.TimerHandle] = None # data channels self._data_channel_id: Optional[int] = None self._data_channel_queue: Deque[Tuple[RTCDataChannel, int, bytes]] = deque() self._data_channels: Dict[int, RTCDataChannel] = {} # FIXME: this is only used by RTCPeerConnection self._bundled = False self.mid: Optional[str] = None
(self, transport: aiortc.rtcdtlstransport.RTCDtlsTransport, port: int = 5000) -> NoneType
718,996
aiortc.rtcsctptransport
_abort
Abort the association.
self.__log_debug = lambda msg, *args: logger.debug(prefix + msg, *args)
(self) -> NoneType
718,999
aiortc.rtcsctptransport
_data_channel_add_negotiated
null
def _data_channel_add_negotiated(self, channel: RTCDataChannel) -> None: if channel.id in self._data_channels: raise ValueError(f"Data channel with ID {channel.id} already registered") self._data_channels[channel.id] = channel if self._association_state == self.State.ESTABLISHED: channel._setReadyState("open")
(self, channel: aiortc.rtcdatachannel.RTCDataChannel) -> NoneType
719,000
aiortc.rtcsctptransport
_data_channel_close
Request closing the datachannel by sending an Outgoing Stream Reset Request.
def _data_channel_close(self, channel, transmit=True): """ Request closing the datachannel by sending an Outgoing Stream Reset Request. """ if channel.readyState not in ["closing", "closed"]: channel._setReadyState("closing") if self._association_state == self.State.ESTABLISHED: # queue a stream reset self._reconfig_queue.append(channel.id) if len(self._reconfig_queue) == 1: asyncio.ensure_future(self._transmit_reconfig()) else: # remove any queued messages for the datachannel new_queue = deque() for queue_item in self._data_channel_queue: if queue_item[0] != channel: new_queue.append(queue_item) self._data_channel_queue = new_queue # mark the datachannel as closed if channel.id is not None: self._data_channels.pop(channel.id) channel._setReadyState("closed")
(self, channel, transmit=True)
719,001
aiortc.rtcsctptransport
_data_channel_closed
null
def _data_channel_closed(self, stream_id: int) -> None: channel = self._data_channels.pop(stream_id) channel._setReadyState("closed")
(self, stream_id: int) -> NoneType
719,002
aiortc.rtcsctptransport
_data_channel_flush
Try to flush buffered data to the SCTP layer. We wait until the association is established, as we need to know whether we are a client or a server to correctly assign an odd/even ID to the data channels.
def _data_channel_closed(self, stream_id: int) -> None: channel = self._data_channels.pop(stream_id) channel._setReadyState("closed")
(self) -> NoneType
719,003
aiortc.rtcsctptransport
_data_channel_open
null
def _data_channel_open(self, channel: RTCDataChannel) -> None: if channel.id is not None: if channel.id in self._data_channels: raise ValueError( f"Data channel with ID {channel.id} already registered" ) else: self._data_channels[channel.id] = channel channel_type = DATA_CHANNEL_RELIABLE priority = 0 reliability = 0 if not channel.ordered: channel_type |= 0x80 if channel.maxRetransmits is not None: channel_type |= 1 reliability = channel.maxRetransmits elif channel.maxPacketLifeTime is not None: channel_type |= 2 reliability = channel.maxPacketLifeTime data = pack( "!BBHLHH", DATA_CHANNEL_OPEN, channel_type, priority, reliability, len(channel.label), len(channel.protocol), ) data += channel.label.encode("utf8") data += channel.protocol.encode("utf8") self._data_channel_queue.append((channel, WEBRTC_DCEP, data)) asyncio.ensure_future(self._data_channel_flush())
(self, channel: aiortc.rtcdatachannel.RTCDataChannel) -> NoneType
719,005
aiortc.rtcsctptransport
_data_channel_send
null
def _data_channel_send(self, channel: RTCDataChannel, data: bytes) -> None: if data == "": pp_id, user_data = WEBRTC_STRING_EMPTY, b"\x00" elif isinstance(data, str): pp_id, user_data = WEBRTC_STRING, data.encode("utf8") elif data == b"": pp_id, user_data = WEBRTC_BINARY_EMPTY, b"\x00" else: pp_id, user_data = WEBRTC_BINARY, data channel._addBufferedAmount(len(user_data)) self._data_channel_queue.append((channel, pp_id, user_data)) asyncio.ensure_future(self._data_channel_flush())
(self, channel: aiortc.rtcdatachannel.RTCDataChannel, data: bytes) -> NoneType
719,008
aiortc.rtcsctptransport
_flight_size_decrease
null
def _flight_size_decrease(self, chunk: DataChunk) -> None: self._flight_size = max(0, self._flight_size - chunk._book_size) # type: ignore
(self, chunk: aiortc.rtcsctptransport.DataChunk) -> NoneType
719,009
aiortc.rtcsctptransport
_flight_size_increase
null
def _flight_size_increase(self, chunk: DataChunk) -> None: self._flight_size += chunk._book_size # type: ignore
(self, chunk: aiortc.rtcsctptransport.DataChunk) -> NoneType
719,010
aiortc.rtcsctptransport
_get_extensions
Gets what extensions are supported by the remote party.
def _get_extensions(self, params: List[Tuple[int, bytes]]) -> None: """ Gets what extensions are supported by the remote party. """ for k, v in params: if k == SCTP_PRSCTP_SUPPORTED: self._remote_partial_reliability = True elif k == SCTP_SUPPORTED_CHUNK_EXT: self._remote_extensions = list(v)
(self, params: List[Tuple[int, bytes]]) -> NoneType
719,011
aiortc.rtcsctptransport
_get_inbound_stream
Get or create the inbound stream with the specified ID.
def _get_inbound_stream(self, stream_id: int) -> InboundStream: """ Get or create the inbound stream with the specified ID. """ if stream_id not in self._inbound_streams: self._inbound_streams[stream_id] = InboundStream() return self._inbound_streams[stream_id]
(self, stream_id: int) -> aiortc.rtcsctptransport.InboundStream
719,012
aiortc.rtcsctptransport
_get_timestamp
null
def _get_timestamp(self) -> int: return int(time.time())
(self) -> int
719,013
aiortc.rtcsctptransport
_handle_data
Handle data received from the network.
def _get_timestamp(self) -> int: return int(time.time())
(self, data)
719,014
aiortc.rtcsctptransport
_init
Initialize the association.
self.__log_debug = lambda msg, *args: logger.debug(prefix + msg, *args)
(self) -> NoneType
719,015
aiortc.rtcsctptransport
_mark_received
Mark an incoming data TSN as received.
def _mark_received(self, tsn: int) -> bool: """ Mark an incoming data TSN as received. """ # it's a duplicate if uint32_gte(self._last_received_tsn, tsn) or tsn in self._sack_misordered: self._sack_duplicates.append(tsn) return True # consolidate misordered entries self._sack_misordered.add(tsn) for tsn in sorted(self._sack_misordered): if tsn == tsn_plus_one(self._last_received_tsn): self._last_received_tsn = tsn else: break # filter out obsolete entries def is_obsolete(x): return uint32_gt(x, self._last_received_tsn) self._sack_duplicates = list(filter(is_obsolete, self._sack_duplicates)) self._sack_misordered = set(filter(is_obsolete, self._sack_misordered)) return False
(self, tsn: int) -> bool
719,016
aiortc.rtcsctptransport
_maybe_abandon
Determine if a chunk needs to be marked as abandoned. If it does, it marks the chunk and any other chunk belong to the same message as abandoned.
@no_type_check def _maybe_abandon(self, chunk: DataChunk) -> bool: """ Determine if a chunk needs to be marked as abandoned. If it does, it marks the chunk and any other chunk belong to the same message as abandoned. """ if chunk._abandoned: return True abandon = ( chunk._max_retransmits is not None and chunk._sent_count > chunk._max_retransmits ) or (chunk._expiry is not None and chunk._expiry < time.time()) if not abandon: return False chunk_pos = self._sent_queue.index(chunk) for pos in range(chunk_pos, -1, -1): ochunk = self._sent_queue[pos] ochunk._abandoned = True ochunk._retransmit = False if ochunk.flags & SCTP_DATA_FIRST_FRAG: break for pos in range(chunk_pos, len(self._sent_queue)): ochunk = self._sent_queue[pos] ochunk._abandoned = True ochunk._retransmit = False if ochunk.flags & SCTP_DATA_LAST_FRAG: break return True
(self, chunk: aiortc.rtcsctptransport.DataChunk) -> bool
719,017
aiortc.rtcsctptransport
_receive
Receive data stream -> ULP.
def _mark_received(self, tsn: int) -> bool: """ Mark an incoming data TSN as received. """ # it's a duplicate if uint32_gte(self._last_received_tsn, tsn) or tsn in self._sack_misordered: self._sack_duplicates.append(tsn) return True # consolidate misordered entries self._sack_misordered.add(tsn) for tsn in sorted(self._sack_misordered): if tsn == tsn_plus_one(self._last_received_tsn): self._last_received_tsn = tsn else: break # filter out obsolete entries def is_obsolete(x): return uint32_gt(x, self._last_received_tsn) self._sack_duplicates = list(filter(is_obsolete, self._sack_duplicates)) self._sack_misordered = set(filter(is_obsolete, self._sack_misordered)) return False
(self, stream_id: int, pp_id: int, data: bytes) -> NoneType
719,018
aiortc.rtcsctptransport
_receive_chunk
Handle an incoming chunk.
def _mark_received(self, tsn: int) -> bool: """ Mark an incoming data TSN as received. """ # it's a duplicate if uint32_gte(self._last_received_tsn, tsn) or tsn in self._sack_misordered: self._sack_duplicates.append(tsn) return True # consolidate misordered entries self._sack_misordered.add(tsn) for tsn in sorted(self._sack_misordered): if tsn == tsn_plus_one(self._last_received_tsn): self._last_received_tsn = tsn else: break # filter out obsolete entries def is_obsolete(x): return uint32_gt(x, self._last_received_tsn) self._sack_duplicates = list(filter(is_obsolete, self._sack_duplicates)) self._sack_misordered = set(filter(is_obsolete, self._sack_misordered)) return False
(self, chunk)
719,019
aiortc.rtcsctptransport
_receive_data_chunk
Handle a DATA chunk.
def _mark_received(self, tsn: int) -> bool: """ Mark an incoming data TSN as received. """ # it's a duplicate if uint32_gte(self._last_received_tsn, tsn) or tsn in self._sack_misordered: self._sack_duplicates.append(tsn) return True # consolidate misordered entries self._sack_misordered.add(tsn) for tsn in sorted(self._sack_misordered): if tsn == tsn_plus_one(self._last_received_tsn): self._last_received_tsn = tsn else: break # filter out obsolete entries def is_obsolete(x): return uint32_gt(x, self._last_received_tsn) self._sack_duplicates = list(filter(is_obsolete, self._sack_duplicates)) self._sack_misordered = set(filter(is_obsolete, self._sack_misordered)) return False
(self, chunk: aiortc.rtcsctptransport.DataChunk) -> NoneType
719,020
aiortc.rtcsctptransport
_receive_forward_tsn_chunk
Handle a FORWARD TSN chunk.
def _mark_received(self, tsn: int) -> bool: """ Mark an incoming data TSN as received. """ # it's a duplicate if uint32_gte(self._last_received_tsn, tsn) or tsn in self._sack_misordered: self._sack_duplicates.append(tsn) return True # consolidate misordered entries self._sack_misordered.add(tsn) for tsn in sorted(self._sack_misordered): if tsn == tsn_plus_one(self._last_received_tsn): self._last_received_tsn = tsn else: break # filter out obsolete entries def is_obsolete(x): return uint32_gt(x, self._last_received_tsn) self._sack_duplicates = list(filter(is_obsolete, self._sack_duplicates)) self._sack_misordered = set(filter(is_obsolete, self._sack_misordered)) return False
(self, chunk: aiortc.rtcsctptransport.ForwardTsnChunk) -> NoneType
719,021
aiortc.rtcsctptransport
_receive_reconfig_param
Handle a RE-CONFIG parameter.
@no_type_check async def _receive_sack_chunk(self, chunk: SackChunk) -> None: """ Handle a SACK chunk. """ if uint32_gt(self._last_sacked_tsn, chunk.cumulative_tsn): return received_time = time.time() self._last_sacked_tsn = chunk.cumulative_tsn cwnd_fully_utilized = self._flight_size >= self._cwnd done = 0 done_bytes = 0 # handle acknowledged data while self._sent_queue and uint32_gte( self._last_sacked_tsn, self._sent_queue[0].tsn ): schunk = self._sent_queue.popleft() done += 1 if not schunk._acked: done_bytes += schunk._book_size self._flight_size_decrease(schunk) # update RTO estimate if done == 1 and schunk._sent_count == 1: self._update_rto(received_time - schunk._sent_time) # handle gap blocks loss = False if chunk.gaps: seen = set() for gap in chunk.gaps: for pos in range(gap[0], gap[1] + 1): highest_seen_tsn = (chunk.cumulative_tsn + pos) % SCTP_TSN_MODULO seen.add(highest_seen_tsn) # determined Highest TSN Newly Acked (HTNA) highest_newly_acked = chunk.cumulative_tsn for schunk in self._sent_queue: if uint32_gt(schunk.tsn, highest_seen_tsn): break if schunk.tsn in seen and not schunk._acked: done_bytes += schunk._book_size schunk._acked = True self._flight_size_decrease(schunk) highest_newly_acked = schunk.tsn # strike missing chunks prior to HTNA for schunk in self._sent_queue: if uint32_gt(schunk.tsn, highest_newly_acked): break if schunk.tsn not in seen: schunk._misses += 1 if schunk._misses == 3: schunk._misses = 0 if not self._maybe_abandon(schunk): schunk._retransmit = True schunk._acked = False self._flight_size_decrease(schunk) loss = True # adjust congestion window if self._fast_recovery_exit is None: if done and cwnd_fully_utilized: if self._cwnd <= self._ssthresh: # slow start self._cwnd += min(done_bytes, USERDATA_MAX_LENGTH) else: # congestion avoidance self._partial_bytes_acked += done_bytes if self._partial_bytes_acked >= self._cwnd: self._partial_bytes_acked -= self._cwnd self._cwnd += USERDATA_MAX_LENGTH if loss: self._ssthresh = max(self._cwnd // 2, 4 * USERDATA_MAX_LENGTH) self._cwnd = self._ssthresh self._partial_bytes_acked = 0 self._fast_recovery_exit = self._sent_queue[-1].tsn self._fast_recovery_transmit = True elif uint32_gte(chunk.cumulative_tsn, self._fast_recovery_exit): self._fast_recovery_exit = None if not self._sent_queue: # there is no outstanding data, stop T3 self._t3_cancel() elif done: # the earliest outstanding chunk was acknowledged, restart T3 self._t3_restart() self._update_advanced_peer_ack_point() await self._data_channel_flush() await self._transmit()
(self, param)
719,022
aiortc.rtcsctptransport
_receive_sack_chunk
Handle a SACK chunk.
@no_type_check async def _receive_sack_chunk(self, chunk: SackChunk) -> None: """ Handle a SACK chunk. """ if uint32_gt(self._last_sacked_tsn, chunk.cumulative_tsn): return received_time = time.time() self._last_sacked_tsn = chunk.cumulative_tsn cwnd_fully_utilized = self._flight_size >= self._cwnd done = 0 done_bytes = 0 # handle acknowledged data while self._sent_queue and uint32_gte( self._last_sacked_tsn, self._sent_queue[0].tsn ): schunk = self._sent_queue.popleft() done += 1 if not schunk._acked: done_bytes += schunk._book_size self._flight_size_decrease(schunk) # update RTO estimate if done == 1 and schunk._sent_count == 1: self._update_rto(received_time - schunk._sent_time) # handle gap blocks loss = False if chunk.gaps: seen = set() for gap in chunk.gaps: for pos in range(gap[0], gap[1] + 1): highest_seen_tsn = (chunk.cumulative_tsn + pos) % SCTP_TSN_MODULO seen.add(highest_seen_tsn) # determined Highest TSN Newly Acked (HTNA) highest_newly_acked = chunk.cumulative_tsn for schunk in self._sent_queue: if uint32_gt(schunk.tsn, highest_seen_tsn): break if schunk.tsn in seen and not schunk._acked: done_bytes += schunk._book_size schunk._acked = True self._flight_size_decrease(schunk) highest_newly_acked = schunk.tsn # strike missing chunks prior to HTNA for schunk in self._sent_queue: if uint32_gt(schunk.tsn, highest_newly_acked): break if schunk.tsn not in seen: schunk._misses += 1 if schunk._misses == 3: schunk._misses = 0 if not self._maybe_abandon(schunk): schunk._retransmit = True schunk._acked = False self._flight_size_decrease(schunk) loss = True # adjust congestion window if self._fast_recovery_exit is None: if done and cwnd_fully_utilized: if self._cwnd <= self._ssthresh: # slow start self._cwnd += min(done_bytes, USERDATA_MAX_LENGTH) else: # congestion avoidance self._partial_bytes_acked += done_bytes if self._partial_bytes_acked >= self._cwnd: self._partial_bytes_acked -= self._cwnd self._cwnd += USERDATA_MAX_LENGTH if loss: self._ssthresh = max(self._cwnd // 2, 4 * USERDATA_MAX_LENGTH) self._cwnd = self._ssthresh self._partial_bytes_acked = 0 self._fast_recovery_exit = self._sent_queue[-1].tsn self._fast_recovery_transmit = True elif uint32_gte(chunk.cumulative_tsn, self._fast_recovery_exit): self._fast_recovery_exit = None if not self._sent_queue: # there is no outstanding data, stop T3 self._t3_cancel() elif done: # the earliest outstanding chunk was acknowledged, restart T3 self._t3_restart() self._update_advanced_peer_ack_point() await self._data_channel_flush() await self._transmit()
(self, chunk: aiortc.rtcsctptransport.SackChunk) -> None
719,024
aiortc.rtcsctptransport
_send
Send data ULP -> stream.
@no_type_check async def _send( self, stream_id: int, pp_id: int, user_data: bytes, expiry: Optional[float] = None, max_retransmits: Optional[int] = None, ordered: bool = True, ) -> None: """ Send data ULP -> stream. """ if ordered: stream_seq = self._outbound_stream_seq.get(stream_id, 0) else: stream_seq = 0 fragments = math.ceil(len(user_data) / USERDATA_MAX_LENGTH) pos = 0 for fragment in range(0, fragments): chunk = DataChunk() chunk.flags = 0 if not ordered: chunk.flags = SCTP_DATA_UNORDERED if fragment == 0: chunk.flags |= SCTP_DATA_FIRST_FRAG if fragment == fragments - 1: chunk.flags |= SCTP_DATA_LAST_FRAG chunk.tsn = self._local_tsn chunk.stream_id = stream_id chunk.stream_seq = stream_seq chunk.protocol = pp_id chunk.user_data = user_data[pos : pos + USERDATA_MAX_LENGTH] # FIXME: dynamically added attributes, mypy can't handle them # initialize counters chunk._abandoned = False chunk._acked = False chunk._book_size = len(chunk.user_data) chunk._expiry = expiry chunk._max_retransmits = max_retransmits chunk._misses = 0 chunk._retransmit = False chunk._sent_count = 0 chunk._sent_time = None pos += USERDATA_MAX_LENGTH self._local_tsn = tsn_plus_one(self._local_tsn) self._outbound_queue.append(chunk) if ordered: self._outbound_stream_seq[stream_id] = uint16_add(stream_seq, 1) # transmit outbound data await self._transmit()
(self, stream_id: int, pp_id: int, user_data: bytes, expiry: Optional[float] = None, max_retransmits: Optional[int] = None, ordered: bool = True) -> None
719,025
aiortc.rtcsctptransport
_send_chunk
Transmit a chunk (no bundling for now).
@no_type_check async def _send( self, stream_id: int, pp_id: int, user_data: bytes, expiry: Optional[float] = None, max_retransmits: Optional[int] = None, ordered: bool = True, ) -> None: """ Send data ULP -> stream. """ if ordered: stream_seq = self._outbound_stream_seq.get(stream_id, 0) else: stream_seq = 0 fragments = math.ceil(len(user_data) / USERDATA_MAX_LENGTH) pos = 0 for fragment in range(0, fragments): chunk = DataChunk() chunk.flags = 0 if not ordered: chunk.flags = SCTP_DATA_UNORDERED if fragment == 0: chunk.flags |= SCTP_DATA_FIRST_FRAG if fragment == fragments - 1: chunk.flags |= SCTP_DATA_LAST_FRAG chunk.tsn = self._local_tsn chunk.stream_id = stream_id chunk.stream_seq = stream_seq chunk.protocol = pp_id chunk.user_data = user_data[pos : pos + USERDATA_MAX_LENGTH] # FIXME: dynamically added attributes, mypy can't handle them # initialize counters chunk._abandoned = False chunk._acked = False chunk._book_size = len(chunk.user_data) chunk._expiry = expiry chunk._max_retransmits = max_retransmits chunk._misses = 0 chunk._retransmit = False chunk._sent_count = 0 chunk._sent_time = None pos += USERDATA_MAX_LENGTH self._local_tsn = tsn_plus_one(self._local_tsn) self._outbound_queue.append(chunk) if ordered: self._outbound_stream_seq[stream_id] = uint16_add(stream_seq, 1) # transmit outbound data await self._transmit()
(self, chunk: aiortc.rtcsctptransport.Chunk) -> NoneType
719,026
aiortc.rtcsctptransport
_send_reconfig_param
null
@no_type_check async def _send( self, stream_id: int, pp_id: int, user_data: bytes, expiry: Optional[float] = None, max_retransmits: Optional[int] = None, ordered: bool = True, ) -> None: """ Send data ULP -> stream. """ if ordered: stream_seq = self._outbound_stream_seq.get(stream_id, 0) else: stream_seq = 0 fragments = math.ceil(len(user_data) / USERDATA_MAX_LENGTH) pos = 0 for fragment in range(0, fragments): chunk = DataChunk() chunk.flags = 0 if not ordered: chunk.flags = SCTP_DATA_UNORDERED if fragment == 0: chunk.flags |= SCTP_DATA_FIRST_FRAG if fragment == fragments - 1: chunk.flags |= SCTP_DATA_LAST_FRAG chunk.tsn = self._local_tsn chunk.stream_id = stream_id chunk.stream_seq = stream_seq chunk.protocol = pp_id chunk.user_data = user_data[pos : pos + USERDATA_MAX_LENGTH] # FIXME: dynamically added attributes, mypy can't handle them # initialize counters chunk._abandoned = False chunk._acked = False chunk._book_size = len(chunk.user_data) chunk._expiry = expiry chunk._max_retransmits = max_retransmits chunk._misses = 0 chunk._retransmit = False chunk._sent_count = 0 chunk._sent_time = None pos += USERDATA_MAX_LENGTH self._local_tsn = tsn_plus_one(self._local_tsn) self._outbound_queue.append(chunk) if ordered: self._outbound_stream_seq[stream_id] = uint16_add(stream_seq, 1) # transmit outbound data await self._transmit()
(self, param)
719,027
aiortc.rtcsctptransport
_send_sack
Build and send a selective acknowledgement (SACK) chunk.
@no_type_check async def _send( self, stream_id: int, pp_id: int, user_data: bytes, expiry: Optional[float] = None, max_retransmits: Optional[int] = None, ordered: bool = True, ) -> None: """ Send data ULP -> stream. """ if ordered: stream_seq = self._outbound_stream_seq.get(stream_id, 0) else: stream_seq = 0 fragments = math.ceil(len(user_data) / USERDATA_MAX_LENGTH) pos = 0 for fragment in range(0, fragments): chunk = DataChunk() chunk.flags = 0 if not ordered: chunk.flags = SCTP_DATA_UNORDERED if fragment == 0: chunk.flags |= SCTP_DATA_FIRST_FRAG if fragment == fragments - 1: chunk.flags |= SCTP_DATA_LAST_FRAG chunk.tsn = self._local_tsn chunk.stream_id = stream_id chunk.stream_seq = stream_seq chunk.protocol = pp_id chunk.user_data = user_data[pos : pos + USERDATA_MAX_LENGTH] # FIXME: dynamically added attributes, mypy can't handle them # initialize counters chunk._abandoned = False chunk._acked = False chunk._book_size = len(chunk.user_data) chunk._expiry = expiry chunk._max_retransmits = max_retransmits chunk._misses = 0 chunk._retransmit = False chunk._sent_count = 0 chunk._sent_time = None pos += USERDATA_MAX_LENGTH self._local_tsn = tsn_plus_one(self._local_tsn) self._outbound_queue.append(chunk) if ordered: self._outbound_stream_seq[stream_id] = uint16_add(stream_seq, 1) # transmit outbound data await self._transmit()
(self)
719,028
aiortc.rtcsctptransport
_set_extensions
Sets what extensions are supported by the local party.
def _set_extensions(self, params: List[Tuple[int, bytes]]) -> None: """ Sets what extensions are supported by the local party. """ extensions = [] if self._local_partial_reliability: params.append((SCTP_PRSCTP_SUPPORTED, b"")) extensions.append(ForwardTsnChunk.type) extensions.append(ReconfigChunk.type) params.append((SCTP_SUPPORTED_CHUNK_EXT, bytes(extensions)))
(self, params: List[Tuple[int, bytes]]) -> NoneType
719,029
aiortc.rtcsctptransport
_set_state
Transition the SCTP association to a new state.
def _set_state(self, state) -> None: """ Transition the SCTP association to a new state. """ if state != self._association_state: self.__log_debug("- %s -> %s", self._association_state, state) self._association_state = state if state == self.State.ESTABLISHED: self.__state = "connected" for channel in list(self._data_channels.values()): if channel.negotiated and channel.readyState != "open": channel._setReadyState("open") asyncio.ensure_future(self._data_channel_flush()) elif state == self.State.CLOSED: self._t1_cancel() self._t2_cancel() self._t3_cancel() self.__state = "closed" # close data channels for stream_id in list(self._data_channels.keys()): self._data_channel_closed(stream_id) # no more events will be emitted, so remove all event listeners # to facilitate garbage collection. self.remove_all_listeners()
(self, state) -> NoneType
719,030
aiortc.rtcsctptransport
_t1_cancel
null
def _t1_cancel(self) -> None: if self._t1_handle is not None: self.__log_debug("- T1(%s) cancel", chunk_type(self._t1_chunk)) self._t1_handle.cancel() self._t1_handle = None self._t1_chunk = None
(self) -> NoneType