code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
194
| url
stringlengths 46
254
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def unwrap_rtx(rtx: RtpPacket, payload_type: int, ssrc: int) -> RtpPacket:
"""
Recover initial packet from a retransmission packet.
"""
packet = RtpPacket(
payload_type=payload_type,
marker=rtx.marker,
sequence_number=unpack("!H", rtx.payload[0:2])[0],
timestamp=rtx.timestamp,
ssrc=ssrc,
payload=rtx.payload[2:],
)
packet.csrc = rtx.csrc
packet.extensions = rtx.extensions
return packet | Recover initial packet from a retransmission packet. | unwrap_rtx | python | aiortc/aiortc | src/aiortc/rtp.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtp.py | BSD-3-Clause |
def wrap_rtx(
packet: RtpPacket, payload_type: int, sequence_number: int, ssrc: int
) -> RtpPacket:
"""
Create a retransmission packet from a lost packet.
"""
rtx = RtpPacket(
payload_type=payload_type,
marker=packet.marker,
sequence_number=sequence_number,
timestamp=packet.timestamp,
ssrc=ssrc,
payload=pack("!H", packet.sequence_number) + packet.payload,
)
rtx.csrc = packet.csrc
rtx.extensions = packet.extensions
return rtx | Create a retransmission packet from a lost packet. | wrap_rtx | python | aiortc/aiortc | src/aiortc/rtp.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtp.py | BSD-3-Clause |
def random_sequence_number() -> int:
"""
Generate a random RTP sequence number.
The sequence number is chosen in the lower half of the allowed range in
order to avoid wraparounds which break SRTP decryption.
See:
https://chromiumdash.appspot.com/commit/13b327b05fa3788b4daa9c3463e13282824cb320
"""
return random16() % 32768 | Generate a random RTP sequence number.
The sequence number is chosen in the lower half of the allowed range in
order to avoid wraparounds which break SRTP decryption.
See:
https://chromiumdash.appspot.com/commit/13b327b05fa3788b4daa9c3463e13282824cb320 | random_sequence_number | python | aiortc/aiortc | src/aiortc/rtcrtpsender.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtpsender.py | BSD-3-Clause |
def track(self) -> MediaStreamTrack:
"""
The :class:`MediaStreamTrack` which is being handled by the sender.
"""
return self.__track | The :class:`MediaStreamTrack` which is being handled by the sender. | track | python | aiortc/aiortc | src/aiortc/rtcrtpsender.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtpsender.py | BSD-3-Clause |
def transport(self):
"""
The :class:`RTCDtlsTransport` over which media data for the track is
transmitted.
"""
return self.__transport | The :class:`RTCDtlsTransport` over which media data for the track is
transmitted. | transport | python | aiortc/aiortc | src/aiortc/rtcrtpsender.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtpsender.py | BSD-3-Clause |
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) | Returns the most optimistic view of the system's capabilities for
sending media of the given `kind`.
:rtype: :class:`RTCRtpCapabilities` | getCapabilities | python | aiortc/aiortc | src/aiortc/rtcrtpsender.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtpsender.py | BSD-3-Clause |
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 | Returns statistics about the RTP sender.
:rtype: :class:`RTCStatsReport` | getStats | python | aiortc/aiortc | src/aiortc/rtcrtpsender.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtpsender.py | BSD-3-Clause |
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 | Attempt to set the parameters controlling the sending of media.
:param parameters: The :class:`RTCRtpSendParameters` for the sender. | send | python | aiortc/aiortc | src/aiortc/rtcrtpsender.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtpsender.py | BSD-3-Clause |
async def stop(self) -> None:
"""
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()) | Irreversibly stop the sender. | stop | python | aiortc/aiortc | src/aiortc/rtcrtpsender.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtpsender.py | BSD-3-Clause |
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) | Retransmit an RTP packet which was reported as lost. | _retransmit | python | aiortc/aiortc | src/aiortc/rtcrtpsender.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtpsender.py | BSD-3-Clause |
def _send_keyframe(self) -> None:
"""
Request the next frame to be a keyframe.
"""
self.__force_keyframe = True | Request the next frame to be a keyframe. | _send_keyframe | python | aiortc/aiortc | src/aiortc/rtcrtpsender.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtpsender.py | BSD-3-Clause |
def uint16_add(a: int, b: int) -> int:
"""
Return a + b.
"""
return (a + b) & 0xFFFF | Return a + b. | uint16_add | python | aiortc/aiortc | src/aiortc/utils.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/utils.py | BSD-3-Clause |
def uint16_gt(a: int, b: int) -> bool:
"""
Return a > b.
"""
half_mod = 0x8000
return ((a < b) and ((b - a) > half_mod)) or ((a > b) and ((a - b) < half_mod)) | Return a > b. | uint16_gt | python | aiortc/aiortc | src/aiortc/utils.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/utils.py | BSD-3-Clause |
def uint16_gte(a: int, b: int) -> bool:
"""
Return a >= b.
"""
return (a == b) or uint16_gt(a, b) | Return a >= b. | uint16_gte | python | aiortc/aiortc | src/aiortc/utils.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/utils.py | BSD-3-Clause |
def uint32_add(a: int, b: int) -> int:
"""
Return a + b.
"""
return (a + b) & 0xFFFFFFFF | Return a + b. | uint32_add | python | aiortc/aiortc | src/aiortc/utils.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/utils.py | BSD-3-Clause |
def uint32_gt(a: int, b: int) -> bool:
"""
Return a > b.
"""
half_mod = 0x80000000
return ((a < b) and ((b - a) > half_mod)) or ((a > b) and ((a - b) < half_mod)) | Return a > b. | uint32_gt | python | aiortc/aiortc | src/aiortc/utils.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/utils.py | BSD-3-Clause |
def uint32_gte(a: int, b: int) -> bool:
"""
Return a >= b.
"""
return (a == b) or uint32_gt(a, b) | Return a >= b. | uint32_gte | python | aiortc/aiortc | src/aiortc/utils.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/utils.py | BSD-3-Clause |
def add(self, packet: RtpPacket) -> bool:
"""
Mark a new packet as received, and deduce missing packets.
"""
missed = False
if self.max_seq is None:
self.max_seq = packet.sequence_number
return missed
# mark missing packets
if uint16_gt(packet.sequence_number, self.max_seq):
seq = uint16_add(self.max_seq, 1)
while uint16_gt(packet.sequence_number, seq):
self.missing.add(seq)
missed = True
seq = uint16_add(seq, 1)
self.max_seq = packet.sequence_number
else:
self.missing.discard(packet.sequence_number)
# limit number of tracked packets
self.truncate()
return missed | Mark a new packet as received, and deduce missing packets. | add | python | aiortc/aiortc | src/aiortc/rtcrtpreceiver.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtpreceiver.py | BSD-3-Clause |
def truncate(self) -> None:
"""
Limit the number of missing packets we track.
Otherwise, the size of RTCP FB messages grows indefinitely.
"""
if self.max_seq is not None:
min_seq = uint16_add(self.max_seq, -RTP_HISTORY_SIZE)
for seq in list(self.missing):
if uint16_gt(min_seq, seq):
self.missing.discard(seq) | Limit the number of missing packets we track.
Otherwise, the size of RTCP FB messages grows indefinitely. | truncate | python | aiortc/aiortc | src/aiortc/rtcrtpreceiver.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtpreceiver.py | BSD-3-Clause |
async def recv(self) -> Frame:
"""
Receive the next frame.
"""
if self.readyState != "live":
raise MediaStreamError
frame = await self._queue.get()
if frame is None:
self.stop()
raise MediaStreamError
return frame | Receive the next frame. | recv | python | aiortc/aiortc | src/aiortc/rtcrtpreceiver.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtpreceiver.py | BSD-3-Clause |
def track(self) -> MediaStreamTrack:
"""
The :class:`MediaStreamTrack` which is being handled by the receiver.
"""
return self._track | The :class:`MediaStreamTrack` which is being handled by the receiver. | track | python | aiortc/aiortc | src/aiortc/rtcrtpreceiver.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtpreceiver.py | BSD-3-Clause |
def transport(self) -> RTCDtlsTransport:
"""
The :class:`RTCDtlsTransport` over which the media for the receiver's
track is received.
"""
return self.__transport | The :class:`RTCDtlsTransport` over which the media for the receiver's
track is received. | transport | python | aiortc/aiortc | src/aiortc/rtcrtpreceiver.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtpreceiver.py | BSD-3-Clause |
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) | Returns the most optimistic view of the system's capabilities for
receiving media of the given `kind`.
:rtype: :class:`RTCRtpCapabilities` | getCapabilities | python | aiortc/aiortc | src/aiortc/rtcrtpreceiver.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtpreceiver.py | BSD-3-Clause |
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 | Returns statistics about the RTP receiver.
:rtype: :class:`RTCStatsReport` | getStats | python | aiortc/aiortc | src/aiortc/rtcrtpreceiver.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtpreceiver.py | BSD-3-Clause |
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 | Returns a :class:`RTCRtpSynchronizationSource` for each unique SSRC identifier
received in the last 10 seconds. | getSynchronizationSources | python | aiortc/aiortc | src/aiortc/rtcrtpreceiver.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtpreceiver.py | BSD-3-Clause |
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 | Attempt to set the parameters controlling the receiving of media.
:param parameters: The :class:`RTCRtpParameters` for the receiver. | receive | python | aiortc/aiortc | src/aiortc/rtcrtpreceiver.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtpreceiver.py | BSD-3-Clause |
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() | Irreversibly stop the receiver. | stop | python | aiortc/aiortc | src/aiortc/rtcrtpreceiver.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtpreceiver.py | BSD-3-Clause |
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
apt = codec.parameters.get("apt")
if (
len(packet.payload) < 2
or not isinstance(apt, int)
or apt not in self.__codecs
):
return
packet = unwrap_rtx(packet, payload_type=apt, 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)) | Handle an incoming RTP packet. | _handle_rtp_packet | python | aiortc/aiortc | src/aiortc/rtcrtpreceiver.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtpreceiver.py | BSD-3-Clause |
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) | Send an RTCP packet to report missing RTP packets. | _send_rtcp_nack | python | aiortc/aiortc | src/aiortc/rtcrtpreceiver.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtpreceiver.py | BSD-3-Clause |
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) | Send an RTCP packet to report picture loss. | _send_rtcp_pli | python | aiortc/aiortc | src/aiortc/rtcrtpreceiver.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtpreceiver.py | BSD-3-Clause |
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 | Stop the decoder thread, which will in turn stop the track. | __stop_decoder | python | aiortc/aiortc | src/aiortc/rtcrtpreceiver.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtpreceiver.py | BSD-3-Clause |
def currentDirection(self) -> Optional[str]:
"""
The currently negotiated direction of the transceiver.
One of `'sendrecv'`, `'sendonly'`, `'recvonly'`, `'inactive'` or `None`.
"""
return self.__currentDirection | The currently negotiated direction of the transceiver.
One of `'sendrecv'`, `'sendonly'`, `'recvonly'`, `'inactive'` or `None`. | currentDirection | python | aiortc/aiortc | src/aiortc/rtcrtptransceiver.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtptransceiver.py | BSD-3-Clause |
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 | 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'`. | direction | python | aiortc/aiortc | src/aiortc/rtcrtptransceiver.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtptransceiver.py | BSD-3-Clause |
def receiver(self) -> RTCRtpReceiver:
"""
The :class:`RTCRtpReceiver` that handles receiving and decoding
incoming media.
"""
return self.__receiver | The :class:`RTCRtpReceiver` that handles receiving and decoding
incoming media. | receiver | python | aiortc/aiortc | src/aiortc/rtcrtptransceiver.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtptransceiver.py | BSD-3-Clause |
def sender(self) -> RTCRtpSender:
"""
The :class:`RTCRtpSender` responsible for encoding and sending
data to the remote peer.
"""
return self.__sender | The :class:`RTCRtpSender` responsible for encoding and sending
data to the remote peer. | sender | python | aiortc/aiortc | src/aiortc/rtcrtptransceiver.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtptransceiver.py | BSD-3-Clause |
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 | 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. | setCodecPreferences | python | aiortc/aiortc | src/aiortc/rtcrtptransceiver.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtptransceiver.py | BSD-3-Clause |
async def stop(self) -> None:
"""
Permanently stops the :class:`RTCRtpTransceiver`.
"""
await self.__receiver.stop()
await self.__sender.stop()
self.__stopped = True | Permanently stops the :class:`RTCRtpTransceiver`. | stop | python | aiortc/aiortc | src/aiortc/rtcrtptransceiver.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcrtptransceiver.py | BSD-3-Clause |
def state(self) -> str:
"""
The current state of the ICE gatherer.
"""
return self.__state | The current state of the ICE gatherer. | state | python | aiortc/aiortc | src/aiortc/rtcicetransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcicetransport.py | BSD-3-Clause |
async def gather(self) -> None:
"""
Gather ICE candidates.
"""
if self.__state == "new":
self.__setState("gathering")
await self._connection.gather_candidates()
self.__setState("completed") | Gather ICE candidates. | gather | python | aiortc/aiortc | src/aiortc/rtcicetransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcicetransport.py | BSD-3-Clause |
def getDefaultIceServers(cls) -> List[RTCIceServer]:
"""
Return the list of default :class:`RTCIceServer`.
"""
return [RTCIceServer("stun:stun.l.google.com:19302")] | Return the list of default :class:`RTCIceServer`. | getDefaultIceServers | python | aiortc/aiortc | src/aiortc/rtcicetransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcicetransport.py | BSD-3-Clause |
def getLocalCandidates(self) -> List[RTCIceCandidate]:
"""
Retrieve the list of valid local candidates associated with the ICE
gatherer.
"""
return [candidate_from_aioice(x) for x in self._connection.local_candidates] | Retrieve the list of valid local candidates associated with the ICE
gatherer. | getLocalCandidates | python | aiortc/aiortc | src/aiortc/rtcicetransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcicetransport.py | BSD-3-Clause |
def getLocalParameters(self) -> RTCIceParameters:
"""
Retrieve the ICE parameters of the ICE gatherer.
:rtype: RTCIceParameters
"""
return RTCIceParameters(
usernameFragment=self._connection.local_username,
password=self._connection.local_password,
) | Retrieve the ICE parameters of the ICE gatherer.
:rtype: RTCIceParameters | getLocalParameters | python | aiortc/aiortc | src/aiortc/rtcicetransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcicetransport.py | BSD-3-Clause |
def iceGatherer(self) -> RTCIceGatherer:
"""
The ICE gatherer passed in the constructor.
"""
return self.__iceGatherer | The ICE gatherer passed in the constructor. | iceGatherer | python | aiortc/aiortc | src/aiortc/rtcicetransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcicetransport.py | BSD-3-Clause |
def role(self) -> str:
"""
The current role of the ICE transport.
Either `'controlling'` or `'controlled'`.
"""
if self._connection.ice_controlling:
return "controlling"
else:
return "controlled" | The current role of the ICE transport.
Either `'controlling'` or `'controlled'`. | role | python | aiortc/aiortc | src/aiortc/rtcicetransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcicetransport.py | BSD-3-Clause |
def state(self) -> str:
"""
The current state of the ICE transport.
"""
return self.__state | The current state of the ICE transport. | state | python | aiortc/aiortc | src/aiortc/rtcicetransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcicetransport.py | BSD-3-Clause |
async def addRemoteCandidate(self, candidate: Optional[RTCIceCandidate]) -> None:
"""
Add a remote candidate.
:param candidate: The new candidate or `None` to signal end of candidates.
"""
if not self.__iceGatherer._remote_candidates_end:
if candidate is None:
self.__iceGatherer._remote_candidates_end = True
await self._connection.add_remote_candidate(None)
else:
await self._connection.add_remote_candidate(
candidate_to_aioice(candidate)
) | Add a remote candidate.
:param candidate: The new candidate or `None` to signal end of candidates. | addRemoteCandidate | python | aiortc/aiortc | src/aiortc/rtcicetransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcicetransport.py | BSD-3-Clause |
def getRemoteCandidates(self) -> List[RTCIceCandidate]:
"""
Retrieve the list of candidates associated with the remote
:class:`RTCIceTransport`.
"""
return [candidate_from_aioice(x) for x in self._connection.remote_candidates] | Retrieve the list of candidates associated with the remote
:class:`RTCIceTransport`. | getRemoteCandidates | python | aiortc/aiortc | src/aiortc/rtcicetransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcicetransport.py | BSD-3-Clause |
async def start(self, remoteParameters: RTCIceParameters) -> None:
"""
Initiate connectivity checks.
:param remoteParameters: The :class:`RTCIceParameters` associated with
the remote :class:`RTCIceTransport`.
"""
if self.state == "closed":
raise InvalidStateError("RTCIceTransport is closed")
# handle the case where start is already in progress
if self.__start is not None:
await self.__start.wait()
return
self.__start = asyncio.Event()
self.__monitor_task = asyncio.ensure_future(self._monitor())
self.__setState("checking")
self._connection.remote_is_lite = remoteParameters.iceLite
self._connection.remote_username = remoteParameters.usernameFragment
self._connection.remote_password = remoteParameters.password
try:
await self._connection.connect()
except ConnectionError:
self.__setState("failed")
else:
self.__setState("completed")
self.__start.set() | Initiate connectivity checks.
:param remoteParameters: The :class:`RTCIceParameters` associated with
the remote :class:`RTCIceTransport`. | start | python | aiortc/aiortc | src/aiortc/rtcicetransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcicetransport.py | BSD-3-Clause |
async def stop(self) -> None:
"""
Irreversibly stop the :class:`RTCIceTransport`.
"""
if self.state != "closed":
self.__setState("closed")
await self._connection.close()
if self.__monitor_task is not None:
await self.__monitor_task
self.__monitor_task = None | Irreversibly stop the :class:`RTCIceTransport`. | stop | python | aiortc/aiortc | src/aiortc/rtcicetransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcicetransport.py | BSD-3-Clause |
def smart_remove(self, count: int) -> bool:
"""
Makes sure that all packages belonging to the same frame are removed
to prevent sending corrupted frames to the decoder.
"""
timestamp = None
for i in range(self._capacity):
pos = self._origin % self._capacity
packet = self._packets[pos]
if packet is not None:
if i >= count and timestamp != packet.timestamp:
break
timestamp = packet.timestamp
self._packets[pos] = None
self._origin = uint16_add(self._origin, 1)
if i == self._capacity - 1:
return True
return False | Makes sure that all packages belonging to the same frame are removed
to prevent sending corrupted frames to the decoder. | smart_remove | python | aiortc/aiortc | src/aiortc/jitterbuffer.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/jitterbuffer.py | BSD-3-Clause |
def set_estimate(self, bitrate: int, now_ms: int) -> None:
"""
For testing purposes.
"""
self.current_bitrate = self._clamp_bitrate(bitrate, bitrate)
self.current_bitrate_initialized = True
self.last_change_ms = now_ms | For testing purposes. | set_estimate | python | aiortc/aiortc | src/aiortc/rate.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rate.py | BSD-3-Clause |
def id(self) -> str:
"""
An automatically generated globally unique ID.
"""
return self._id | An automatically generated globally unique ID. | id | python | aiortc/aiortc | src/aiortc/mediastreams.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/mediastreams.py | BSD-3-Clause |
async def recv(self) -> Union[Frame, Packet]:
"""
Receive the next :class:`~av.audio.frame.AudioFrame`,
:class:`~av.video.frame.VideoFrame` or :class:`~av.packet.Packet`
""" | Receive the next :class:`~av.audio.frame.AudioFrame`,
:class:`~av.video.frame.VideoFrame` or :class:`~av.packet.Packet` | recv | python | aiortc/aiortc | src/aiortc/mediastreams.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/mediastreams.py | BSD-3-Clause |
async def recv(self) -> Frame:
"""
Receive the next :class:`~av.audio.frame.AudioFrame`.
The base implementation just reads silence, subclass
:class:`AudioStreamTrack` to provide a useful implementation.
"""
if self.readyState != "live":
raise MediaStreamError
sample_rate = 8000
samples = int(AUDIO_PTIME * sample_rate)
if hasattr(self, "_timestamp"):
self._timestamp += samples
wait = self._start + (self._timestamp / sample_rate) - time.time()
await asyncio.sleep(wait)
else:
self._start = time.time()
self._timestamp = 0
frame = AudioFrame(format="s16", layout="mono", samples=samples)
for p in frame.planes:
p.update(bytes(p.buffer_size))
frame.pts = self._timestamp
frame.sample_rate = sample_rate
frame.time_base = fractions.Fraction(1, sample_rate)
return frame | Receive the next :class:`~av.audio.frame.AudioFrame`.
The base implementation just reads silence, subclass
:class:`AudioStreamTrack` to provide a useful implementation. | recv | python | aiortc/aiortc | src/aiortc/mediastreams.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/mediastreams.py | BSD-3-Clause |
async def recv(self) -> Frame:
"""
Receive the next :class:`~av.video.frame.VideoFrame`.
The base implementation just reads a 640x480 green frame at 30fps,
subclass :class:`VideoStreamTrack` to provide a useful implementation.
"""
pts, time_base = await self.next_timestamp()
frame = VideoFrame(width=640, height=480)
for p in frame.planes:
p.update(bytes(p.buffer_size))
frame.pts = pts
frame.time_base = time_base
return frame | Receive the next :class:`~av.video.frame.VideoFrame`.
The base implementation just reads a 640x480 green frame at 30fps,
subclass :class:`VideoStreamTrack` to provide a useful implementation. | recv | python | aiortc/aiortc | src/aiortc/mediastreams.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/mediastreams.py | BSD-3-Clause |
def allocate_mid(mids: Set[str]) -> str:
"""
Allocate a MID which has not been used yet.
"""
i = 0
while True:
mid = str(i)
if mid not in mids:
mids.add(mid)
return mid
i += 1 | Allocate a MID which has not been used yet. | allocate_mid | python | aiortc/aiortc | src/aiortc/rtcpeerconnection.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcpeerconnection.py | BSD-3-Clause |
def connectionState(self) -> str:
"""
The current connection state.
Possible values: `"connected"`, `"connecting"`, `"closed"`, `"failed"`, `"new`".
When the state changes, the `"connectionstatechange"` event is fired.
"""
return self.__connectionState | The current connection state.
Possible values: `"connected"`, `"connecting"`, `"closed"`, `"failed"`, `"new`".
When the state changes, the `"connectionstatechange"` event is fired. | connectionState | python | aiortc/aiortc | src/aiortc/rtcpeerconnection.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcpeerconnection.py | BSD-3-Clause |
def iceConnectionState(self) -> str:
"""
The current ICE connection state.
Possible values: `"checking"`, `"completed"`, `"closed"`, `"failed"`, `"new`".
When the state changes, the `"iceconnectionstatechange"` event is fired.
"""
return self.__iceConnectionState | The current ICE connection state.
Possible values: `"checking"`, `"completed"`, `"closed"`, `"failed"`, `"new`".
When the state changes, the `"iceconnectionstatechange"` event is fired. | iceConnectionState | python | aiortc/aiortc | src/aiortc/rtcpeerconnection.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcpeerconnection.py | BSD-3-Clause |
def iceGatheringState(self) -> str:
"""
The current ICE gathering state.
Possible values: `"complete"`, `"gathering"`, `"new`".
When the state changes, the `"icegatheringstatechange"` event is fired.
"""
return self.__iceGatheringState | The current ICE gathering state.
Possible values: `"complete"`, `"gathering"`, `"new`".
When the state changes, the `"icegatheringstatechange"` event is fired. | iceGatheringState | python | aiortc/aiortc | src/aiortc/rtcpeerconnection.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcpeerconnection.py | BSD-3-Clause |
def localDescription(self) -> RTCSessionDescription:
"""
An :class:`RTCSessionDescription` describing the session for
the local end of the connection.
"""
return wrap_session_description(self.__localDescription()) | An :class:`RTCSessionDescription` describing the session for
the local end of the connection. | localDescription | python | aiortc/aiortc | src/aiortc/rtcpeerconnection.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcpeerconnection.py | BSD-3-Clause |
def remoteDescription(self) -> RTCSessionDescription:
"""
An :class:`RTCSessionDescription` describing the session for
the remote end of the connection.
"""
return wrap_session_description(self.__remoteDescription()) | An :class:`RTCSessionDescription` describing the session for
the remote end of the connection. | remoteDescription | python | aiortc/aiortc | src/aiortc/rtcpeerconnection.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcpeerconnection.py | BSD-3-Clause |
def sctp(self) -> Optional[RTCSctpTransport]:
"""
An :class:`RTCSctpTransport` describing the SCTP transport being used
for datachannels or `None`.
"""
return self.__sctp | An :class:`RTCSctpTransport` describing the SCTP transport being used
for datachannels or `None`. | sctp | python | aiortc/aiortc | src/aiortc/rtcpeerconnection.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcpeerconnection.py | BSD-3-Clause |
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 | The current signaling state.
Possible values: `"closed"`, `"have-local-offer"`, `"have-remote-offer`",
`"stable"`.
When the state changes, the `"signalingstatechange"` event is fired. | signalingState | python | aiortc/aiortc | src/aiortc/rtcpeerconnection.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcpeerconnection.py | BSD-3-Clause |
async def addIceCandidate(self, candidate: RTCIceCandidate) -> None:
"""
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.
"""
if candidate.sdpMid is None and candidate.sdpMLineIndex is None:
raise ValueError("Candidate must have either sdpMid or sdpMLineIndex")
for transceiver in self.__transceivers:
if candidate.sdpMid == transceiver.mid and not transceiver._bundled:
iceTransport = transceiver._transport.transport
await iceTransport.addRemoteCandidate(candidate)
return
if (
self.__sctp
and candidate.sdpMid == self.__sctp.mid
and not self.__sctp._bundled
):
iceTransport = self.__sctp.transport.transport
await iceTransport.addRemoteCandidate(candidate) | 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. | addIceCandidate | python | aiortc/aiortc | src/aiortc/rtcpeerconnection.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcpeerconnection.py | BSD-3-Clause |
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 | Add a :class:`MediaStreamTrack` to the set of media tracks which
will be transmitted to the remote peer. | addTrack | python | aiortc/aiortc | src/aiortc/rtcpeerconnection.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcpeerconnection.py | BSD-3-Clause |
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
) | Add a new :class:`RTCRtpTransceiver`. | addTransceiver | python | aiortc/aiortc | src/aiortc/rtcpeerconnection.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcpeerconnection.py | BSD-3-Clause |
async def close(self) -> None:
"""
Terminate the ICE agent, ending ICE processing and streams.
"""
if self.__isClosed:
await self.__isClosed
return
self.__isClosed = asyncio.Future()
self.__setSignalingState("closed")
# stop senders / receivers
for transceiver in self.__transceivers:
await transceiver.stop()
if self.__sctp:
await self.__sctp.stop()
# stop transports
for transceiver in self.__transceivers:
await transceiver._transport.stop()
await transceiver._transport.transport.stop()
if self.__sctp:
await self.__sctp.transport.stop()
await self.__sctp.transport.transport.stop()
# update states
self.__updateIceGatheringState()
self.__updateIceConnectionState()
self.__updateConnectionState()
# no more events will be emitted, so remove all event listeners
# to facilitate garbage collection.
self.remove_all_listeners()
self.__isClosed.set_result(True) | Terminate the ICE agent, ending ICE processing and streams. | close | python | aiortc/aiortc | src/aiortc/rtcpeerconnection.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcpeerconnection.py | BSD-3-Clause |
async def createAnswer(self) -> RTCSessionDescription:
"""
Create an SDP answer to an offer received from a remote peer during
the offer/answer negotiation of a WebRTC connection.
:rtype: :class:`RTCSessionDescription`
"""
# check state is valid
self.__assertNotClosed()
if self.signalingState not in ["have-remote-offer", "have-local-pranswer"]:
raise InvalidStateError(
f'Cannot create answer in signaling state "{self.signalingState}"'
)
# create description
ntp_seconds = clock.current_ntp_time() >> 32
description = sdp.SessionDescription()
description.origin = f"- {ntp_seconds} {ntp_seconds} IN IP4 0.0.0.0"
description.msid_semantic.append(
sdp.GroupDescription(semantic="WMS", items=["*"])
)
description.type = "answer"
for remote_m in self.__remoteDescription().media:
if remote_m.kind in ["audio", "video"]:
transceiver = self.__getTransceiverByMid(remote_m.rtp.muxId)
media = create_media_description_for_transceiver(
transceiver,
cname=self.__cname,
direction=and_direction(
transceiver.direction, transceiver._offerDirection
),
mid=transceiver.mid,
)
dtlsTransport = transceiver._transport
else:
media = create_media_description_for_sctp(
self.__sctp, legacy=self._sctpLegacySdp, mid=self.__sctp.mid
)
dtlsTransport = self.__sctp.transport
# determine DTLS role, or preserve the currently configured role
if dtlsTransport._role == "auto":
media.dtls.role = "client"
else:
media.dtls.role = dtlsTransport._role
description.media.append(media)
bundle = sdp.GroupDescription(semantic="BUNDLE", items=[])
for media in description.media:
bundle.items.append(media.rtp.muxId)
description.group.append(bundle)
return wrap_session_description(description) | Create an SDP answer to an offer received from a remote peer during
the offer/answer negotiation of a WebRTC connection.
:rtype: :class:`RTCSessionDescription` | createAnswer | python | aiortc/aiortc | src/aiortc/rtcpeerconnection.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcpeerconnection.py | BSD-3-Clause |
def createDataChannel(
self,
label,
maxPacketLifeTime=None,
maxRetransmits=None,
ordered=True,
protocol="",
negotiated=False,
id=None,
) -> RTCDataChannel:
"""
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) | Create a data channel with the given label.
:rtype: :class:`RTCDataChannel` | createDataChannel | python | aiortc/aiortc | src/aiortc/rtcpeerconnection.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcpeerconnection.py | BSD-3-Clause |
async def createOffer(self) -> RTCSessionDescription:
"""
Create an SDP offer for the purpose of starting a new WebRTC
connection to a remote peer.
:rtype: :class:`RTCSessionDescription`
"""
# check state is valid
self.__assertNotClosed()
if not self.__sctp and not self.__transceivers:
raise InternalError(
"Cannot create an offer with no media and no data channels"
)
# offer codecs
for transceiver in self.__transceivers:
transceiver._codecs = filter_preferred_codecs(
CODECS[transceiver.kind][:], transceiver._preferred_codecs
)
transceiver._headerExtensions = HEADER_EXTENSIONS[transceiver.kind][:]
mids = self.__seenMids.copy()
# create description
ntp_seconds = clock.current_ntp_time() >> 32
description = sdp.SessionDescription()
description.origin = f"- {ntp_seconds} {ntp_seconds} IN IP4 0.0.0.0"
description.msid_semantic.append(
sdp.GroupDescription(semantic="WMS", items=["*"])
)
description.type = "offer"
def get_media(
description: sdp.SessionDescription,
) -> List[sdp.MediaDescription]:
return description.media if description else []
def get_media_section(
media: List[sdp.MediaDescription], i: int
) -> Optional[sdp.MediaDescription]:
return media[i] if i < len(media) else None
# handle existing transceivers / sctp
local_media = get_media(self.__localDescription())
remote_media = get_media(self.__remoteDescription())
for i in range(max(len(local_media), len(remote_media))):
local_m = get_media_section(local_media, i)
remote_m = get_media_section(remote_media, i)
media_kind = local_m.kind if local_m else remote_m.kind
mid = local_m.rtp.muxId if local_m else remote_m.rtp.muxId
if media_kind in ["audio", "video"]:
transceiver = self.__getTransceiverByMid(mid)
transceiver._set_mline_index(i)
description.media.append(
create_media_description_for_transceiver(
transceiver,
cname=self.__cname,
direction=transceiver.direction,
mid=mid,
)
)
elif media_kind == "application":
self.__sctp_mline_index = i
description.media.append(
create_media_description_for_sctp(
self.__sctp, legacy=self._sctpLegacySdp, mid=mid
)
)
# handle new transceivers / sctp
def next_mline_index() -> int:
return len(description.media)
for transceiver in filter(
lambda x: x.mid is None and not x.stopped, self.__transceivers
):
transceiver._set_mline_index(next_mline_index())
description.media.append(
create_media_description_for_transceiver(
transceiver,
cname=self.__cname,
direction=transceiver.direction,
mid=allocate_mid(mids),
)
)
if self.__sctp and self.__sctp.mid is None:
self.__sctp_mline_index = next_mline_index()
description.media.append(
create_media_description_for_sctp(
self.__sctp, legacy=self._sctpLegacySdp, mid=allocate_mid(mids)
)
)
bundle = sdp.GroupDescription(semantic="BUNDLE", items=[])
for media in description.media:
bundle.items.append(media.rtp.muxId)
description.group.append(bundle)
return wrap_session_description(description) | Create an SDP offer for the purpose of starting a new WebRTC
connection to a remote peer.
:rtype: :class:`RTCSessionDescription` | createOffer | python | aiortc/aiortc | src/aiortc/rtcpeerconnection.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcpeerconnection.py | BSD-3-Clause |
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)) | Returns the list of :class:`RTCRtpReceiver` objects that are currently
attached to the connection. | getReceivers | python | aiortc/aiortc | src/aiortc/rtcpeerconnection.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcpeerconnection.py | BSD-3-Clause |
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)) | Returns the list of :class:`RTCRtpSender` objects that are currently
attached to the connection. | getSenders | python | aiortc/aiortc | src/aiortc/rtcpeerconnection.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcpeerconnection.py | BSD-3-Clause |
async def getStats(self) -> RTCStatsReport:
"""
Returns statistics for the connection.
:rtype: :class:`RTCStatsReport`
"""
merged = RTCStatsReport()
coros = [x.getStats() for x in self.getSenders()] + [
x.getStats() for x in self.getReceivers()
]
for report in await asyncio.gather(*coros):
merged.update(report)
return merged | Returns statistics for the connection.
:rtype: :class:`RTCStatsReport` | getStats | python | aiortc/aiortc | src/aiortc/rtcpeerconnection.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcpeerconnection.py | BSD-3-Clause |
def getTransceivers(self) -> List[RTCRtpTransceiver]:
"""
Returns the list of :class:`RTCRtpTransceiver` objects that are currently
attached to the connection.
"""
return list(self.__transceivers) | Returns the list of :class:`RTCRtpTransceiver` objects that are currently
attached to the connection. | getTransceivers | python | aiortc/aiortc | src/aiortc/rtcpeerconnection.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcpeerconnection.py | BSD-3-Clause |
async def setLocalDescription(
self, sessionDescription: RTCSessionDescription
) -> None:
"""
Change the local description associated with the connection.
:param sessionDescription: An :class:`RTCSessionDescription` generated
by :meth:`createOffer` or :meth:`createAnswer()`.
"""
self.__log_debug(
"setLocalDescription(%s)\n%s",
sessionDescription.type,
sessionDescription.sdp,
)
# parse and validate description
description = sdp.SessionDescription.parse(sessionDescription.sdp)
description.type = sessionDescription.type
self.__validate_description(description, is_local=True)
# update signaling state
if description.type == "offer":
self.__setSignalingState("have-local-offer")
elif description.type == "answer":
self.__setSignalingState("stable")
# assign MID
for i, media in enumerate(description.media):
mid = media.rtp.muxId
self.__seenMids.add(mid)
if media.kind in ["audio", "video"]:
transceiver = self.__getTransceiverByMLineIndex(i)
transceiver._set_mid(mid)
elif media.kind == "application":
self.__sctp.mid = mid
# set ICE role
if description.type == "offer":
for iceTransport in self.__iceTransports:
if not iceTransport._role_set:
iceTransport._connection.ice_controlling = True
iceTransport._role_set = True
# set DTLS role
if description.type == "answer":
for i, media in enumerate(description.media):
if media.kind in ["audio", "video"]:
transceiver = self.__getTransceiverByMLineIndex(i)
transceiver._transport._set_role(media.dtls.role)
elif media.kind == "application":
self.__sctp.transport._set_role(media.dtls.role)
# configure direction
for t in self.__transceivers:
if description.type in ["answer", "pranswer"]:
t._setCurrentDirection(and_direction(t.direction, t._offerDirection))
# gather candidates
await self.__gather()
for i, media in enumerate(description.media):
if media.kind in ["audio", "video"]:
transceiver = self.__getTransceiverByMLineIndex(i)
add_transport_description(media, transceiver._transport)
elif media.kind == "application":
add_transport_description(media, self.__sctp.transport)
# connect
asyncio.ensure_future(self.__connect())
# replace description
if description.type == "answer":
self.__currentLocalDescription = description
self.__pendingLocalDescription = None
else:
self.__pendingLocalDescription = description | Change the local description associated with the connection.
:param sessionDescription: An :class:`RTCSessionDescription` generated
by :meth:`createOffer` or :meth:`createAnswer()`. | setLocalDescription | python | aiortc/aiortc | src/aiortc/rtcpeerconnection.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcpeerconnection.py | BSD-3-Clause |
async def setRemoteDescription(
self, sessionDescription: RTCSessionDescription
) -> None:
"""
Changes the remote description associated with the connection.
:param sessionDescription: An :class:`RTCSessionDescription` created from
information received over the signaling channel.
"""
self.__log_debug(
"setRemoteDescription(%s)\n%s",
sessionDescription.type,
sessionDescription.sdp,
)
# parse and validate description
description = sdp.SessionDescription.parse(sessionDescription.sdp)
description.type = sessionDescription.type
self.__validate_description(description, is_local=False)
# apply description
iceCandidates: Dict[RTCIceTransport, sdp.MediaDescription] = {}
trackEvents = []
for i, media in enumerate(description.media):
dtlsTransport: Optional[RTCDtlsTransport] = None
self.__seenMids.add(media.rtp.muxId)
if media.kind in ["audio", "video"]:
# find transceiver
transceiver = None
for t in self.__transceivers:
if t.kind == media.kind and t.mid in [None, media.rtp.muxId]:
transceiver = t
if transceiver is None:
transceiver = self.__createTransceiver(
direction="recvonly", kind=media.kind
)
if transceiver.mid is None:
transceiver._set_mid(media.rtp.muxId)
transceiver._set_mline_index(i)
# negotiate codecs
common = filter_preferred_codecs(
find_common_codecs(CODECS[media.kind], media.rtp.codecs),
transceiver._preferred_codecs,
)
if not len(common):
raise OperationError(
"Failed to set remote {} description send parameters".format(
media.kind
)
)
transceiver._codecs = common
transceiver._headerExtensions = find_common_header_extensions(
HEADER_EXTENSIONS[media.kind], media.rtp.headerExtensions
)
# configure direction
direction = reverse_direction(media.direction)
if description.type in ["answer", "pranswer"]:
transceiver._setCurrentDirection(direction)
else:
transceiver._offerDirection = direction
# create remote stream track
if (
direction in ["recvonly", "sendrecv"]
and not transceiver.receiver.track
):
transceiver.receiver._track = RemoteStreamTrack(
kind=media.kind, id=description.webrtc_track_id(media)
)
trackEvents.append(
RTCTrackEvent(
receiver=transceiver.receiver,
track=transceiver.receiver.track,
transceiver=transceiver,
)
)
# memorise transport parameters
dtlsTransport = transceiver._transport
self.__remoteDtls[transceiver] = media.dtls
self.__remoteIce[transceiver] = media.ice
elif media.kind == "application":
if not self.__sctp:
self.__createSctpTransport()
if self.__sctp.mid is None:
self.__sctp.mid = media.rtp.muxId
self.__sctp_mline_index = i
# configure sctp
if media.profile == "DTLS/SCTP":
self._sctpLegacySdp = True
self.__sctpRemotePort = int(media.fmt[0])
else:
self._sctpLegacySdp = False
self.__sctpRemotePort = media.sctp_port
self.__sctpRemoteCaps = media.sctpCapabilities
# memorise transport parameters
dtlsTransport = self.__sctp.transport
self.__remoteDtls[self.__sctp] = media.dtls
self.__remoteIce[self.__sctp] = media.ice
if dtlsTransport is not None:
# add ICE candidates
iceTransport = dtlsTransport.transport
iceCandidates[iceTransport] = media
# set ICE role
if description.type == "offer" and not iceTransport._role_set:
iceTransport._connection.ice_controlling = media.ice.iceLite
iceTransport._role_set = True
# set DTLS role
if description.type == "offer" and media.dtls.role == "client":
dtlsTransport._set_role(role="server")
if description.type == "answer":
dtlsTransport._set_role(
role="server" if media.dtls.role == "client" else "client"
)
# remove bundled transports
bundle = next((x for x in description.group if x.semantic == "BUNDLE"), None)
if bundle and bundle.items:
# find main media stream
masterMid = bundle.items[0]
masterTransport = None
for transceiver in self.__transceivers:
if transceiver.mid == masterMid:
masterTransport = transceiver._transport
break
if self.__sctp and self.__sctp.mid == masterMid:
masterTransport = self.__sctp.transport
# replace transport for bundled media
oldTransports = set()
slaveMids = bundle.items[1:]
for transceiver in self.__transceivers:
if transceiver.mid in slaveMids and not transceiver._bundled:
oldTransports.add(transceiver._transport)
transceiver.receiver.setTransport(masterTransport)
transceiver.sender.setTransport(masterTransport)
transceiver._bundled = True
transceiver._transport = masterTransport
if (
self.__sctp
and self.__sctp.mid in slaveMids
and not self.__sctp._bundled
):
oldTransports.add(self.__sctp.transport)
self.__sctp.setTransport(masterTransport)
self.__sctp._bundled = True
# stop and discard old ICE transports
for dtlsTransport in oldTransports:
await dtlsTransport.stop()
await dtlsTransport.transport.stop()
self.__dtlsTransports.discard(dtlsTransport)
self.__iceTransports.discard(dtlsTransport.transport)
iceCandidates.pop(dtlsTransport.transport, None)
self.__updateIceGatheringState()
self.__updateIceConnectionState()
self.__updateConnectionState()
# add remote candidates
coros = [
add_remote_candidates(iceTransport, media)
for iceTransport, media in iceCandidates.items()
]
await asyncio.gather(*coros)
# FIXME: in aiortc 2.0.0 emit RTCTrackEvent directly
for event in trackEvents:
self.emit("track", event.track)
# connect
asyncio.ensure_future(self.__connect())
# update signaling state
if description.type == "offer":
self.__setSignalingState("have-remote-offer")
elif description.type == "answer":
self.__setSignalingState("stable")
# replace description
if description.type == "answer":
self.__currentRemoteDescription = description
self.__pendingRemoteDescription = None
else:
self.__pendingRemoteDescription = description | Changes the remote description associated with the connection.
:param sessionDescription: An :class:`RTCSessionDescription` created from
information received over the signaling channel. | setRemoteDescription | python | aiortc/aiortc | src/aiortc/rtcpeerconnection.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcpeerconnection.py | BSD-3-Clause |
def prune_chunks(self, tsn: int) -> int:
"""
Prune chunks up to the given TSN.
"""
pos = -1
size = 0
for i, chunk in enumerate(self.reassembly):
if uint32_gte(tsn, chunk.tsn):
pos = i
size += len(chunk.user_data)
else:
break
self.reassembly = self.reassembly[pos + 1 :]
return size | Prune chunks up to the given TSN. | prune_chunks | python | aiortc/aiortc | src/aiortc/rtcsctptransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcsctptransport.py | BSD-3-Clause |
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 | The maximum number of :class:`RTCDataChannel` that can be used simultaneously. | maxChannels | python | aiortc/aiortc | src/aiortc/rtcsctptransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcsctptransport.py | BSD-3-Clause |
def port(self) -> int:
"""
The local SCTP port number used for data channels.
"""
return self._local_port | The local SCTP port number used for data channels. | port | python | aiortc/aiortc | src/aiortc/rtcsctptransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcsctptransport.py | BSD-3-Clause |
def state(self) -> str:
"""
The current state of the SCTP transport.
"""
return self.__state | The current state of the SCTP transport. | state | python | aiortc/aiortc | src/aiortc/rtcsctptransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcsctptransport.py | BSD-3-Clause |
def transport(self):
"""
The :class:`RTCDtlsTransport` over which SCTP data is transmitted.
"""
return self.__transport | The :class:`RTCDtlsTransport` over which SCTP data is transmitted. | transport | python | aiortc/aiortc | src/aiortc/rtcsctptransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcsctptransport.py | BSD-3-Clause |
def getCapabilities(cls) -> RTCSctpCapabilities:
"""
Retrieve the capabilities of the transport.
:rtype: RTCSctpCapabilities
"""
return RTCSctpCapabilities(maxMessageSize=65536) | Retrieve the capabilities of the transport.
:rtype: RTCSctpCapabilities | getCapabilities | python | aiortc/aiortc | src/aiortc/rtcsctptransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcsctptransport.py | BSD-3-Clause |
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() | Start the transport. | start | python | aiortc/aiortc | src/aiortc/rtcsctptransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcsctptransport.py | BSD-3-Clause |
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) | Stop the transport. | stop | python | aiortc/aiortc | src/aiortc/rtcsctptransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcsctptransport.py | BSD-3-Clause |
async def _abort(self) -> None:
"""
Abort the association.
"""
chunk = AbortChunk()
try:
await self._send_chunk(chunk)
except ConnectionError:
pass | Abort the association. | _abort | python | aiortc/aiortc | src/aiortc/rtcsctptransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcsctptransport.py | BSD-3-Clause |
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) | Initialize the association. | _init | python | aiortc/aiortc | src/aiortc/rtcsctptransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcsctptransport.py | BSD-3-Clause |
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) | Gets what extensions are supported by the remote party. | _get_extensions | python | aiortc/aiortc | src/aiortc/rtcsctptransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcsctptransport.py | BSD-3-Clause |
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))) | Sets what extensions are supported by the local party. | _set_extensions | python | aiortc/aiortc | src/aiortc/rtcsctptransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcsctptransport.py | BSD-3-Clause |
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] | Get or create the inbound stream with the specified ID. | _get_inbound_stream | python | aiortc/aiortc | src/aiortc/rtcsctptransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcsctptransport.py | BSD-3-Clause |
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() | Handle data received from the network. | _handle_data | python | aiortc/aiortc | src/aiortc/rtcsctptransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcsctptransport.py | BSD-3-Clause |
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 | 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. | _maybe_abandon | python | aiortc/aiortc | src/aiortc/rtcsctptransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcsctptransport.py | BSD-3-Clause |
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 | Mark an incoming data TSN as received. | _mark_received | python | aiortc/aiortc | src/aiortc/rtcsctptransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcsctptransport.py | BSD-3-Clause |
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) | Receive data stream -> ULP. | _receive | python | aiortc/aiortc | src/aiortc/rtcsctptransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcsctptransport.py | BSD-3-Clause |
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 | Handle an incoming chunk. | _receive_chunk | python | aiortc/aiortc | src/aiortc/rtcsctptransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcsctptransport.py | BSD-3-Clause |
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) | Handle a DATA chunk. | _receive_data_chunk | python | aiortc/aiortc | src/aiortc/rtcsctptransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcsctptransport.py | BSD-3-Clause |
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
) | Handle a FORWARD TSN chunk. | _receive_forward_tsn_chunk | python | aiortc/aiortc | src/aiortc/rtcsctptransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcsctptransport.py | BSD-3-Clause |
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() | Handle a SACK chunk. | _receive_sack_chunk | python | aiortc/aiortc | src/aiortc/rtcsctptransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcsctptransport.py | BSD-3-Clause |
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() | Handle a RE-CONFIG parameter. | _receive_reconfig_param | python | aiortc/aiortc | src/aiortc/rtcsctptransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcsctptransport.py | BSD-3-Clause |
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() | Send data ULP -> stream. | _send | python | aiortc/aiortc | src/aiortc/rtcsctptransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcsctptransport.py | BSD-3-Clause |
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,
)
) | Transmit a chunk (no bundling for now). | _send_chunk | python | aiortc/aiortc | src/aiortc/rtcsctptransport.py | https://github.com/aiortc/aiortc/blob/master/src/aiortc/rtcsctptransport.py | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.