aiortc 1.12.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
aiortc/__init__.py ADDED
@@ -0,0 +1,100 @@
1
+ # ruff: noqa: F401
2
+ import logging
3
+
4
+ from .exceptions import InvalidAccessError, InvalidStateError
5
+ from .mediastreams import (
6
+ AudioStreamTrack,
7
+ MediaStreamError,
8
+ MediaStreamTrack,
9
+ VideoStreamTrack,
10
+ )
11
+ from .rtcconfiguration import RTCBundlePolicy, RTCConfiguration, RTCIceServer
12
+ from .rtcdatachannel import RTCDataChannel, RTCDataChannelParameters
13
+ from .rtcdtlstransport import (
14
+ RTCCertificate,
15
+ RTCDtlsFingerprint,
16
+ RTCDtlsParameters,
17
+ RTCDtlsTransport,
18
+ )
19
+ from .rtcicetransport import (
20
+ RTCIceCandidate,
21
+ RTCIceGatherer,
22
+ RTCIceParameters,
23
+ RTCIceTransport,
24
+ )
25
+ from .rtcpeerconnection import RTCPeerConnection
26
+ from .rtcrtpparameters import (
27
+ RTCRtcpParameters,
28
+ RTCRtpCapabilities,
29
+ RTCRtpCodecCapability,
30
+ RTCRtpCodecParameters,
31
+ RTCRtpHeaderExtensionCapability,
32
+ RTCRtpHeaderExtensionParameters,
33
+ RTCRtpParameters,
34
+ )
35
+ from .rtcrtpreceiver import (
36
+ RTCRtpContributingSource,
37
+ RTCRtpReceiver,
38
+ RTCRtpSynchronizationSource,
39
+ )
40
+ from .rtcrtpsender import RTCRtpSender
41
+ from .rtcrtptransceiver import RTCRtpTransceiver
42
+ from .rtcsctptransport import RTCSctpCapabilities, RTCSctpTransport
43
+ from .rtcsessiondescription import RTCSessionDescription
44
+ from .stats import (
45
+ RTCInboundRtpStreamStats,
46
+ RTCOutboundRtpStreamStats,
47
+ RTCRemoteInboundRtpStreamStats,
48
+ RTCRemoteOutboundRtpStreamStats,
49
+ RTCStatsReport,
50
+ RTCTransportStats,
51
+ )
52
+
53
+ __version__ = "1.12.0"
54
+
55
+ # Set default logging handler to avoid "No handler found" warnings.
56
+ logging.getLogger(__name__).addHandler(logging.NullHandler())
57
+
58
+ __all__ = [
59
+ "AudioStreamTrack",
60
+ "InvalidAccessError",
61
+ "InvalidStateError",
62
+ "MediaStreamError",
63
+ "MediaStreamTrack",
64
+ "RTCBundlePolicy",
65
+ "RTCCertificate",
66
+ "RTCConfiguration",
67
+ "RTCDataChannel",
68
+ "RTCDataChannelParameters",
69
+ "RTCDtlsFingerprint",
70
+ "RTCDtlsParameters",
71
+ "RTCDtlsTransport",
72
+ "RTCIceCandidate",
73
+ "RTCIceGatherer",
74
+ "RTCIceParameters",
75
+ "RTCIceServer",
76
+ "RTCIceTransport",
77
+ "RTCInboundRtpStreamStats",
78
+ "RTCOutboundRtpStreamStats",
79
+ "RTCPeerConnection",
80
+ "RTCRemoteInboundRtpStreamStats",
81
+ "RTCRemoteOutboundRtpStreamStats",
82
+ "RTCRtcpParameters",
83
+ "RTCRtpCapabilities",
84
+ "RTCRtpCodecCapability",
85
+ "RTCRtpCodecParameters",
86
+ "RTCRtpContributingSource",
87
+ "RTCRtpHeaderExtensionCapability",
88
+ "RTCRtpHeaderExtensionParameters",
89
+ "RTCRtpParameters",
90
+ "RTCRtpReceiver",
91
+ "RTCRtpSender",
92
+ "RTCRtpSynchronizationSource",
93
+ "RTCRtpTransceiver",
94
+ "RTCSctpCapabilities",
95
+ "RTCSctpTransport",
96
+ "RTCSessionDescription",
97
+ "RTCStatsReport",
98
+ "RTCTransportStats",
99
+ "VideoStreamTrack",
100
+ ]
aiortc/clock.py ADDED
@@ -0,0 +1,29 @@
1
+ import datetime
2
+
3
+ NTP_EPOCH = datetime.datetime(1900, 1, 1, tzinfo=datetime.timezone.utc)
4
+
5
+
6
+ def current_datetime() -> datetime.datetime:
7
+ return datetime.datetime.now(datetime.timezone.utc)
8
+
9
+
10
+ def current_ms() -> int:
11
+ delta = current_datetime() - NTP_EPOCH
12
+ return int(delta.total_seconds() * 1000)
13
+
14
+
15
+ def current_ntp_time() -> int:
16
+ return datetime_to_ntp(current_datetime())
17
+
18
+
19
+ def datetime_from_ntp(ntp: int) -> datetime.datetime:
20
+ seconds = ntp >> 32
21
+ microseconds = ((ntp & 0xFFFFFFFF) * 1000000) / (1 << 32)
22
+ return NTP_EPOCH + datetime.timedelta(seconds=seconds, microseconds=microseconds)
23
+
24
+
25
+ def datetime_to_ntp(dt: datetime.datetime) -> int:
26
+ delta = dt - NTP_EPOCH
27
+ high = int(delta.total_seconds())
28
+ low = round((delta.microseconds * (1 << 32)) // 1000000)
29
+ return (high << 32) | low
@@ -0,0 +1,179 @@
1
+ from typing import Optional, Union
2
+
3
+ from ..rtcrtpparameters import (
4
+ ParametersDict,
5
+ RTCRtcpFeedback,
6
+ RTCRtpCapabilities,
7
+ RTCRtpCodecCapability,
8
+ RTCRtpCodecParameters,
9
+ RTCRtpHeaderExtensionCapability,
10
+ RTCRtpHeaderExtensionParameters,
11
+ )
12
+ from .base import Decoder, Encoder
13
+ from .g711 import PcmaDecoder, PcmaEncoder, PcmuDecoder, PcmuEncoder
14
+ from .h264 import H264Decoder, H264Encoder, h264_depayload
15
+ from .opus import OpusDecoder, OpusEncoder
16
+ from .vpx import Vp8Decoder, Vp8Encoder, vp8_depayload
17
+
18
+ PCMU_CODEC = RTCRtpCodecParameters(
19
+ mimeType="audio/PCMU", clockRate=8000, channels=1, payloadType=0
20
+ )
21
+ PCMA_CODEC = RTCRtpCodecParameters(
22
+ mimeType="audio/PCMA", clockRate=8000, channels=1, payloadType=8
23
+ )
24
+
25
+ CODECS: dict[str, list[RTCRtpCodecParameters]] = {
26
+ "audio": [
27
+ RTCRtpCodecParameters(
28
+ mimeType="audio/opus", clockRate=48000, channels=2, payloadType=96
29
+ ),
30
+ PCMU_CODEC,
31
+ PCMA_CODEC,
32
+ ],
33
+ "video": [],
34
+ }
35
+ # Note, the id space for these extensions is shared across media types when BUNDLE
36
+ # is negotiated. If you add a audio- or video-specific extension, make sure it has
37
+ # a unique id.
38
+ HEADER_EXTENSIONS: dict[str, list[RTCRtpHeaderExtensionParameters]] = {
39
+ "audio": [
40
+ RTCRtpHeaderExtensionParameters(
41
+ id=1, uri="urn:ietf:params:rtp-hdrext:sdes:mid"
42
+ ),
43
+ RTCRtpHeaderExtensionParameters(
44
+ id=2, uri="urn:ietf:params:rtp-hdrext:ssrc-audio-level"
45
+ ),
46
+ ],
47
+ "video": [
48
+ RTCRtpHeaderExtensionParameters(
49
+ id=1, uri="urn:ietf:params:rtp-hdrext:sdes:mid"
50
+ ),
51
+ RTCRtpHeaderExtensionParameters(
52
+ id=3, uri="http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"
53
+ ),
54
+ ],
55
+ }
56
+
57
+
58
+ def init_codecs() -> None:
59
+ dynamic_pt = 97
60
+
61
+ def add_video_codec(
62
+ mimeType: str, parameters: Optional[ParametersDict] = None
63
+ ) -> None:
64
+ nonlocal dynamic_pt
65
+
66
+ clockRate = 90000
67
+ CODECS["video"] += [
68
+ RTCRtpCodecParameters(
69
+ mimeType=mimeType,
70
+ clockRate=clockRate,
71
+ payloadType=dynamic_pt,
72
+ rtcpFeedback=[
73
+ RTCRtcpFeedback(type="nack"),
74
+ RTCRtcpFeedback(type="nack", parameter="pli"),
75
+ RTCRtcpFeedback(type="goog-remb"),
76
+ ],
77
+ parameters=parameters or {},
78
+ ),
79
+ RTCRtpCodecParameters(
80
+ mimeType="video/rtx",
81
+ clockRate=clockRate,
82
+ payloadType=dynamic_pt + 1,
83
+ parameters={"apt": dynamic_pt},
84
+ ),
85
+ ]
86
+ dynamic_pt += 2
87
+
88
+ add_video_codec("video/VP8")
89
+ for profile_level_id in ("42001f", "42e01f"):
90
+ add_video_codec(
91
+ "video/H264",
92
+ {
93
+ "level-asymmetry-allowed": "1",
94
+ "packetization-mode": "1",
95
+ "profile-level-id": profile_level_id,
96
+ },
97
+ )
98
+
99
+
100
+ def depayload(codec: RTCRtpCodecParameters, payload: bytes) -> bytes:
101
+ if codec.name == "VP8":
102
+ return vp8_depayload(payload)
103
+ elif codec.name == "H264":
104
+ return h264_depayload(payload)
105
+ else:
106
+ return payload
107
+
108
+
109
+ def get_capabilities(kind: str) -> RTCRtpCapabilities:
110
+ if kind not in CODECS:
111
+ raise ValueError(f"cannot get capabilities for unknown media {kind}")
112
+
113
+ codecs = []
114
+ rtx_added = False
115
+ for params in CODECS[kind]:
116
+ if not is_rtx(params):
117
+ codecs.append(
118
+ RTCRtpCodecCapability(
119
+ mimeType=params.mimeType,
120
+ clockRate=params.clockRate,
121
+ channels=params.channels,
122
+ parameters=params.parameters,
123
+ )
124
+ )
125
+ elif not rtx_added:
126
+ # There will only be a single entry in codecs[] for retransmission
127
+ # via RTX, with sdpFmtpLine not present.
128
+ codecs.append(
129
+ RTCRtpCodecCapability(
130
+ mimeType=params.mimeType, clockRate=params.clockRate
131
+ )
132
+ )
133
+ rtx_added = True
134
+
135
+ headerExtensions = []
136
+ for extension in HEADER_EXTENSIONS[kind]:
137
+ headerExtensions.append(RTCRtpHeaderExtensionCapability(uri=extension.uri))
138
+ return RTCRtpCapabilities(codecs=codecs, headerExtensions=headerExtensions)
139
+
140
+
141
+ def get_decoder(codec: RTCRtpCodecParameters) -> Decoder:
142
+ mimeType = codec.mimeType.lower()
143
+
144
+ if mimeType == "audio/opus":
145
+ return OpusDecoder()
146
+ elif mimeType == "audio/pcma":
147
+ return PcmaDecoder()
148
+ elif mimeType == "audio/pcmu":
149
+ return PcmuDecoder()
150
+ elif mimeType == "video/h264":
151
+ return H264Decoder()
152
+ elif mimeType == "video/vp8":
153
+ return Vp8Decoder()
154
+ else:
155
+ raise ValueError(f"No decoder found for MIME type `{mimeType}`")
156
+
157
+
158
+ def get_encoder(codec: RTCRtpCodecParameters) -> Encoder:
159
+ mimeType = codec.mimeType.lower()
160
+
161
+ if mimeType == "audio/opus":
162
+ return OpusEncoder()
163
+ elif mimeType == "audio/pcma":
164
+ return PcmaEncoder()
165
+ elif mimeType == "audio/pcmu":
166
+ return PcmuEncoder()
167
+ elif mimeType == "video/h264":
168
+ return H264Encoder()
169
+ elif mimeType == "video/vp8":
170
+ return Vp8Encoder()
171
+ else:
172
+ raise ValueError(f"No encoder found for MIME type `{mimeType}`")
173
+
174
+
175
+ def is_rtx(codec: Union[RTCRtpCodecCapability, RTCRtpCodecParameters]) -> bool:
176
+ return codec.name.lower() == "rtx"
177
+
178
+
179
+ init_codecs()
aiortc/codecs/base.py ADDED
@@ -0,0 +1,24 @@
1
+ from abc import ABCMeta, abstractmethod
2
+
3
+ from av.frame import Frame
4
+ from av.packet import Packet
5
+
6
+ from ..jitterbuffer import JitterFrame
7
+
8
+
9
+ class Decoder(metaclass=ABCMeta):
10
+ @abstractmethod
11
+ def decode(self, encoded_frame: JitterFrame) -> list[Frame]:
12
+ pass # pragma: no cover
13
+
14
+
15
+ class Encoder(metaclass=ABCMeta):
16
+ @abstractmethod
17
+ def encode(
18
+ self, frame: Frame, force_keyframe: bool = False
19
+ ) -> tuple[list[bytes], int]:
20
+ pass # pragma: no cover
21
+
22
+ @abstractmethod
23
+ def pack(self, packet: Packet) -> tuple[list[bytes], int]:
24
+ pass # pragma: no cover
aiortc/codecs/g711.py ADDED
@@ -0,0 +1,89 @@
1
+ import fractions
2
+ from typing import Literal, cast
3
+
4
+ from av import AudioFrame, AudioResampler, CodecContext
5
+ from av.frame import Frame
6
+ from av.packet import Packet
7
+
8
+ from ..jitterbuffer import JitterFrame
9
+ from ..mediastreams import convert_timebase
10
+ from .base import Decoder, Encoder
11
+
12
+ SAMPLE_RATE = 8000
13
+ SAMPLE_WIDTH = 2
14
+ SAMPLES_PER_FRAME = 160
15
+ TIME_BASE = fractions.Fraction(1, 8000)
16
+
17
+
18
+ class PcmDecoder(Decoder):
19
+ def __init__(self, codec_name: Literal["pcm_alaw", "pcm_mulaw"]) -> None:
20
+ self.codec = CodecContext.create(codec_name, "r")
21
+ self.codec.format = "s16"
22
+ self.codec.layout = "mono"
23
+ self.codec.sample_rate = SAMPLE_RATE
24
+
25
+ def decode(self, encoded_frame: JitterFrame) -> list[Frame]:
26
+ packet = Packet(encoded_frame.data)
27
+ packet.pts = encoded_frame.timestamp
28
+ packet.time_base = TIME_BASE
29
+ return cast(list[Frame], self.codec.decode(packet))
30
+
31
+
32
+ class PcmEncoder(Encoder):
33
+ def __init__(self, codec_name: Literal["pcm_alaw", "pcm_mulaw"]) -> None:
34
+ self.codec = CodecContext.create(codec_name, "w")
35
+ self.codec.format = "s16"
36
+ self.codec.layout = "mono"
37
+ self.codec.sample_rate = SAMPLE_RATE
38
+ self.codec.time_base = TIME_BASE
39
+
40
+ # Create our own resampler to control the frame size.
41
+ self.resampler = AudioResampler(
42
+ format="s16",
43
+ layout="mono",
44
+ rate=SAMPLE_RATE,
45
+ frame_size=SAMPLES_PER_FRAME,
46
+ )
47
+
48
+ def encode(
49
+ self, frame: Frame, force_keyframe: bool = False
50
+ ) -> tuple[list[bytes], int]:
51
+ assert isinstance(frame, AudioFrame)
52
+ assert frame.format.name == "s16"
53
+ assert frame.layout.name in ["mono", "stereo"]
54
+
55
+ # Send frame through resampler and encoder.
56
+ packets = []
57
+ for frame in self.resampler.resample(frame):
58
+ packets += self.codec.encode(frame)
59
+
60
+ if packets:
61
+ # Packets were returned.
62
+ return [bytes(p) for p in packets], packets[0].pts
63
+ else:
64
+ # No packets were returned due to buffering.
65
+ return [], None
66
+
67
+ def pack(self, packet: Packet) -> tuple[list[bytes], int]:
68
+ timestamp = convert_timebase(packet.pts, packet.time_base, TIME_BASE)
69
+ return [bytes(packet)], timestamp
70
+
71
+
72
+ class PcmaDecoder(PcmDecoder):
73
+ def __init__(self) -> None:
74
+ super().__init__("pcm_alaw")
75
+
76
+
77
+ class PcmaEncoder(PcmEncoder):
78
+ def __init__(self) -> None:
79
+ super().__init__("pcm_alaw")
80
+
81
+
82
+ class PcmuDecoder(PcmDecoder):
83
+ def __init__(self) -> None:
84
+ super().__init__("pcm_mulaw")
85
+
86
+
87
+ class PcmuEncoder(PcmEncoder):
88
+ def __init__(self) -> None:
89
+ super().__init__("pcm_mulaw")