dtelecom-rtc 0.1.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.
@@ -0,0 +1,53 @@
1
+ """dTelecom's asyncio server-side room participant."""
2
+
3
+ from .audio import AudioFrame, AudioSource, RemoteAudioTrack
4
+ from .data import create_text_message, decode_data_packet, encode_data_packet
5
+ from .models import (
6
+ ConnectionQuality,
7
+ DataPacket,
8
+ DataPacketKind,
9
+ DisconnectReason,
10
+ ICEServer,
11
+ ParticipantInfo,
12
+ ParticipantState,
13
+ RoomInfo,
14
+ SpeakerInfo,
15
+ TrackInfo,
16
+ TrackSource,
17
+ TrackType,
18
+ UserPacket,
19
+ )
20
+ from .resample import downsample, resample, upsample
21
+ from .room import LocalPublication, Participant, Publication, Room
22
+ from .transport import SessionEnded, TransportError
23
+
24
+ __all__ = [
25
+ "AudioFrame",
26
+ "AudioSource",
27
+ "ConnectionQuality",
28
+ "DataPacket",
29
+ "DataPacketKind",
30
+ "DisconnectReason",
31
+ "ICEServer",
32
+ "LocalPublication",
33
+ "Participant",
34
+ "ParticipantInfo",
35
+ "ParticipantState",
36
+ "Publication",
37
+ "RemoteAudioTrack",
38
+ "Room",
39
+ "RoomInfo",
40
+ "SessionEnded",
41
+ "SpeakerInfo",
42
+ "TrackInfo",
43
+ "TrackSource",
44
+ "TrackType",
45
+ "TransportError",
46
+ "UserPacket",
47
+ "create_text_message",
48
+ "decode_data_packet",
49
+ "downsample",
50
+ "encode_data_packet",
51
+ "resample",
52
+ "upsample",
53
+ ]
dtelecom_rtc/audio.py ADDED
@@ -0,0 +1,213 @@
1
+ """Paced PCM16 audio for room publishers and subscribers."""
2
+
3
+ import asyncio
4
+ from collections.abc import AsyncIterator
5
+ from dataclasses import dataclass
6
+ from fractions import Fraction
7
+
8
+ import av
9
+ from aiortc import MediaStreamError, MediaStreamTrack
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class AudioFrame:
14
+ data: bytes
15
+ sample_rate: int
16
+ channels: int = 1
17
+
18
+ def __post_init__(self) -> None:
19
+ if self.sample_rate <= 0 or self.channels not in (1, 2):
20
+ raise ValueError(
21
+ "PCM16 requires a positive sample rate and one or two channels"
22
+ )
23
+ if len(self.data) % (2 * self.channels):
24
+ raise ValueError("PCM payload must contain whole interleaved samples")
25
+
26
+ @classmethod
27
+ def silence(cls, sample_rate: int, channels: int, samples_per_channel: int):
28
+ return cls(bytes(samples_per_channel * channels * 2), sample_rate, channels)
29
+
30
+ @property
31
+ def duration(self) -> float:
32
+ return self.samples_per_channel / self.sample_rate
33
+
34
+ @property
35
+ def samples_per_channel(self) -> int:
36
+ return len(self.data) // (2 * self.channels)
37
+
38
+
39
+ class AudioSource:
40
+ """Bounded, paced PCM16 source. A sender can replace its peer connection."""
41
+
42
+ def __init__(
43
+ self, sample_rate: int = 48000, channels: int = 1, *, queue_ms: int = 400
44
+ ):
45
+ if (
46
+ sample_rate <= 0
47
+ or sample_rate % 50
48
+ or channels not in (1, 2)
49
+ or queue_ms < 20
50
+ ):
51
+ raise ValueError(
52
+ "Use whole 20 ms frames, one or two channels, and queue_ms >= 20"
53
+ )
54
+ self.sample_rate = sample_rate
55
+ self.channels = channels
56
+ self._chunk_bytes = (sample_rate // 50) * channels * 2
57
+ self._capacity = max(1, queue_ms // 20) * self._chunk_bytes
58
+ self._buffer = bytearray()
59
+ self._writable = asyncio.Event()
60
+ self._writable.set()
61
+ self._empty = asyncio.Event()
62
+ self._empty.set()
63
+ self._closed = False
64
+ self._epoch = 0
65
+
66
+ async def capture_frame(self, frame: AudioFrame) -> None:
67
+ if (self.sample_rate, self.channels) != (frame.sample_rate, frame.channels):
68
+ raise ValueError("PCM format must match the audio source")
69
+ offset = 0
70
+ epoch = self._epoch
71
+ while offset < len(frame.data):
72
+ if self._closed:
73
+ raise RuntimeError("Audio source is closed")
74
+ if self._epoch != epoch:
75
+ return
76
+ available = self._capacity - len(self._buffer)
77
+ if not available:
78
+ self._writable.clear()
79
+ await self._writable.wait()
80
+ continue
81
+ end = min(len(frame.data), offset + available)
82
+ self._empty.clear()
83
+ self._buffer.extend(frame.data[offset:end])
84
+ offset = end
85
+
86
+ async def drain(self) -> None:
87
+ """Wait until the queued samples have been consumed by the track."""
88
+ await self._empty.wait()
89
+
90
+ def clear_queue(self) -> None:
91
+ self._epoch += 1
92
+ self._buffer.clear()
93
+ self._empty.set()
94
+ self._writable.set()
95
+
96
+ def close(self) -> None:
97
+ self._closed = True
98
+ self.clear_queue()
99
+
100
+ def _read(self) -> bytes:
101
+ if self._closed:
102
+ raise MediaStreamError
103
+ data = bytes(self._buffer[: self._chunk_bytes])
104
+ del self._buffer[: len(data)]
105
+ if not self._buffer:
106
+ self._empty.set()
107
+ self._writable.set()
108
+ return data.ljust(self._chunk_bytes, b"\0")
109
+
110
+
111
+ class SourceTrack(MediaStreamTrack):
112
+ kind = "audio"
113
+
114
+ def __init__(self, source: AudioSource):
115
+ super().__init__()
116
+ self.source = source
117
+ self._pts = 0
118
+ self._next: float | None = None
119
+
120
+ async def recv(self) -> av.AudioFrame:
121
+ if self.readyState != "live":
122
+ raise MediaStreamError
123
+ clock = asyncio.get_running_loop().time
124
+ if self._next is not None:
125
+ await asyncio.sleep(max(0, self._next - clock()))
126
+ self._next = max(self._next or clock(), clock() - 0.02) + 0.02
127
+ source = self.source
128
+ frame = av.AudioFrame(
129
+ format="s16",
130
+ layout="mono" if source.channels == 1 else "stereo",
131
+ samples=source.sample_rate // 50,
132
+ )
133
+ frame.sample_rate = source.sample_rate
134
+ frame.time_base = Fraction(1, source.sample_rate)
135
+ frame.pts = self._pts
136
+ frame.planes[0].update(source._read())
137
+ self._pts += frame.samples
138
+ return frame
139
+
140
+
141
+ class RemoteAudioTrack:
142
+ def __init__(self, media: MediaStreamTrack):
143
+ self.media = media
144
+ self._ended = asyncio.Event()
145
+ media.on("ended", self._ended.set)
146
+
147
+ def stop(self):
148
+ self._ended.set()
149
+ self.media.stop()
150
+
151
+ async def stream(
152
+ self, sample_rate: int = 16000, channels: int = 1
153
+ ) -> AsyncIterator[AudioFrame]:
154
+ """Decode to interleaved PCM16 and maintain the audio clock through silence."""
155
+ if sample_rate <= 0 or sample_rate % 50 or channels not in (1, 2):
156
+ raise ValueError("Expected whole 20 ms frames and one or two channels")
157
+ converter = av.AudioResampler(
158
+ format="s16", layout="mono" if channels == 1 else "stereo", rate=sample_rate
159
+ )
160
+ samples = sample_rate // 50
161
+ silence = AudioFrame(bytes(samples * channels * 2), sample_rate, channels)
162
+ next_pts: int | None = None
163
+ covered = 0
164
+ clock = asyncio.get_running_loop().time
165
+ deadline = clock()
166
+ read = asyncio.create_task(self.media.recv())
167
+ ended = asyncio.create_task(self._ended.wait())
168
+ try:
169
+ while True:
170
+ timeout = None if next_pts is None else max(0.0, deadline - clock())
171
+ done, _ = await asyncio.wait(
172
+ [read, ended], timeout=timeout, return_when=asyncio.FIRST_COMPLETED
173
+ )
174
+ if ended in done:
175
+ return
176
+ if not done:
177
+ covered += samples
178
+ deadline = max(deadline, clock() - 0.02) + 0.02
179
+ yield silence
180
+ continue
181
+ frame = read.result()
182
+ read = asyncio.create_task(self.media.recv())
183
+ start = (
184
+ round(frame.pts * frame.time_base * sample_rate)
185
+ if frame.pts is not None
186
+ else next_pts
187
+ )
188
+ if start is not None and next_pts is not None:
189
+ gap = min(3 * sample_rate, max(0, start - next_pts - covered))
190
+ while gap > 0:
191
+ count = min(samples, gap)
192
+ yield AudioFrame(
193
+ silence.data[: count * channels * 2], sample_rate, channels
194
+ )
195
+ gap -= count
196
+ covered = 0
197
+ # Resample frame data independently of RTP timestamp jumps.
198
+ frame.pts = None
199
+ for pcm in converter.resample(frame):
200
+ yield AudioFrame(
201
+ bytes(pcm.planes[0])[: pcm.samples * channels * 2],
202
+ sample_rate,
203
+ channels,
204
+ )
205
+ duration = frame.samples / frame.sample_rate
206
+ next_pts = (start or 0) + round(duration * sample_rate)
207
+ deadline = clock() + max(0.06, duration)
208
+ except MediaStreamError:
209
+ return
210
+ finally:
211
+ read.cancel()
212
+ ended.cancel()
213
+ await asyncio.gather(read, ended, return_exceptions=True)
dtelecom_rtc/data.py ADDED
@@ -0,0 +1,40 @@
1
+ """Room data messages encoded using the dTelecom wire schema."""
2
+
3
+ from collections.abc import Iterable
4
+
5
+ from dtelecom_server.protocol import message_type
6
+
7
+ DataPacket = message_type("DataPacket")
8
+
9
+
10
+ def encode_data_packet(
11
+ participant_sid: str,
12
+ payload: bytes,
13
+ *,
14
+ reliable: bool = True,
15
+ destination_sids: Iterable[str] = (),
16
+ topic: str | None = None,
17
+ ) -> bytes:
18
+ packet = DataPacket(kind=0 if reliable else 1)
19
+ packet.user.participant_sid = participant_sid
20
+ packet.user.payload = payload
21
+ packet.user.destination_sids.extend(destination_sids)
22
+ if topic is not None:
23
+ packet.user.topic = topic
24
+ return packet.SerializeToString()
25
+
26
+
27
+ def decode_data_packet(data: bytes):
28
+ return DataPacket.FromString(data)
29
+
30
+
31
+ def create_text_message(
32
+ participant_sid: str,
33
+ text: str,
34
+ *,
35
+ destination_sids: Iterable[str] = (),
36
+ topic: str | None = None,
37
+ ) -> bytes:
38
+ return encode_data_packet(
39
+ participant_sid, text.encode(), destination_sids=destination_sids, topic=topic
40
+ )
dtelecom_rtc/models.py ADDED
@@ -0,0 +1,56 @@
1
+ """Room wire types and enums from dTelecom's forked protocol."""
2
+
3
+ from enum import IntEnum
4
+
5
+ from dtelecom_server.protocol import message_type
6
+
7
+ RoomInfo = message_type("Room")
8
+ ParticipantInfo = message_type("ParticipantInfo")
9
+ TrackInfo = message_type("TrackInfo")
10
+ DataPacket = message_type("DataPacket")
11
+ UserPacket = message_type("UserPacket")
12
+ ICEServer = message_type("ICEServer")
13
+ SpeakerInfo = message_type("SpeakerInfo")
14
+
15
+
16
+ class TrackType(IntEnum):
17
+ AUDIO = 0
18
+ VIDEO = 1
19
+ DATA = 2
20
+
21
+
22
+ class TrackSource(IntEnum):
23
+ UNKNOWN = 0
24
+ CAMERA = 1
25
+ MICROPHONE = 2
26
+ SCREEN_SHARE = 3
27
+ SCREEN_SHARE_AUDIO = 4
28
+
29
+
30
+ class DataPacketKind(IntEnum):
31
+ RELIABLE = 0
32
+ LOSSY = 1
33
+
34
+
35
+ class ParticipantState(IntEnum):
36
+ JOINING = 0
37
+ JOINED = 1
38
+ ACTIVE = 2
39
+ DISCONNECTED = 3
40
+
41
+
42
+ class ConnectionQuality(IntEnum):
43
+ POOR = 0
44
+ GOOD = 1
45
+ EXCELLENT = 2
46
+
47
+
48
+ class DisconnectReason(IntEnum):
49
+ UNKNOWN_REASON = 0
50
+ CLIENT_INITIATED = 1
51
+ DUPLICATE_IDENTITY = 2
52
+ SERVER_SHUTDOWN = 3
53
+ PARTICIPANT_REMOVED = 4
54
+ ROOM_DELETED = 5
55
+ STATE_MISMATCH = 6
56
+ JOIN_FAILURE = 7
dtelecom_rtc/py.typed ADDED
File without changes
@@ -0,0 +1,53 @@
1
+ """PCM16 resampling with the speech-oriented filters exposed by the Node SDK."""
2
+
3
+ from array import array
4
+ from math import floor
5
+
6
+ from .audio import AudioFrame
7
+
8
+
9
+ def resample(frame: AudioFrame, sample_rate: int) -> AudioFrame:
10
+ """Resample interleaved PCM16 while preserving the channels."""
11
+ if sample_rate <= 0:
12
+ raise ValueError("sample_rate must be positive")
13
+ if frame.sample_rate == sample_rate:
14
+ return frame
15
+ channels = frame.channels
16
+ source = array("h")
17
+ source.frombytes(frame.data)
18
+ output = array("h")
19
+ length = frame.samples_per_channel
20
+ source_rate = frame.sample_rate
21
+ if source_rate > sample_rate and source_rate % sample_rate == 0:
22
+ width = source_rate // sample_rate
23
+ for first in range(0, length - width + 1, width):
24
+ for channel in range(channels):
25
+ begin = first * channels + channel
26
+ value = sum(source[begin : begin + width * channels : channels]) / width
27
+ output.append(floor(value + 0.5))
28
+ else:
29
+ size = floor(length * sample_rate / source_rate + 0.5)
30
+ for i in range(size):
31
+ a, remainder = divmod(i * source_rate, sample_rate)
32
+ b = min(a + 1, length - 1)
33
+ for channel in range(channels):
34
+ left, right = (
35
+ source[a * channels + channel],
36
+ source[b * channels + channel],
37
+ )
38
+ output.append(
39
+ floor(left + (right - left) * remainder / sample_rate + 0.5)
40
+ )
41
+ return AudioFrame(output.tobytes(), sample_rate, channels)
42
+
43
+
44
+ def downsample(frame: AudioFrame, sample_rate: int) -> AudioFrame:
45
+ if frame.sample_rate < sample_rate:
46
+ raise ValueError("Output sample rate must be at most the input rate")
47
+ return resample(frame, sample_rate)
48
+
49
+
50
+ def upsample(frame: AudioFrame, sample_rate: int) -> AudioFrame:
51
+ if frame.sample_rate > sample_rate:
52
+ raise ValueError("Output sample rate must be at least the input rate")
53
+ return resample(frame, sample_rate)