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,616
autopage
__exit__
null
def __exit__(self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException], traceback: Optional[types.TracebackType]) -> bool: if self._pager is not None: # Pager ignores Ctrl-C, so we should too with _sigint_ignore(): pager_in = self._pager.stdin assert pager_in is not None try: pager_in.close() except BrokenPipeError: # Other end of pipe already closed self._exit_code = _signal_exit_code(signal.SIGPIPE) # Wait for user to exit pager self._pager.wait() else: self._flush_output() return self._process_exception(exc)
(self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException], traceback: Optional[traceback]) -> bool
718,617
autopage
__init__
null
def __init__(self, output_stream: Optional[TextIO] = None, *, pager_command: command.CommandType = command.DefaultPager(), allow_color: bool = True, line_buffering: Optional[bool] = None, reset_on_exit: bool = False, errors: Optional[ErrorStrategy] = None): self._use_stdout = output_stream is None or output_stream is sys.stdout self._out = sys.stdout if output_stream is None else output_stream self._tty = (not self._out.closed) and self._out.isatty() self._command = command.get_pager_command(pager_command) self._config = command.PagerConfig( color=allow_color, line_buffering_requested=bool(line_buffering), reset_terminal=reset_on_exit, ) self._set_line_buffering = line_buffering self._set_errors = (ErrorStrategy(errors) if errors is not None else None) self._pager: Optional[subprocess.Popen] = None self._exit_code = 0
(self, output_stream: Optional[TextIO] = None, *, pager_command: Union[autopage.command.PagerCommand, Callable[[], autopage.command.PagerCommand], str, Sequence[str]] = <autopage.command.Less object at 0x7f2fc8e3abf0>, allow_color: bool = True, line_buffering: Optional[bool] = None, reset_on_exit: bool = False, errors: Optional[autopage.ErrorStrategy] = None)
718,618
autopage
_encoding
null
def _encoding(self) -> str: return getattr(self._out, 'encoding', 'ascii')
(self) -> str
718,619
autopage
_errors
null
def _errors(self) -> str: if self._set_errors is None: return getattr(self._out, 'errors', ErrorStrategy.STRICT.value) return self._set_errors.value
(self) -> str
718,620
autopage
_flush_output
null
def _flush_output(self) -> None: try: if not self._out.closed: self._out.flush() except BrokenPipeError: self._exit_code = _signal_exit_code(signal.SIGPIPE) try: # Other end of pipe already closed, so close the stream now # and handle the error. If we leave the stream open with # unflushed data, then it will print an unhandleable # exception during Python's interpreter shutdown. self._out.close() except BrokenPipeError: # This will always happen pass
(self) -> NoneType
718,621
autopage
_line_buffering
null
def _line_buffering(self) -> bool: if self._set_line_buffering is None: return getattr(self._out, 'line_buffering', self._tty) return self._set_line_buffering
(self) -> bool
718,622
autopage
_paged_stream
null
def _paged_stream(self) -> TextIO: buffer_size = 1 if self._line_buffering() else -1 self._pager = subprocess.Popen(self._command.command(), env=self._pager_env(), bufsize=buffer_size, universal_newlines=True, encoding=self._encoding(), errors=self._errors(), stdin=subprocess.PIPE, stdout=self._pager_out_stream()) assert self._pager.stdin is not None return typing.cast(TextIO, self._pager.stdin)
(self) -> <class 'TextIO'>
718,623
autopage
_pager_env
null
def _pager_env(self) -> Optional[Dict[str, str]]: new_vars = self._command.environment_variables(self._config) if not new_vars: return None env = dict(os.environ) env.update(new_vars) return env
(self) -> Optional[Dict[str, str]]
718,624
autopage
_pager_out_stream
null
def _pager_out_stream(self) -> Optional[TextIO]: if not self._use_stdout: try: # Ensure the output stream has a file descriptor self._out.fileno() except OSError: pass else: return self._out return None
(self) -> Optional[TextIO]
718,625
autopage
_process_exception
null
def _process_exception(self, exc: Optional[BaseException]) -> bool: if exc is not None: if isinstance(exc, BrokenPipeError): self._exit_code = _signal_exit_code(signal.SIGPIPE) # Suppress exceptions caused by a broken pipe (indicating that # the user has exited the pager, or the following process in # the pipeline has exited) return True elif isinstance(exc, KeyboardInterrupt): self._exit_code = _signal_exit_code(signal.SIGINT) elif isinstance(exc, SystemExit) and isinstance(exc.code, int): self._exit_code = exc.code else: self._exit_code = 1 return False
(self, exc: Optional[BaseException]) -> bool
718,626
autopage
_reconfigure_output_stream
null
def _reconfigure_output_stream(self) -> None: if self._set_line_buffering is None and self._set_errors is None: return if not isinstance(self._out, io.TextIOWrapper): return # Python 3.7 & later if hasattr(self._out, 'reconfigure'): self._out.reconfigure(line_buffering=self._set_line_buffering, errors=(self._set_errors.value if self._set_errors is not None else None)) # Python 3.6 elif (self._out.line_buffering != self._line_buffering() or self._out.errors != self._errors()): # Pure-python I/O if (hasattr(self._out, '_line_buffering') and hasattr(self._out, '_errors')): py_out = typing.cast(Any, self._out) py_out._line_buffering = self._line_buffering() py_out._errors = self._errors() py_out.flush() # Native C I/O else: encoding = self._encoding() errors = self._errors() line_buffering = self._line_buffering() try: if self._use_stdout: sys.stdout = typing.cast(TextIO, None) newstream = io.TextIOWrapper( self._out.detach(), line_buffering=line_buffering, encoding=encoding, errors=errors) self._out = newstream finally: if self._use_stdout: sys.stdout = self._out
(self) -> NoneType
718,627
autopage
exit_code
Return an appropriate exit code for the process based on any errors. If the user exits the program prematurely by closing the pager, we may want to return a different exit code for the process. This method returns an appropriate exit code on the basis of the existence and type of any uncaught exceptions.
def exit_code(self) -> int: """ Return an appropriate exit code for the process based on any errors. If the user exits the program prematurely by closing the pager, we may want to return a different exit code for the process. This method returns an appropriate exit code on the basis of the existence and type of any uncaught exceptions. """ return self._exit_code
(self) -> int
718,628
autopage
to_terminal
Return whether the output stream is a terminal.
def to_terminal(self) -> bool: """Return whether the output stream is a terminal.""" return self._tty
(self) -> bool
718,629
autopage
ErrorStrategy
The strategy for dealing with unicode errors when convering text to bytes.
class ErrorStrategy(enum.Enum): """ The strategy for dealing with unicode errors when convering text to bytes. """ STRICT = 'strict' IGNORE = 'ignore' REPLACE = 'replace' BACKSLASH_REPLACE = 'backslashreplace' XML_CHARREF_REPLACE = 'xmlcharrefreplace' NAME_REPLACE = 'namereplace'
(value, names=None, *, module=None, qualname=None, type=None, start=1)
718,648
autopage
_sigint_ignore
Context manager to temporarily ignore SIGINT.
def _signal_exit_code(signum: signal.Signals) -> int: """ Return the exit code corresponding to a received signal. Conventionally, when a program exits due to a signal its exit code is 128 plus the signal number. """ return 128 + int(signum)
() -> Generator[NoneType, NoneType, NoneType]
718,649
autopage
_signal_exit_code
Return the exit code corresponding to a received signal. Conventionally, when a program exits due to a signal its exit code is 128 plus the signal number.
def _signal_exit_code(signum: signal.Signals) -> int: """ Return the exit code corresponding to a received signal. Conventionally, when a program exits due to a signal its exit code is 128 plus the signal number. """ return 128 + int(signum)
(signum: signal.Signals) -> int
718,654
autopage
line_buffer_from_input
Return whether line buffering should be enabled for a given input stream. When data is being read from an input stream, processed somehow, and then written to an autopaged output stream, it may be desirable to enable line buffering on the output. This means that each line of data written to the output will be visible immediately, as opposed to waiting for the output buffer to fill up. This is, however, slower. If the input stream is a file, line buffering is unnecessary. This function determines whether an input stream might require line buffering on output. If no input stream is specified, sys.stdin is assumed. >>> with AutoPager(line_buffering=line_buffer_from_input()) as out: >>> for l in sys.stdin: >>> out.write(l)
def line_buffer_from_input(input_stream: Optional[typing.IO] = None) -> bool: """ Return whether line buffering should be enabled for a given input stream. When data is being read from an input stream, processed somehow, and then written to an autopaged output stream, it may be desirable to enable line buffering on the output. This means that each line of data written to the output will be visible immediately, as opposed to waiting for the output buffer to fill up. This is, however, slower. If the input stream is a file, line buffering is unnecessary. This function determines whether an input stream might require line buffering on output. If no input stream is specified, sys.stdin is assumed. >>> with AutoPager(line_buffering=line_buffer_from_input()) as out: >>> for l in sys.stdin: >>> out.write(l) """ if input_stream is None: input_stream = sys.stdin # On Illumos, TTYs claim to be seekable so don't believe them return not (input_stream.seekable() and not input_stream.isatty())
(input_stream: Optional[IO] = None) -> bool
718,662
aiortc.mediastreams
AudioStreamTrack
A dummy audio track which reads silence.
class AudioStreamTrack(MediaStreamTrack): """ A dummy audio track which reads silence. """ kind = "audio" _start: float _timestamp: int 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
() -> None
718,664
aiortc.mediastreams
__init__
null
def __init__(self) -> None: super().__init__() self.__ended = False self._id = str(uuid.uuid4())
(self) -> NoneType
718,678
aiortc.mediastreams
recv
Receive the next :class:`~av.audio.frame.AudioFrame`. The base implementation just reads silence, subclass :class:`AudioStreamTrack` to provide a useful implementation.
def stop(self) -> None: if not self.__ended: self.__ended = True self.emit("ended") # no more events will be emitted, so remove all event listeners # to facilitate garbage collection. self.remove_all_listeners()
(self) -> av.frame.Frame
718,681
aiortc.mediastreams
stop
null
def stop(self) -> None: if not self.__ended: self.__ended = True self.emit("ended") # no more events will be emitted, so remove all event listeners # to facilitate garbage collection. self.remove_all_listeners()
(self) -> NoneType
718,682
aiortc.exceptions
InvalidAccessError
null
class InvalidAccessError(Exception): pass
null
718,683
aiortc.exceptions
InvalidStateError
null
class InvalidStateError(Exception): pass
null
718,684
aiortc.mediastreams
MediaStreamTrack
A single media track within a stream.
class MediaStreamTrack(AsyncIOEventEmitter, metaclass=ABCMeta): """ A single media track within a stream. """ kind = "unknown" def __init__(self) -> None: super().__init__() self.__ended = False self._id = str(uuid.uuid4()) @property def id(self) -> str: """ An automatically generated globally unique ID. """ return self._id @property def readyState(self) -> str: return "ended" if self.__ended else "live" @abstractmethod 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` """ def stop(self) -> None: if not self.__ended: self.__ended = True self.emit("ended") # no more events will be emitted, so remove all event listeners # to facilitate garbage collection. self.remove_all_listeners()
() -> None
718,700
aiortc.mediastreams
recv
Receive the next :class:`~av.audio.frame.AudioFrame`, :class:`~av.video.frame.VideoFrame` or :class:`~av.packet.Packet`
@abstractmethod 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` """
(self) -> Union[av.frame.Frame, av.packet.Packet]
718,704
aiortc.rtcdtlstransport
RTCCertificate
The :class:`RTCCertificate` interface enables the certificates used by an :class:`RTCDtlsTransport`. To generate a certificate and the corresponding private key use :func:`generateCertificate`.
class RTCCertificate: """ The :class:`RTCCertificate` interface enables the certificates used by an :class:`RTCDtlsTransport`. To generate a certificate and the corresponding private key use :func:`generateCertificate`. """ def __init__(self, key: crypto.PKey, cert: crypto.X509) -> None: self._key = key self._cert = cert @property def expires(self) -> datetime.datetime: """ The date and time after which the certificate will be considered invalid. """ return self._cert.to_cryptography().not_valid_after_utc def getFingerprints(self) -> List[RTCDtlsFingerprint]: """ Returns the list of certificate fingerprints, one of which is computed with the digest algorithm used in the certificate signature. """ return [ RTCDtlsFingerprint( algorithm="sha-256", value=certificate_digest(self._cert), ) ] @classmethod def generateCertificate(cls: Type[CERTIFICATE_T]) -> CERTIFICATE_T: """ Create and return an X.509 certificate and corresponding private key. :rtype: RTCCertificate """ key = ec.generate_private_key(ec.SECP256R1(), default_backend()) cert = generate_certificate(key) return cls( key=crypto.PKey.from_cryptography_key(key), cert=crypto.X509.from_cryptography(cert), ) def _create_ssl_context( self, srtp_profiles: List[SRTPProtectionProfile] ) -> SSL.Context: ctx = SSL.Context(SSL.DTLS_METHOD) ctx.set_verify( SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, lambda *args: 1 ) ctx.use_certificate(self._cert) ctx.use_privatekey(self._key) ctx.set_cipher_list( b"ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA" ) ctx.set_tlsext_use_srtp(b":".join(x.openssl_profile for x in srtp_profiles)) return ctx
(key: OpenSSL.crypto.PKey, cert: OpenSSL.crypto.X509) -> None
718,705
aiortc.rtcdtlstransport
__init__
null
def __init__(self, key: crypto.PKey, cert: crypto.X509) -> None: self._key = key self._cert = cert
(self, key: OpenSSL.crypto.PKey, cert: OpenSSL.crypto.X509) -> NoneType
718,706
aiortc.rtcdtlstransport
_create_ssl_context
null
def _create_ssl_context( self, srtp_profiles: List[SRTPProtectionProfile] ) -> SSL.Context: ctx = SSL.Context(SSL.DTLS_METHOD) ctx.set_verify( SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, lambda *args: 1 ) ctx.use_certificate(self._cert) ctx.use_privatekey(self._key) ctx.set_cipher_list( b"ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA" ) ctx.set_tlsext_use_srtp(b":".join(x.openssl_profile for x in srtp_profiles)) return ctx
(self, srtp_profiles: List[aiortc.rtcdtlstransport.SRTPProtectionProfile]) -> OpenSSL.SSL.Context
718,707
aiortc.rtcdtlstransport
getFingerprints
Returns the list of certificate fingerprints, one of which is computed with the digest algorithm used in the certificate signature.
def getFingerprints(self) -> List[RTCDtlsFingerprint]: """ Returns the list of certificate fingerprints, one of which is computed with the digest algorithm used in the certificate signature. """ return [ RTCDtlsFingerprint( algorithm="sha-256", value=certificate_digest(self._cert), ) ]
(self) -> List[aiortc.rtcdtlstransport.RTCDtlsFingerprint]
718,708
aiortc.rtcconfiguration
RTCConfiguration
The :class:`RTCConfiguration` dictionary is used to provide configuration options for an :class:`RTCPeerConnection`.
class RTCConfiguration: """ The :class:`RTCConfiguration` dictionary is used to provide configuration options for an :class:`RTCPeerConnection`. """ iceServers: Optional[List[RTCIceServer]] = None "A list of :class:`RTCIceServer` objects to configure STUN / TURN servers."
(iceServers: Optional[List[aiortc.rtcconfiguration.RTCIceServer]] = None) -> None
718,709
aiortc.rtcconfiguration
__eq__
null
from dataclasses import dataclass from typing import List, Optional @dataclass class RTCIceServer: """ The :class:`RTCIceServer` dictionary defines how to connect to a single STUN or TURN server. It includes both the URL and the necessary credentials, if any, to connect to the server. """ urls: str """ This required property is either a single string or a list of strings, each specifying a URL which can be used to connect to the server. """ username: Optional[str] = None "The username to use during authentication (for TURN only)." credential: Optional[str] = None "The credential to use during authentication (for TURN only)." credentialType: str = "password"
(self, other)
718,712
aiortc.rtcdatachannel
RTCDataChannel
The :class:`RTCDataChannel` interface represents a network channel which can be used for bidirectional peer-to-peer transfers of arbitrary data. :param transport: An :class:`RTCSctpTransport`. :param parameters: An :class:`RTCDataChannelParameters`.
class RTCDataChannel(AsyncIOEventEmitter): """ The :class:`RTCDataChannel` interface represents a network channel which can be used for bidirectional peer-to-peer transfers of arbitrary data. :param transport: An :class:`RTCSctpTransport`. :param parameters: An :class:`RTCDataChannelParameters`. """ def __init__( self, transport, parameters: RTCDataChannelParameters, send_open: bool = True ) -> None: super().__init__() self.__bufferedAmount = 0 self.__bufferedAmountLowThreshold = 0 self.__id = parameters.id self.__parameters = parameters self.__readyState = "connecting" self.__transport = transport self.__send_open = send_open if self.__parameters.negotiated and ( self.__id is None or self.__id < 0 or self.__id > 65534 ): raise ValueError( "ID must be in range 0-65534 " "if data channel is negotiated out-of-band" ) if not self.__parameters.negotiated: if self.__send_open: self.__send_open = False self.__transport._data_channel_open(self) else: self.__transport._data_channel_add_negotiated(self) @property def bufferedAmount(self) -> int: """ The number of bytes of data currently queued to be sent over the data channel. """ return self.__bufferedAmount @property def bufferedAmountLowThreshold(self) -> int: """ The number of bytes of buffered outgoing data that is considered "low". """ return self.__bufferedAmountLowThreshold @bufferedAmountLowThreshold.setter def bufferedAmountLowThreshold(self, value: int) -> None: if value < 0 or value > 4294967295: raise ValueError( "bufferedAmountLowThreshold must be in range 0 - 4294967295" ) self.__bufferedAmountLowThreshold = value @property def negotiated(self) -> bool: """ Whether data channel was negotiated out-of-band. """ return self.__parameters.negotiated @property def id(self) -> Optional[int]: """ An ID number which uniquely identifies the data channel. """ return self.__id @property def label(self) -> str: """ A name describing the data channel. These labels are not required to be unique. """ return self.__parameters.label @property def ordered(self) -> bool: """ Indicates whether or not the data channel guarantees in-order delivery of messages. """ return self.__parameters.ordered @property def maxPacketLifeTime(self) -> Optional[int]: """ The maximum time in milliseconds during which transmissions are attempted. """ return self.__parameters.maxPacketLifeTime @property def maxRetransmits(self) -> Optional[int]: """ "The maximum number of retransmissions that are attempted. """ return self.__parameters.maxRetransmits @property def protocol(self) -> str: """ The name of the subprotocol in use. """ return self.__parameters.protocol @property def readyState(self) -> str: """ A string indicating the current state of the underlying data transport. """ return self.__readyState @property def transport(self): """ The :class:`RTCSctpTransport` over which data is transmitted. """ return self.__transport def close(self) -> None: """ Close the data channel. """ self.transport._data_channel_close(self) def send(self, data: Union[bytes, str]) -> None: """ Send `data` across the data channel to the remote peer. """ if self.readyState != "open": raise InvalidStateError if not isinstance(data, (str, bytes)): raise ValueError(f"Cannot send unsupported data type: {type(data)}") self.transport._data_channel_send(self, data) def _addBufferedAmount(self, amount: int) -> None: crosses_threshold = ( self.__bufferedAmount > self.bufferedAmountLowThreshold and self.__bufferedAmount + amount <= self.bufferedAmountLowThreshold ) self.__bufferedAmount += amount if crosses_threshold: self.emit("bufferedamountlow") def _setId(self, id: int) -> None: self.__id = id def _setReadyState(self, state: str) -> None: if state != self.__readyState: self.__log_debug("- %s -> %s", self.__readyState, state) self.__readyState = state if state == "open": self.emit("open") elif state == "closed": self.emit("close") # no more events will be emitted, so remove all event listeners # to facilitate garbage collection. self.remove_all_listeners() def __log_debug(self, msg: str, *args) -> None: logger.debug(f"RTCDataChannel(%s) {msg}", self.__id, *args)
(transport, parameters: aiortc.rtcdatachannel.RTCDataChannelParameters, send_open: bool = True) -> None
718,713
aiortc.rtcdatachannel
__log_debug
null
def __log_debug(self, msg: str, *args) -> None: logger.debug(f"RTCDataChannel(%s) {msg}", self.__id, *args)
(self, msg: str, *args) -> NoneType
718,715
aiortc.rtcdatachannel
__init__
null
def __init__( self, transport, parameters: RTCDataChannelParameters, send_open: bool = True ) -> None: super().__init__() self.__bufferedAmount = 0 self.__bufferedAmountLowThreshold = 0 self.__id = parameters.id self.__parameters = parameters self.__readyState = "connecting" self.__transport = transport self.__send_open = send_open if self.__parameters.negotiated and ( self.__id is None or self.__id < 0 or self.__id > 65534 ): raise ValueError( "ID must be in range 0-65534 " "if data channel is negotiated out-of-band" ) if not self.__parameters.negotiated: if self.__send_open: self.__send_open = False self.__transport._data_channel_open(self) else: self.__transport._data_channel_add_negotiated(self)
(self, transport, parameters: aiortc.rtcdatachannel.RTCDataChannelParameters, send_open: bool = True) -> NoneType
718,717
aiortc.rtcdatachannel
_addBufferedAmount
null
def _addBufferedAmount(self, amount: int) -> None: crosses_threshold = ( self.__bufferedAmount > self.bufferedAmountLowThreshold and self.__bufferedAmount + amount <= self.bufferedAmountLowThreshold ) self.__bufferedAmount += amount if crosses_threshold: self.emit("bufferedamountlow")
(self, amount: int) -> NoneType
718,723
aiortc.rtcdatachannel
_setId
null
def _setId(self, id: int) -> None: self.__id = id
(self, id: int) -> NoneType
718,724
aiortc.rtcdatachannel
_setReadyState
null
def _setReadyState(self, state: str) -> None: if state != self.__readyState: self.__log_debug("- %s -> %s", self.__readyState, state) self.__readyState = state if state == "open": self.emit("open") elif state == "closed": self.emit("close") # no more events will be emitted, so remove all event listeners # to facilitate garbage collection. self.remove_all_listeners()
(self, state: str) -> NoneType
718,726
aiortc.rtcdatachannel
close
Close the data channel.
def close(self) -> None: """ Close the data channel. """ self.transport._data_channel_close(self)
(self) -> NoneType
718,735
aiortc.rtcdatachannel
send
Send `data` across the data channel to the remote peer.
def send(self, data: Union[bytes, str]) -> None: """ Send `data` across the data channel to the remote peer. """ if self.readyState != "open": raise InvalidStateError if not isinstance(data, (str, bytes)): raise ValueError(f"Cannot send unsupported data type: {type(data)}") self.transport._data_channel_send(self, data)
(self, data: Union[bytes, str]) -> NoneType
718,736
aiortc.rtcdatachannel
RTCDataChannelParameters
The :class:`RTCDataChannelParameters` dictionary describes the configuration of an :class:`RTCDataChannel`.
class RTCDataChannelParameters: """ The :class:`RTCDataChannelParameters` dictionary describes the configuration of an :class:`RTCDataChannel`. """ label: str = "" "A name describing the data channel." maxPacketLifeTime: Optional[int] = None "The maximum time in milliseconds during which transmissions are attempted." maxRetransmits: Optional[int] = None "The maximum number of retransmissions that are attempted." ordered: bool = True "Whether the data channel guarantees in-order delivery of messages." protocol: str = "" "The name of the subprotocol in use." negotiated: bool = False """ Whether data channel will be negotiated out of-band, where both sides create data channel with an agreed-upon ID.""" id: Optional[int] = None """ An numeric ID for the channel; permitted values are 0-65534. If you don't include this option, the user agent will select an ID for you. Must be set when negotiating out-of-band. """
(label: str = '', maxPacketLifeTime: Optional[int] = None, maxRetransmits: Optional[int] = None, ordered: bool = True, protocol: str = '', negotiated: bool = False, id: Optional[int] = None) -> None
718,737
aiortc.rtcdatachannel
__eq__
null
import logging from dataclasses import dataclass from typing import Optional, Union from pyee.asyncio import AsyncIOEventEmitter from .exceptions import InvalidStateError logger = logging.getLogger(__name__) @dataclass class RTCDataChannelParameters: """ The :class:`RTCDataChannelParameters` dictionary describes the configuration of an :class:`RTCDataChannel`. """ label: str = "" "A name describing the data channel." maxPacketLifeTime: Optional[int] = None "The maximum time in milliseconds during which transmissions are attempted." maxRetransmits: Optional[int] = None "The maximum number of retransmissions that are attempted." ordered: bool = True "Whether the data channel guarantees in-order delivery of messages." protocol: str = "" "The name of the subprotocol in use." negotiated: bool = False """ Whether data channel will be negotiated out of-band, where both sides create data channel with an agreed-upon ID.""" id: Optional[int] = None """ An numeric ID for the channel; permitted values are 0-65534. If you don't include this option, the user agent will select an ID for you. Must be set when negotiating out-of-band. """
(self, other)
718,740
aiortc.rtcdtlstransport
RTCDtlsFingerprint
The :class:`RTCDtlsFingerprint` dictionary includes the hash function algorithm and certificate fingerprint.
class RTCDtlsFingerprint: """ The :class:`RTCDtlsFingerprint` dictionary includes the hash function algorithm and certificate fingerprint. """ algorithm: str "The hash function name, for instance `'sha-256'`." value: str "The fingerprint value."
(algorithm: str, value: str) -> None
718,741
aiortc.rtcdtlstransport
__eq__
null
import asyncio import binascii import datetime import enum import logging import os import traceback from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Set, Type, TypeVar import pylibsrtp from cryptography import x509 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import ec from OpenSSL import SSL, crypto from pyee.asyncio import AsyncIOEventEmitter from pylibsrtp import Policy, Session from . import clock, rtp from .rtcicetransport import RTCIceTransport from .rtcrtpparameters import RTCRtpReceiveParameters, RTCRtpSendParameters from .rtp import ( AnyRtcpPacket, RtcpByePacket, RtcpPacket, RtcpPsfbPacket, RtcpRrPacket, RtcpRtpfbPacket, RtcpSrPacket, RtpPacket, is_rtcp, ) from .stats import RTCStatsReport, RTCTransportStats CERTIFICATE_T = TypeVar("CERTIFICATE_T", bound="RTCCertificate") logger = logging.getLogger(__name__) @dataclass(frozen=True) class SRTPProtectionProfile: libsrtp_profile: int openssl_profile: bytes key_length: int salt_length: int def get_key_and_salt(self, src, idx: int) -> bytes: key_start = idx * self.key_length salt_start = 2 * self.key_length + idx * self.salt_length return ( src[key_start : key_start + self.key_length] + src[salt_start : salt_start + self.salt_length] )
(self, other)
718,743
aiortc.rtcdtlstransport
__repr__
null
def register_receiver( self, receiver, ssrcs: List[int], payload_types: List[int], mid: Optional[str] = None, ): self.receivers.add(receiver) if mid is not None: self.mid_table[mid] = receiver for ssrc in ssrcs: self.ssrc_table[ssrc] = receiver for payload_type in payload_types: if payload_type not in self.payload_type_table: self.payload_type_table[payload_type] = set() self.payload_type_table[payload_type].add(receiver)
(self)
718,744
aiortc.rtcdtlstransport
RTCDtlsParameters
The :class:`RTCDtlsParameters` dictionary includes information relating to DTLS configuration.
class RTCDtlsParameters: """ The :class:`RTCDtlsParameters` dictionary includes information relating to DTLS configuration. """ fingerprints: List[RTCDtlsFingerprint] = field(default_factory=list) "List of :class:`RTCDtlsFingerprint`, one fingerprint for each certificate." role: str = "auto" "The DTLS role, with a default of auto."
(fingerprints: List[aiortc.rtcdtlstransport.RTCDtlsFingerprint] = <factory>, role: str = 'auto') -> None
718,748
aiortc.rtcdtlstransport
RTCDtlsTransport
The :class:`RTCDtlsTransport` object includes information relating to Datagram Transport Layer Security (DTLS) transport. :param transport: An :class:`RTCIceTransport`. :param certificates: A list of :class:`RTCCertificate` (only one is allowed currently).
class RTCDtlsTransport(AsyncIOEventEmitter): """ The :class:`RTCDtlsTransport` object includes information relating to Datagram Transport Layer Security (DTLS) transport. :param transport: An :class:`RTCIceTransport`. :param certificates: A list of :class:`RTCCertificate` (only one is allowed currently). """ def __init__( self, transport: RTCIceTransport, certificates: List[RTCCertificate] ) -> None: assert len(certificates) == 1 certificate = certificates[0] super().__init__() self.encrypted = False self._data_receiver = None self._role = "auto" self._rtp_header_extensions_map = rtp.HeaderExtensionsMap() self._rtp_router = RtpRouter() self._state = State.NEW self._stats_id = "transport_" + str(id(self)) self._task: Optional[asyncio.Future[None]] = None self._transport = transport # counters self.__rx_bytes = 0 self.__rx_packets = 0 self.__tx_bytes = 0 self.__tx_packets = 0 # SRTP self._rx_srtp: Session = None self._tx_srtp: Session = None # SSL self._srtp_profiles = SRTP_PROFILES self._ssl: Optional[SSL.Connection] = None self.__local_certificate = certificate @property def state(self) -> str: """ The current state of the DTLS transport. One of `'new'`, `'connecting'`, `'connected'`, `'closed'` or `'failed'`. """ return str(self._state)[6:].lower() @property def transport(self): """ The associated :class:`RTCIceTransport` instance. """ return self._transport def getLocalParameters(self) -> RTCDtlsParameters: """ Get the local parameters of the DTLS transport. :rtype: :class:`RTCDtlsParameters` """ return RTCDtlsParameters( fingerprints=self.__local_certificate.getFingerprints() ) async def start(self, remoteParameters: RTCDtlsParameters) -> None: """ Start DTLS transport negotiation with the parameters of the remote DTLS transport. :param remoteParameters: An :class:`RTCDtlsParameters`. """ assert self._state == State.NEW assert len(remoteParameters.fingerprints) # For WebRTC, the DTLS role is explicitly determined as part of the # offer / answer exchange. # # For ORTC however, we determine the DTLS role based on the ICE role. if self._role == "auto": if self.transport.role == "controlling": self._set_role("server") else: self._set_role("client") # Initialise SSL. self._ssl = SSL.Connection( self.__local_certificate._create_ssl_context( srtp_profiles=self._srtp_profiles ) ) if self._role == "server": self._ssl.set_accept_state() else: self._ssl.set_connect_state() self._set_state(State.CONNECTING) try: while not self.encrypted: try: self._ssl.do_handshake() except SSL.WantReadError: await self._write_ssl() await self._recv_next() except SSL.Error as exc: self.__log_debug("x DTLS handshake failed (error %s)", exc) self._set_state(State.FAILED) return else: self.encrypted = True except ConnectionError: self.__log_debug("x DTLS handshake failed (connection error)") self._set_state(State.FAILED) return # check remote fingerprint x509 = self._ssl.get_peer_certificate() remote_fingerprint = certificate_digest(x509) fingerprint_is_valid = False for f in remoteParameters.fingerprints: if ( f.algorithm.lower() == "sha-256" and f.value.lower() == remote_fingerprint.lower() ): fingerprint_is_valid = True break if not fingerprint_is_valid: self.__log_debug("x DTLS handshake failed (fingerprint mismatch)") self._set_state(State.FAILED) return # generate keying material openssl_profile = self._ssl.get_selected_srtp_profile() for srtp_profile in self._srtp_profiles: if srtp_profile.openssl_profile == openssl_profile: self.__log_debug( "x DTLS handshake negotiated %s", srtp_profile.openssl_profile.decode(), ) break else: self.__log_debug("x DTLS handshake failed (no SRTP profile negotiated)") self._set_state(State.FAILED) return view = self._ssl.export_keying_material( b"EXTRACTOR-dtls_srtp", 2 * (srtp_profile.key_length + srtp_profile.salt_length), ) if self._role == "server": srtp_tx_key = srtp_profile.get_key_and_salt(view, 1) srtp_rx_key = srtp_profile.get_key_and_salt(view, 0) else: srtp_tx_key = srtp_profile.get_key_and_salt(view, 0) srtp_rx_key = srtp_profile.get_key_and_salt(view, 1) rx_policy = Policy( key=srtp_rx_key, ssrc_type=Policy.SSRC_ANY_INBOUND, srtp_profile=srtp_profile.libsrtp_profile, ) rx_policy.allow_repeat_tx = True rx_policy.window_size = 1024 self._rx_srtp = Session(rx_policy) tx_policy = Policy( key=srtp_tx_key, ssrc_type=Policy.SSRC_ANY_OUTBOUND, srtp_profile=srtp_profile.libsrtp_profile, ) tx_policy.allow_repeat_tx = True tx_policy.window_size = 1024 self._tx_srtp = Session(tx_policy) # start data pump self.__log_debug("- DTLS handshake complete") self._set_state(State.CONNECTED) self._task = asyncio.ensure_future(self.__run()) async def stop(self) -> None: """ Stop and close the DTLS transport. """ if self._task is not None: self._task.cancel() self._task = None if self._ssl and self._state in [State.CONNECTING, State.CONNECTED]: try: self._ssl.shutdown() except SSL.Error: pass try: await self._write_ssl() except ConnectionError: pass self.__log_debug("- DTLS shutdown complete") async def __run(self) -> None: try: while True: await self._recv_next() except ConnectionError: for receiver in self._rtp_router.receivers: receiver._handle_disconnect() except Exception as exc: if not isinstance(exc, asyncio.CancelledError): self.__log_warning(traceback.format_exc()) raise exc finally: self._set_state(State.CLOSED) def _get_stats(self) -> RTCStatsReport: report = RTCStatsReport() report.add( RTCTransportStats( # RTCStats timestamp=clock.current_datetime(), type="transport", id=self._stats_id, # RTCTransportStats, packetsSent=self.__tx_packets, packetsReceived=self.__rx_packets, bytesSent=self.__tx_bytes, bytesReceived=self.__rx_bytes, iceRole=self.transport.role, dtlsState=self.state, ) ) return report async def _handle_rtcp_data(self, data: bytes) -> None: try: packets = RtcpPacket.parse(data) except ValueError as exc: self.__log_debug("x RTCP parsing failed: %s", exc) return for packet in packets: # route RTCP packet for recipient in self._rtp_router.route_rtcp(packet): await recipient._handle_rtcp_packet(packet) async def _handle_rtp_data(self, data: bytes, arrival_time_ms: int) -> None: try: packet = RtpPacket.parse(data, self._rtp_header_extensions_map) except ValueError as exc: self.__log_debug("x RTP parsing failed: %s", exc) return # route RTP packet receiver = self._rtp_router.route_rtp(packet) if receiver is not None: await receiver._handle_rtp_packet(packet, arrival_time_ms=arrival_time_ms) async def _recv_next(self) -> None: # get timeout timeout = None if not self.encrypted: timeout = self._ssl.DTLSv1_get_timeout() # receive next datagram if timeout is not None: try: data = await asyncio.wait_for(self.transport._recv(), timeout=timeout) except asyncio.TimeoutError: self.__log_debug("x DTLS handling timeout") self._ssl.DTLSv1_handle_timeout() await self._write_ssl() return else: data = await self.transport._recv() self.__rx_bytes += len(data) self.__rx_packets += 1 first_byte = data[0] if first_byte > 19 and first_byte < 64: # DTLS self._ssl.bio_write(data) try: data = self._ssl.recv(1500) except SSL.ZeroReturnError: data = None except SSL.Error: data = b"" await self._write_ssl() if data is None: self.__log_debug("- DTLS shutdown by remote party") raise ConnectionError elif data and self._data_receiver: await self._data_receiver._handle_data(data) elif first_byte > 127 and first_byte < 192 and self._rx_srtp: # SRTP / SRTCP arrival_time_ms = clock.current_ms() try: if is_rtcp(data): data = self._rx_srtp.unprotect_rtcp(data) await self._handle_rtcp_data(data) else: data = self._rx_srtp.unprotect(data) await self._handle_rtp_data(data, arrival_time_ms=arrival_time_ms) except pylibsrtp.Error as exc: self.__log_debug("x SRTP unprotect failed: %s", exc) def _register_data_receiver(self, receiver) -> None: assert self._data_receiver is None self._data_receiver = receiver def _register_rtp_receiver( self, receiver, parameters: RTCRtpReceiveParameters ) -> None: ssrcs = set() for encoding in parameters.encodings: ssrcs.add(encoding.ssrc) self._rtp_header_extensions_map.configure(parameters) self._rtp_router.register_receiver( receiver, ssrcs=list(ssrcs), payload_types=[codec.payloadType for codec in parameters.codecs], mid=parameters.muxId, ) def _register_rtp_sender(self, sender, parameters: RTCRtpSendParameters) -> None: self._rtp_header_extensions_map.configure(parameters) self._rtp_router.register_sender(sender, ssrc=sender._ssrc) async def _send_data(self, data: bytes) -> None: if self._state != State.CONNECTED: raise ConnectionError("Cannot send encrypted data, not connected") self._ssl.send(data) await self._write_ssl() async def _send_rtp(self, data: bytes) -> None: if self._state != State.CONNECTED: raise ConnectionError("Cannot send encrypted RTP, not connected") if is_rtcp(data): data = self._tx_srtp.protect_rtcp(data) else: data = self._tx_srtp.protect(data) await self.transport._send(data) self.__tx_bytes += len(data) self.__tx_packets += 1 def _set_role(self, role: str) -> None: self._role = role def _set_state(self, state: State) -> None: if state != self._state: self.__log_debug("- %s -> %s", self._state, state) self._state = state self.emit("statechange") def _unregister_data_receiver(self, receiver) -> None: if self._data_receiver == receiver: self._data_receiver = None def _unregister_rtp_receiver(self, receiver) -> None: self._rtp_router.unregister_receiver(receiver) def _unregister_rtp_sender(self, sender) -> None: self._rtp_router.unregister_sender(sender) async def _write_ssl(self) -> None: """ Flush outgoing data which OpenSSL put in our BIO to the transport. """ try: data = self._ssl.bio_read(1500) except SSL.Error: data = b"" if data: await self.transport._send(data) self.__tx_bytes += len(data) self.__tx_packets += 1 def __log_debug(self, msg: str, *args) -> None: logger.debug(f"RTCDtlsTransport(%s) {msg}", self._role, *args) def __log_warning(self, msg: str, *args) -> None: logger.warning(f"RTCDtlsTransport(%s) {msg}", self._role, *args)
(transport: aiortc.rtcicetransport.RTCIceTransport, certificates: List[aiortc.rtcdtlstransport.RTCCertificate]) -> None
718,749
aiortc.rtcdtlstransport
__log_debug
null
def __log_debug(self, msg: str, *args) -> None: logger.debug(f"RTCDtlsTransport(%s) {msg}", self._role, *args)
(self, msg: str, *args) -> NoneType
718,750
aiortc.rtcdtlstransport
__log_warning
null
def __log_warning(self, msg: str, *args) -> None: logger.warning(f"RTCDtlsTransport(%s) {msg}", self._role, *args)
(self, msg: str, *args) -> NoneType
718,751
aiortc.rtcdtlstransport
__run
null
def getLocalParameters(self) -> RTCDtlsParameters: """ Get the local parameters of the DTLS transport. :rtype: :class:`RTCDtlsParameters` """ return RTCDtlsParameters( fingerprints=self.__local_certificate.getFingerprints() )
(self) -> NoneType
718,753
aiortc.rtcdtlstransport
__init__
null
def __init__( self, transport: RTCIceTransport, certificates: List[RTCCertificate] ) -> None: assert len(certificates) == 1 certificate = certificates[0] super().__init__() self.encrypted = False self._data_receiver = None self._role = "auto" self._rtp_header_extensions_map = rtp.HeaderExtensionsMap() self._rtp_router = RtpRouter() self._state = State.NEW self._stats_id = "transport_" + str(id(self)) self._task: Optional[asyncio.Future[None]] = None self._transport = transport # counters self.__rx_bytes = 0 self.__rx_packets = 0 self.__tx_bytes = 0 self.__tx_packets = 0 # SRTP self._rx_srtp: Session = None self._tx_srtp: Session = None # SSL self._srtp_profiles = SRTP_PROFILES self._ssl: Optional[SSL.Connection] = None self.__local_certificate = certificate
(self, transport: aiortc.rtcicetransport.RTCIceTransport, certificates: List[aiortc.rtcdtlstransport.RTCCertificate]) -> NoneType
718,759
aiortc.rtcdtlstransport
_get_stats
null
def _get_stats(self) -> RTCStatsReport: report = RTCStatsReport() report.add( RTCTransportStats( # RTCStats timestamp=clock.current_datetime(), type="transport", id=self._stats_id, # RTCTransportStats, packetsSent=self.__tx_packets, packetsReceived=self.__rx_packets, bytesSent=self.__tx_bytes, bytesReceived=self.__rx_bytes, iceRole=self.transport.role, dtlsState=self.state, ) ) return report
(self) -> aiortc.stats.RTCStatsReport
718,763
aiortc.rtcdtlstransport
_register_data_receiver
null
def _register_data_receiver(self, receiver) -> None: assert self._data_receiver is None self._data_receiver = receiver
(self, receiver) -> NoneType
718,764
aiortc.rtcdtlstransport
_register_rtp_receiver
null
def _register_rtp_receiver( self, receiver, parameters: RTCRtpReceiveParameters ) -> None: ssrcs = set() for encoding in parameters.encodings: ssrcs.add(encoding.ssrc) self._rtp_header_extensions_map.configure(parameters) self._rtp_router.register_receiver( receiver, ssrcs=list(ssrcs), payload_types=[codec.payloadType for codec in parameters.codecs], mid=parameters.muxId, )
(self, receiver, parameters: aiortc.rtcrtpparameters.RTCRtpReceiveParameters) -> NoneType
718,765
aiortc.rtcdtlstransport
_register_rtp_sender
null
def _register_rtp_sender(self, sender, parameters: RTCRtpSendParameters) -> None: self._rtp_header_extensions_map.configure(parameters) self._rtp_router.register_sender(sender, ssrc=sender._ssrc)
(self, sender, parameters: aiortc.rtcrtpparameters.RTCRtpSendParameters) -> NoneType
718,769
aiortc.rtcdtlstransport
_set_role
null
def _set_role(self, role: str) -> None: self._role = role
(self, role: str) -> NoneType
718,770
aiortc.rtcdtlstransport
_set_state
null
def _set_state(self, state: State) -> None: if state != self._state: self.__log_debug("- %s -> %s", self._state, state) self._state = state self.emit("statechange")
(self, state: aiortc.rtcdtlstransport.State) -> NoneType
718,771
aiortc.rtcdtlstransport
_unregister_data_receiver
null
def _unregister_data_receiver(self, receiver) -> None: if self._data_receiver == receiver: self._data_receiver = None
(self, receiver) -> NoneType
718,772
aiortc.rtcdtlstransport
_unregister_rtp_receiver
null
def _unregister_rtp_receiver(self, receiver) -> None: self._rtp_router.unregister_receiver(receiver)
(self, receiver) -> NoneType
718,773
aiortc.rtcdtlstransport
_unregister_rtp_sender
null
def _unregister_rtp_sender(self, sender) -> None: self._rtp_router.unregister_sender(sender)
(self, sender) -> NoneType
718,774
aiortc.rtcdtlstransport
_write_ssl
Flush outgoing data which OpenSSL put in our BIO to the transport.
def _unregister_rtp_sender(self, sender) -> None: self._rtp_router.unregister_sender(sender)
(self) -> NoneType
718,778
aiortc.rtcdtlstransport
getLocalParameters
Get the local parameters of the DTLS transport. :rtype: :class:`RTCDtlsParameters`
def getLocalParameters(self) -> RTCDtlsParameters: """ Get the local parameters of the DTLS transport. :rtype: :class:`RTCDtlsParameters` """ return RTCDtlsParameters( fingerprints=self.__local_certificate.getFingerprints() )
(self) -> aiortc.rtcdtlstransport.RTCDtlsParameters
718,785
aiortc.rtcdtlstransport
start
Start DTLS transport negotiation with the parameters of the remote DTLS transport. :param remoteParameters: An :class:`RTCDtlsParameters`.
def getLocalParameters(self) -> RTCDtlsParameters: """ Get the local parameters of the DTLS transport. :rtype: :class:`RTCDtlsParameters` """ return RTCDtlsParameters( fingerprints=self.__local_certificate.getFingerprints() )
(self, remoteParameters: aiortc.rtcdtlstransport.RTCDtlsParameters) -> NoneType
718,786
aiortc.rtcdtlstransport
stop
Stop and close the DTLS transport.
def getLocalParameters(self) -> RTCDtlsParameters: """ Get the local parameters of the DTLS transport. :rtype: :class:`RTCDtlsParameters` """ return RTCDtlsParameters( fingerprints=self.__local_certificate.getFingerprints() )
(self) -> NoneType
718,787
aiortc.rtcicetransport
RTCIceCandidate
The :class:`RTCIceCandidate` interface represents a candidate Interactive Connectivity Establishment (ICE) configuration which may be used to establish an RTCPeerConnection.
class RTCIceCandidate: """ The :class:`RTCIceCandidate` interface represents a candidate Interactive Connectivity Establishment (ICE) configuration which may be used to establish an RTCPeerConnection. """ component: int foundation: str ip: str port: int priority: int protocol: str type: str relatedAddress: Optional[str] = None relatedPort: Optional[int] = None sdpMid: Optional[str] = None sdpMLineIndex: Optional[int] = None tcpType: Optional[str] = None
(component: int, foundation: str, ip: str, port: int, priority: int, protocol: str, type: str, relatedAddress: Optional[str] = None, relatedPort: Optional[int] = None, sdpMid: Optional[str] = None, sdpMLineIndex: Optional[int] = None, tcpType: Optional[str] = None) -> None
718,788
aiortc.rtcicetransport
__eq__
null
import asyncio import logging import re from dataclasses import dataclass from typing import Any, Dict, List, Optional from aioice import Candidate, Connection, ConnectionClosed from pyee.asyncio import AsyncIOEventEmitter from .exceptions import InvalidStateError from .rtcconfiguration import RTCIceServer STUN_REGEX = re.compile( r"(?P<scheme>stun|stuns)\:(?P<host>[^?:]+)(\:(?P<port>[0-9]+?))?" # RFC 7064 does not define a "transport" option but some providers # include it, so just ignore it r"(\?transport=.*)?" ) TURN_REGEX = re.compile( r"(?P<scheme>turn|turns)\:(?P<host>[^?:]+)(\:(?P<port>[0-9]+?))?" r"(\?transport=(?P<transport>.*))?" ) logger = logging.getLogger(__name__) @dataclass class RTCIceCandidate: """ The :class:`RTCIceCandidate` interface represents a candidate Interactive Connectivity Establishment (ICE) configuration which may be used to establish an RTCPeerConnection. """ component: int foundation: str ip: str port: int priority: int protocol: str type: str relatedAddress: Optional[str] = None relatedPort: Optional[int] = None sdpMid: Optional[str] = None sdpMLineIndex: Optional[int] = None tcpType: Optional[str] = None
(self, other)
718,790
aiortc.rtcicetransport
__repr__
null
def __setState(self, state: str) -> None: self.__state = state self.emit("statechange")
(self)
718,791
aiortc.rtcicetransport
RTCIceGatherer
The :class:`RTCIceGatherer` interface gathers local host, server reflexive and relay candidates, as well as enabling the retrieval of local Interactive Connectivity Establishment (ICE) parameters which can be exchanged in signaling.
class RTCIceGatherer(AsyncIOEventEmitter): """ The :class:`RTCIceGatherer` interface gathers local host, server reflexive and relay candidates, as well as enabling the retrieval of local Interactive Connectivity Establishment (ICE) parameters which can be exchanged in signaling. """ def __init__(self, iceServers: Optional[List[RTCIceServer]] = None) -> None: super().__init__() if iceServers is None: iceServers = self.getDefaultIceServers() ice_kwargs = connection_kwargs(iceServers) self._connection = Connection(ice_controlling=False, **ice_kwargs) self._remote_candidates_end = False self.__state = "new" @property def state(self) -> str: """ The current state of the ICE gatherer. """ return self.__state async def gather(self) -> None: """ Gather ICE candidates. """ if self.__state == "new": self.__setState("gathering") await self._connection.gather_candidates() self.__setState("completed") @classmethod def getDefaultIceServers(cls) -> List[RTCIceServer]: """ Return the list of default :class:`RTCIceServer`. """ return [RTCIceServer("stun:stun.l.google.com:19302")] 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] 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, ) def __setState(self, state: str) -> None: self.__state = state self.emit("statechange")
(iceServers: Optional[List[aiortc.rtcconfiguration.RTCIceServer]] = None) -> None
718,794
aiortc.rtcicetransport
__init__
null
def __init__(self, iceServers: Optional[List[RTCIceServer]] = None) -> None: super().__init__() if iceServers is None: iceServers = self.getDefaultIceServers() ice_kwargs = connection_kwargs(iceServers) self._connection = Connection(ice_controlling=False, **ice_kwargs) self._remote_candidates_end = False self.__state = "new"
(self, iceServers: Optional[List[aiortc.rtcconfiguration.RTCIceServer]] = None) -> NoneType
718,804
aiortc.rtcicetransport
gather
Gather ICE candidates.
@property def state(self) -> str: """ The current state of the ICE gatherer. """ return self.__state
(self) -> NoneType
718,805
aiortc.rtcicetransport
getLocalCandidates
Retrieve the list of valid local candidates associated with the ICE gatherer.
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]
(self) -> List[aiortc.rtcicetransport.RTCIceCandidate]
718,806
aiortc.rtcicetransport
getLocalParameters
Retrieve the ICE parameters of the ICE gatherer. :rtype: RTCIceParameters
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, )
(self) -> aiortc.rtcicetransport.RTCIceParameters
718,813
aiortc.rtcicetransport
RTCIceParameters
The :class:`RTCIceParameters` dictionary includes the ICE username fragment and password and other ICE-related parameters.
class RTCIceParameters: """ The :class:`RTCIceParameters` dictionary includes the ICE username fragment and password and other ICE-related parameters. """ usernameFragment: Optional[str] = None "ICE username fragment." password: Optional[str] = None "ICE password." iceLite: bool = False
(usernameFragment: Optional[str] = None, password: Optional[str] = None, iceLite: bool = False) -> None
718,817
aiortc.rtcconfiguration
RTCIceServer
The :class:`RTCIceServer` dictionary defines how to connect to a single STUN or TURN server. It includes both the URL and the necessary credentials, if any, to connect to the server.
class RTCIceServer: """ The :class:`RTCIceServer` dictionary defines how to connect to a single STUN or TURN server. It includes both the URL and the necessary credentials, if any, to connect to the server. """ urls: str """ This required property is either a single string or a list of strings, each specifying a URL which can be used to connect to the server. """ username: Optional[str] = None "The username to use during authentication (for TURN only)." credential: Optional[str] = None "The credential to use during authentication (for TURN only)." credentialType: str = "password"
(urls: str, username: Optional[str] = None, credential: Optional[str] = None, credentialType: str = 'password') -> None
718,821
aiortc.rtcicetransport
RTCIceTransport
The :class:`RTCIceTransport` interface allows an application access to information about the Interactive Connectivity Establishment (ICE) transport over which packets are sent and received. :param gatherer: An :class:`RTCIceGatherer`.
class RTCIceTransport(AsyncIOEventEmitter): """ The :class:`RTCIceTransport` interface allows an application access to information about the Interactive Connectivity Establishment (ICE) transport over which packets are sent and received. :param gatherer: An :class:`RTCIceGatherer`. """ def __init__(self, gatherer: RTCIceGatherer) -> None: super().__init__() self.__iceGatherer = gatherer self.__monitor_task: Optional[asyncio.Future[None]] = None self.__start: Optional[asyncio.Event] = None self.__state = "new" self._connection = gatherer._connection self._role_set = False # expose recv / send methods self._recv = self._connection.recv self._send = self._connection.send @property def iceGatherer(self) -> RTCIceGatherer: """ The ICE gatherer passed in the constructor. """ return self.__iceGatherer @property 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" @property def state(self) -> str: """ The current state of the ICE transport. """ return self.__state 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) ) 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] 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() 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 async def _monitor(self) -> None: while True: event = await self._connection.get_event() if isinstance(event, ConnectionClosed): if self.state == "completed": self.__setState("failed") return def __log_debug(self, msg: str, *args) -> None: logger.debug(f"RTCIceTransport(%s) {msg}", self.role, *args) def __setState(self, state: str) -> None: if state != self.__state: self.__log_debug("- %s -> %s", self.__state, state) self.__state = state self.emit("statechange") # no more events will be emitted, so remove all event listeners # to facilitate garbage collection. if state == "closed": self.iceGatherer.remove_all_listeners() self.remove_all_listeners()
(gatherer: aiortc.rtcicetransport.RTCIceGatherer) -> None
718,822
aiortc.rtcicetransport
__log_debug
null
def __log_debug(self, msg: str, *args) -> None: logger.debug(f"RTCIceTransport(%s) {msg}", self.role, *args)
(self, msg: str, *args) -> NoneType
718,823
aiortc.rtcicetransport
__setState
null
def __setState(self, state: str) -> None: if state != self.__state: self.__log_debug("- %s -> %s", self.__state, state) self.__state = state self.emit("statechange") # no more events will be emitted, so remove all event listeners # to facilitate garbage collection. if state == "closed": self.iceGatherer.remove_all_listeners() self.remove_all_listeners()
(self, state: str) -> NoneType
718,825
aiortc.rtcicetransport
__init__
null
def __init__(self, gatherer: RTCIceGatherer) -> None: super().__init__() self.__iceGatherer = gatherer self.__monitor_task: Optional[asyncio.Future[None]] = None self.__start: Optional[asyncio.Event] = None self.__state = "new" self._connection = gatherer._connection self._role_set = False # expose recv / send methods self._recv = self._connection.recv self._send = self._connection.send
(self, gatherer: aiortc.rtcicetransport.RTCIceGatherer) -> NoneType
718,831
aiortc.rtcicetransport
_monitor
null
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]
(self) -> NoneType
718,833
aiortc.rtcicetransport
addRemoteCandidate
Add a remote candidate. :param candidate: The new candidate or `None` to signal end of candidates.
@property def state(self) -> str: """ The current state of the ICE transport. """ return self.__state
(self, candidate: Optional[aiortc.rtcicetransport.RTCIceCandidate]) -> NoneType
718,837
aiortc.rtcicetransport
getRemoteCandidates
Retrieve the list of candidates associated with the remote :class:`RTCIceTransport`.
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]
(self) -> List[aiortc.rtcicetransport.RTCIceCandidate]
718,844
aiortc.rtcicetransport
start
Initiate connectivity checks. :param remoteParameters: The :class:`RTCIceParameters` associated with the remote :class:`RTCIceTransport`.
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]
(self, remoteParameters: aiortc.rtcicetransport.RTCIceParameters) -> NoneType
718,845
aiortc.rtcicetransport
stop
Irreversibly stop the :class:`RTCIceTransport`.
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]
(self) -> NoneType
718,846
aiortc.stats
RTCInboundRtpStreamStats
The :class:`RTCInboundRtpStreamStats` dictionary represents the measurement metrics for the incoming RTP media stream.
class RTCInboundRtpStreamStats(RTCReceivedRtpStreamStats): """ The :class:`RTCInboundRtpStreamStats` dictionary represents the measurement metrics for the incoming RTP media stream. """ pass
(timestamp: datetime.datetime, type: str, id: str, ssrc: int, kind: str, transportId: str, packetsReceived: int, packetsLost: int, jitter: int) -> None
718,847
aiortc.stats
__eq__
null
import datetime from dataclasses import dataclass from typing import Optional @dataclass class RTCStats: """ Base class for statistics. """ timestamp: datetime.datetime "The timestamp associated with this object." type: str id: str
(self, other)
718,850
aiortc.stats
RTCOutboundRtpStreamStats
The :class:`RTCOutboundRtpStreamStats` dictionary represents the measurement metrics for the outgoing RTP stream.
class RTCOutboundRtpStreamStats(RTCSentRtpStreamStats): """ The :class:`RTCOutboundRtpStreamStats` dictionary represents the measurement metrics for the outgoing RTP stream. """ trackId: str
(timestamp: datetime.datetime, type: str, id: str, ssrc: int, kind: str, transportId: str, packetsSent: int, bytesSent: int, trackId: str) -> None
718,854
aiortc.rtcpeerconnection
RTCPeerConnection
The :class:`RTCPeerConnection` interface represents a WebRTC connection between the local computer and a remote peer. :param configuration: An optional :class:`RTCConfiguration`.
class RTCPeerConnection(AsyncIOEventEmitter): """ The :class:`RTCPeerConnection` interface represents a WebRTC connection between the local computer and a remote peer. :param configuration: An optional :class:`RTCConfiguration`. """ 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 @property 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 @property 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 @property 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 @property def localDescription(self) -> RTCSessionDescription: """ An :class:`RTCSessionDescription` describing the session for the local end of the connection. """ return wrap_session_description(self.__localDescription()) @property def remoteDescription(self) -> RTCSessionDescription: """ An :class:`RTCSessionDescription` describing the session for the remote end of the connection. """ return wrap_session_description(self.__remoteDescription()) @property def sctp(self) -> Optional[RTCSctpTransport]: """ An :class:`RTCSctpTransport` describing the SCTP transport being used for datachannels or `None`. """ return self.__sctp @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 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) 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 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 ) async def close(self): """ 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) async def createAnswer(self): """ 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) 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) 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) 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)) 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)) 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 def getTransceivers(self) -> List[RTCRtpTransceiver]: """ Returns the list of :class:`RTCRtpTransceiver` objects that are currently attached to the connection. """ return list(self.__transceivers) 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 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 == "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 async def __connect(self) -> None: for transceiver in self.__transceivers: dtlsTransport = transceiver._transport iceTransport = dtlsTransport.transport if ( iceTransport.iceGatherer.getLocalCandidates() and transceiver in self.__remoteIce ): await iceTransport.start(self.__remoteIce[transceiver]) if dtlsTransport.state == "new": await dtlsTransport.start(self.__remoteDtls[transceiver]) if dtlsTransport.state == "connected": if transceiver.currentDirection in ["sendonly", "sendrecv"]: await transceiver.sender.send(self.__localRtp(transceiver)) if transceiver.currentDirection in ["recvonly", "sendrecv"]: await transceiver.receiver.receive( self.__remoteRtp(transceiver) ) if self.__sctp: dtlsTransport = self.__sctp.transport iceTransport = dtlsTransport.transport if ( iceTransport.iceGatherer.getLocalCandidates() and self.__sctp in self.__remoteIce ): await iceTransport.start(self.__remoteIce[self.__sctp]) if dtlsTransport.state == "new": await dtlsTransport.start(self.__remoteDtls[self.__sctp]) if dtlsTransport.state == "connected": await self.__sctp.start( self.__sctpRemoteCaps, self.__sctpRemotePort ) async def __gather(self) -> None: coros = map(lambda t: t.iceGatherer.gather(), self.__iceTransports) await asyncio.gather(*coros) def __assertNotClosed(self) -> None: if self.__isClosed: raise InvalidStateError("RTCPeerConnection is closed") def __assertTrackHasNoSender(self, track: MediaStreamTrack) -> None: for sender in self.getSenders(): if sender.track == track: raise InvalidAccessError("Track already has a sender") def __createDtlsTransport(self) -> RTCDtlsTransport: # create ICE transport iceGatherer = RTCIceGatherer(iceServers=self.__configuration.iceServers) iceGatherer.on("statechange", self.__updateIceGatheringState) iceTransport = RTCIceTransport(iceGatherer) iceTransport.on("statechange", self.__updateIceConnectionState) iceTransport.on("statechange", self.__updateConnectionState) self.__iceTransports.add(iceTransport) # create DTLS transport dtlsTransport = RTCDtlsTransport(iceTransport, self.__certificates) dtlsTransport.on("statechange", self.__updateConnectionState) self.__dtlsTransports.add(dtlsTransport) # update states self.__updateIceGatheringState() self.__updateIceConnectionState() self.__updateConnectionState() return dtlsTransport def __createSctpTransport(self) -> None: self.__sctp = RTCSctpTransport(self.__createDtlsTransport()) self.__sctp._bundled = False self.__sctp.mid = None @self.__sctp.on("datachannel") def on_datachannel(channel): self.emit("datachannel", channel) def __createTransceiver( self, direction: str, kind: str, sender_track=None ) -> RTCRtpTransceiver: dtlsTransport = self.__createDtlsTransport() transceiver = RTCRtpTransceiver( direction=direction, kind=kind, sender=RTCRtpSender(sender_track or kind, dtlsTransport), receiver=RTCRtpReceiver(kind, dtlsTransport), ) transceiver.receiver._set_rtcp_ssrc(transceiver.sender._ssrc) transceiver.sender._stream_id = self.__stream_id transceiver._bundled = False transceiver._transport = dtlsTransport self.__transceivers.append(transceiver) return transceiver def __getTransceiverByMid(self, mid: str) -> Optional[RTCRtpTransceiver]: return next(filter(lambda x: x.mid == mid, self.__transceivers), None) def __getTransceiverByMLineIndex(self, index: int) -> Optional[RTCRtpTransceiver]: return next( filter(lambda x: x._get_mline_index() == index, self.__transceivers), None ) def __localDescription(self) -> Optional[sdp.SessionDescription]: return self.__pendingLocalDescription or self.__currentLocalDescription def __localRtp(self, transceiver: RTCRtpTransceiver) -> RTCRtpSendParameters: rtp = RTCRtpSendParameters( codecs=transceiver._codecs, headerExtensions=transceiver._headerExtensions, muxId=transceiver.mid, ) rtp.rtcp.cname = self.__cname rtp.rtcp.ssrc = transceiver.sender._ssrc rtp.rtcp.mux = True return rtp def __log_debug(self, msg: str, *args) -> None: logger.debug(f"RTCPeerConnection() {msg}", *args) def __remoteDescription(self) -> Optional[sdp.SessionDescription]: return self.__pendingRemoteDescription or self.__currentRemoteDescription def __remoteRtp(self, transceiver: RTCRtpTransceiver) -> RTCRtpReceiveParameters: media = self.__remoteDescription().media[transceiver._get_mline_index()] receiveParameters = RTCRtpReceiveParameters( codecs=transceiver._codecs, headerExtensions=transceiver._headerExtensions, muxId=media.rtp.muxId, rtcp=media.rtp.rtcp, ) if len(media.ssrc): encodings: Dict[int, RTCRtpDecodingParameters] = {} for codec in transceiver._codecs: if is_rtx(codec): if codec.parameters["apt"] in encodings and len(media.ssrc) == 2: encodings[codec.parameters["apt"]].rtx = RTCRtpRtxParameters( ssrc=media.ssrc[1].ssrc ) continue encodings[codec.payloadType] = RTCRtpDecodingParameters( ssrc=media.ssrc[0].ssrc, payloadType=codec.payloadType ) receiveParameters.encodings = list(encodings.values()) return receiveParameters def __setSignalingState(self, state: str) -> None: self.__signalingState = state self.emit("signalingstatechange") 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()) 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") 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") 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")
(configuration: Optional[aiortc.rtcconfiguration.RTCConfiguration] = None) -> None
718,855
aiortc.rtcpeerconnection
__assertNotClosed
null
def __assertNotClosed(self) -> None: if self.__isClosed: raise InvalidStateError("RTCPeerConnection is closed")
(self) -> NoneType
718,856
aiortc.rtcpeerconnection
__assertTrackHasNoSender
null
def __assertTrackHasNoSender(self, track: MediaStreamTrack) -> None: for sender in self.getSenders(): if sender.track == track: raise InvalidAccessError("Track already has a sender")
(self, track: aiortc.mediastreams.MediaStreamTrack) -> NoneType
718,857
aiortc.rtcpeerconnection
__connect
null
def getTransceivers(self) -> List[RTCRtpTransceiver]: """ Returns the list of :class:`RTCRtpTransceiver` objects that are currently attached to the connection. """ return list(self.__transceivers)
(self) -> NoneType
718,858
aiortc.rtcpeerconnection
__createDtlsTransport
null
def __createDtlsTransport(self) -> RTCDtlsTransport: # create ICE transport iceGatherer = RTCIceGatherer(iceServers=self.__configuration.iceServers) iceGatherer.on("statechange", self.__updateIceGatheringState) iceTransport = RTCIceTransport(iceGatherer) iceTransport.on("statechange", self.__updateIceConnectionState) iceTransport.on("statechange", self.__updateConnectionState) self.__iceTransports.add(iceTransport) # create DTLS transport dtlsTransport = RTCDtlsTransport(iceTransport, self.__certificates) dtlsTransport.on("statechange", self.__updateConnectionState) self.__dtlsTransports.add(dtlsTransport) # update states self.__updateIceGatheringState() self.__updateIceConnectionState() self.__updateConnectionState() return dtlsTransport
(self) -> aiortc.rtcdtlstransport.RTCDtlsTransport
718,859
aiortc.rtcpeerconnection
__createSctpTransport
null
def __createSctpTransport(self) -> None: self.__sctp = RTCSctpTransport(self.__createDtlsTransport()) self.__sctp._bundled = False self.__sctp.mid = None @self.__sctp.on("datachannel") def on_datachannel(channel): self.emit("datachannel", channel)
(self) -> NoneType
718,860
aiortc.rtcpeerconnection
__createTransceiver
null
def __createTransceiver( self, direction: str, kind: str, sender_track=None ) -> RTCRtpTransceiver: dtlsTransport = self.__createDtlsTransport() transceiver = RTCRtpTransceiver( direction=direction, kind=kind, sender=RTCRtpSender(sender_track or kind, dtlsTransport), receiver=RTCRtpReceiver(kind, dtlsTransport), ) transceiver.receiver._set_rtcp_ssrc(transceiver.sender._ssrc) transceiver.sender._stream_id = self.__stream_id transceiver._bundled = False transceiver._transport = dtlsTransport self.__transceivers.append(transceiver) return transceiver
(self, direction: str, kind: str, sender_track=None) -> aiortc.rtcrtptransceiver.RTCRtpTransceiver
718,862
aiortc.rtcpeerconnection
__getTransceiverByMLineIndex
null
def __getTransceiverByMLineIndex(self, index: int) -> Optional[RTCRtpTransceiver]: return next( filter(lambda x: x._get_mline_index() == index, self.__transceivers), None )
(self, index: int) -> Optional[aiortc.rtcrtptransceiver.RTCRtpTransceiver]
718,863
aiortc.rtcpeerconnection
__getTransceiverByMid
null
def __getTransceiverByMid(self, mid: str) -> Optional[RTCRtpTransceiver]: return next(filter(lambda x: x.mid == mid, self.__transceivers), None)
(self, mid: str) -> Optional[aiortc.rtcrtptransceiver.RTCRtpTransceiver]
718,864
aiortc.rtcpeerconnection
__localDescription
null
def __localDescription(self) -> Optional[sdp.SessionDescription]: return self.__pendingLocalDescription or self.__currentLocalDescription
(self) -> Optional[aiortc.sdp.SessionDescription]
718,865
aiortc.rtcpeerconnection
__localRtp
null
def __localRtp(self, transceiver: RTCRtpTransceiver) -> RTCRtpSendParameters: rtp = RTCRtpSendParameters( codecs=transceiver._codecs, headerExtensions=transceiver._headerExtensions, muxId=transceiver.mid, ) rtp.rtcp.cname = self.__cname rtp.rtcp.ssrc = transceiver.sender._ssrc rtp.rtcp.mux = True return rtp
(self, transceiver: aiortc.rtcrtptransceiver.RTCRtpTransceiver) -> aiortc.rtcrtpparameters.RTCRtpSendParameters
718,866
aiortc.rtcpeerconnection
__log_debug
null
def __log_debug(self, msg: str, *args) -> None: logger.debug(f"RTCPeerConnection() {msg}", *args)
(self, msg: str, *args) -> NoneType
718,867
aiortc.rtcpeerconnection
__remoteDescription
null
def __remoteDescription(self) -> Optional[sdp.SessionDescription]: return self.__pendingRemoteDescription or self.__currentRemoteDescription
(self) -> Optional[aiortc.sdp.SessionDescription]
718,868
aiortc.rtcpeerconnection
__remoteRtp
null
def __remoteRtp(self, transceiver: RTCRtpTransceiver) -> RTCRtpReceiveParameters: media = self.__remoteDescription().media[transceiver._get_mline_index()] receiveParameters = RTCRtpReceiveParameters( codecs=transceiver._codecs, headerExtensions=transceiver._headerExtensions, muxId=media.rtp.muxId, rtcp=media.rtp.rtcp, ) if len(media.ssrc): encodings: Dict[int, RTCRtpDecodingParameters] = {} for codec in transceiver._codecs: if is_rtx(codec): if codec.parameters["apt"] in encodings and len(media.ssrc) == 2: encodings[codec.parameters["apt"]].rtx = RTCRtpRtxParameters( ssrc=media.ssrc[1].ssrc ) continue encodings[codec.payloadType] = RTCRtpDecodingParameters( ssrc=media.ssrc[0].ssrc, payloadType=codec.payloadType ) receiveParameters.encodings = list(encodings.values()) return receiveParameters
(self, transceiver: aiortc.rtcrtptransceiver.RTCRtpTransceiver) -> aiortc.rtcrtpparameters.RTCRtpReceiveParameters
718,869
aiortc.rtcpeerconnection
__setSignalingState
null
def __setSignalingState(self, state: str) -> None: self.__signalingState = state self.emit("signalingstatechange")
(self, state: str) -> NoneType