dtelecom-rtc 0.1.0__tar.gz

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,11 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.py[cod]
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ dist/
7
+ build/
8
+ *.egg-info/
9
+ .env
10
+ .env.*
11
+ !.env.example
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ This package implements the signaling, room and data behavior of dTelecom/server-sdk-node v0.4.0 under the Apache License 2.0. Its asyncio implementation uses aiortc and the dTelecom protocol schema from the companion Python server package.
@@ -0,0 +1,45 @@
1
+ Metadata-Version: 2.5
2
+ Name: dtelecom-rtc
3
+ Version: 0.1.0
4
+ Summary: Server-side asyncio audio and data participant for dTelecom rooms
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ License-File: NOTICE
8
+ Requires-Python: >=3.11
9
+ Requires-Dist: aiortc<1.18,>=1.17
10
+ Requires-Dist: av<20,>=14
11
+ Requires-Dist: dtelecom-server-sdk==0.1.0
12
+ Requires-Dist: pyee<17,>=13
13
+ Requires-Dist: websockets<17,>=14
14
+ Description-Content-Type: text/markdown
15
+
16
+ # dTelecom RTC for Python
17
+
18
+ Join a dTelecom room from a Python process, receive remote audio as PCM16, and publish audio or room data. Supply a participant grant from your backend. Its response includes the signaling URL, token and ranked fallback URLs. [Room connections](https://docs.dtelecom.org/rooms/connect/)
19
+
20
+ ```python
21
+ from dtelecom_rtc import AudioSource, Room
22
+
23
+ async def echo(grant, finished):
24
+ source = AudioSource(sample_rate=16000)
25
+ async with Room() as room:
26
+ @room.on("track_subscribed")
27
+ async def receive(track, publication, participant):
28
+ async for frame in track.stream(sample_rate=16000):
29
+ await source.capture_frame(frame)
30
+
31
+ await room.connect(grant.ws_url, grant.token, fallback_urls=grant.fallback_urls)
32
+ await room.publish_audio("echo", source)
33
+ await finished.wait()
34
+ source.close()
35
+ ```
36
+
37
+ Use a distinct identity for each participant. Set `auto_subscribe=False` to choose remote tracks explicitly with `set_subscribed`. Register event handlers before joining to include publications already present in the room. A `data_received` handler receives payload bytes, the sender when known, the delivery kind and topic. `publish_data` accepts a string or bytes, optional topic and destination participant SIDs, and reliable or lossy delivery.
38
+
39
+ The SDK tries the issuer's ranked endpoints with the same grant after a transport failure. When extending a grant through Cloud, call `room.update_connection_token(token, fallback_urls)` so the room uses the refreshed credentials after a reconnect. Use `disconnect()` or exit the async context to leave.
40
+
41
+ Configure SDK log levels using Python's standard `logging.getLogger("dtelecom_rtc").setLevel(...)`. Use `AudioFrame.duration`, `samples_per_channel`, and the `resample`, `downsample` and `upsample` helpers for standalone PCM. `create_text_message`, `encode_data_packet` and `decode_data_packet` expose the fork's room-data format. The protocol message models and enums are exported from `dtelecom_rtc.models`.
42
+
43
+ For a live interoperability check, install Playwright and use the ESM bundle of `@dtelecom/livekit-client@1.13.0`. Set `DTELECOM_API_KEY`, `DTELECOM_API_SECRET`, `DTELECOM_CLOUD_URL` and `DTELECOM_BROWSER_MODULE`, then run `python tests/integration/browser_call.py`. The script creates a disposable room and uses synthetic audio. Add `--recovery` to test a grant with three ranked nodes and reconnect the Python publisher. `CHROME_EXECUTABLE` selects a local browser when needed.
44
+
45
+ On transport loss, `room.state` becomes `"reconnecting"` and the room emits `reconnecting` before releasing remote tracks and participants. A service can keep per-speaker state through that teardown, then reconcile the identities present at `reconnected`. A terminal `disconnected` ends the session.
@@ -0,0 +1,30 @@
1
+ # dTelecom RTC for Python
2
+
3
+ Join a dTelecom room from a Python process, receive remote audio as PCM16, and publish audio or room data. Supply a participant grant from your backend. Its response includes the signaling URL, token and ranked fallback URLs. [Room connections](https://docs.dtelecom.org/rooms/connect/)
4
+
5
+ ```python
6
+ from dtelecom_rtc import AudioSource, Room
7
+
8
+ async def echo(grant, finished):
9
+ source = AudioSource(sample_rate=16000)
10
+ async with Room() as room:
11
+ @room.on("track_subscribed")
12
+ async def receive(track, publication, participant):
13
+ async for frame in track.stream(sample_rate=16000):
14
+ await source.capture_frame(frame)
15
+
16
+ await room.connect(grant.ws_url, grant.token, fallback_urls=grant.fallback_urls)
17
+ await room.publish_audio("echo", source)
18
+ await finished.wait()
19
+ source.close()
20
+ ```
21
+
22
+ Use a distinct identity for each participant. Set `auto_subscribe=False` to choose remote tracks explicitly with `set_subscribed`. Register event handlers before joining to include publications already present in the room. A `data_received` handler receives payload bytes, the sender when known, the delivery kind and topic. `publish_data` accepts a string or bytes, optional topic and destination participant SIDs, and reliable or lossy delivery.
23
+
24
+ The SDK tries the issuer's ranked endpoints with the same grant after a transport failure. When extending a grant through Cloud, call `room.update_connection_token(token, fallback_urls)` so the room uses the refreshed credentials after a reconnect. Use `disconnect()` or exit the async context to leave.
25
+
26
+ Configure SDK log levels using Python's standard `logging.getLogger("dtelecom_rtc").setLevel(...)`. Use `AudioFrame.duration`, `samples_per_channel`, and the `resample`, `downsample` and `upsample` helpers for standalone PCM. `create_text_message`, `encode_data_packet` and `decode_data_packet` expose the fork's room-data format. The protocol message models and enums are exported from `dtelecom_rtc.models`.
27
+
28
+ For a live interoperability check, install Playwright and use the ESM bundle of `@dtelecom/livekit-client@1.13.0`. Set `DTELECOM_API_KEY`, `DTELECOM_API_SECRET`, `DTELECOM_CLOUD_URL` and `DTELECOM_BROWSER_MODULE`, then run `python tests/integration/browser_call.py`. The script creates a disposable room and uses synthetic audio. Add `--recovery` to test a grant with three ranked nodes and reconnect the Python publisher. `CHROME_EXECUTABLE` selects a local browser when needed.
29
+
30
+ On transport loss, `room.state` becomes `"reconnecting"` and the room emits `reconnecting` before releasing remote tracks and participants. A service can keep per-speaker state through that teardown, then reconcile the identities present at `reconnected`. A terminal `disconnected` ends the session.
@@ -0,0 +1,16 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "dtelecom-rtc"
7
+ version = "0.1.0"
8
+ description = "Server-side asyncio audio and data participant for dTelecom rooms"
9
+ requires-python = ">=3.11"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE", "NOTICE"]
12
+ readme = "README.md"
13
+ dependencies = ["dtelecom-server-sdk==0.1.0", "aiortc>=1.17,<1.18", "av>=14,<20", "websockets>=14,<17", "pyee>=13,<17"]
14
+
15
+ [tool.hatch.build.targets.wheel]
16
+ packages = ["src/dtelecom_rtc"]
@@ -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
+ ]
@@ -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)
@@ -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
+ )
@@ -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
File without changes