baresip-python 0.1.0a1__cp313-cp313-macosx_15_0_arm64.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.
Binary file
Binary file
Binary file
baresip/__init__.py ADDED
@@ -0,0 +1,98 @@
1
+ #
2
+ # Copyright (c) 2026, Daily
3
+ #
4
+ # SPDX-License-Identifier: BSD-2-Clause
5
+ #
6
+
7
+ """baresip-python: Python bindings for the baresip SIP stack.
8
+
9
+ A complete, embeddable SIP user agent for Python applications: registration,
10
+ inbound and outbound calls, programmatic PCM audio access, and DTMF — built on
11
+ baresip/libre (BSD-3) with an asyncio-native API.
12
+
13
+ The public API is exactly what ``__all__`` exports; anything else is internal
14
+ and may change without notice. See the README for the stability policy.
15
+ """
16
+
17
+ import importlib
18
+ import logging
19
+
20
+ from baresip.config import Account, Config
21
+ from baresip.errors import (
22
+ AudioNotActive,
23
+ AudioRestarted,
24
+ BaresipError,
25
+ CallBusy,
26
+ CallDeclined,
27
+ CallFailed,
28
+ CallTimeout,
29
+ CommandQueueFull,
30
+ CommandTimeout,
31
+ RegistrationError,
32
+ RuntimeDead,
33
+ StaleHandleError,
34
+ UnsupportedFeatureError,
35
+ )
36
+ from baresip.events import Event, StackEvent
37
+ from baresip.stats import CallStats
38
+
39
+ # Library convention: log into the "baresip" hierarchy, emit nothing unless
40
+ # the application configures handlers.
41
+ logging.getLogger("baresip").addHandler(logging.NullHandler())
42
+
43
+ __version__ = "0.1.0a1"
44
+
45
+ # Names that pull in the native extension are resolved lazily (PEP 562), so
46
+ # that `import baresip` — and with it the version lookup done by build
47
+ # tooling — works before the extension is compiled.
48
+ _NATIVE_BACKED = {
49
+ "AudioInfo": "baresip.audio",
50
+ "AudioStats": "baresip.audio",
51
+ "AudioWarning": "baresip.audio",
52
+ "Call": "baresip.call",
53
+ "CallAudio": "baresip.audio",
54
+ "CallState": "baresip.call",
55
+ "DigitEvent": "baresip.call",
56
+ "Runtime": "baresip.runtime",
57
+ "UserAgent": "baresip.ua",
58
+ }
59
+
60
+
61
+ def __getattr__(name: str):
62
+ module_name = _NATIVE_BACKED.get(name)
63
+ if module_name is None:
64
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
65
+ return getattr(importlib.import_module(module_name), name)
66
+
67
+
68
+ # The public-API definition. Names are added here — and only here — as their
69
+ # implementations land.
70
+ __all__: list[str] = [
71
+ "Account",
72
+ "AudioInfo",
73
+ "AudioNotActive",
74
+ "AudioRestarted",
75
+ "AudioStats",
76
+ "AudioWarning",
77
+ "BaresipError",
78
+ "Call",
79
+ "CallAudio",
80
+ "CallBusy",
81
+ "CallDeclined",
82
+ "CallFailed",
83
+ "CallState",
84
+ "CallStats",
85
+ "CallTimeout",
86
+ "CommandQueueFull",
87
+ "CommandTimeout",
88
+ "Config",
89
+ "DigitEvent",
90
+ "Event",
91
+ "RegistrationError",
92
+ "Runtime",
93
+ "RuntimeDead",
94
+ "StackEvent",
95
+ "StaleHandleError",
96
+ "UnsupportedFeatureError",
97
+ "UserAgent",
98
+ ]
baresip/_events.py ADDED
@@ -0,0 +1,52 @@
1
+ #
2
+ # Copyright (c) 2026, Daily
3
+ #
4
+ # SPDX-License-Identifier: BSD-2-Clause
5
+ #
6
+
7
+ """The single registration point for the native event callback.
8
+
9
+ cffi allows exactly one Python function per ``extern "Python"`` name — a
10
+ second ``@ffi.def_extern()`` for the same name silently replaces the first.
11
+ To keep that from ever biting, ``bp_event_h`` is registered here and nowhere
12
+ else; consumers plug in through :func:`set_sink`.
13
+
14
+ The callback runs on the re thread. It must never raise into C and must not
15
+ keep references to the C string, so the payload is copied to ``bytes`` before
16
+ the sink sees it.
17
+ """
18
+
19
+ import logging
20
+
21
+ from baresip._native import ffi, lib # noqa: F401 (lib re-exported for consumers)
22
+
23
+ logger = logging.getLogger("baresip.events")
24
+
25
+ # Read by bp_event_h on the re thread, written by set_sink on any thread.
26
+ # A single attribute load/store is atomic under the GIL — which the cffi
27
+ # trampoline must hold before this module's code runs at all — so no lock
28
+ # is needed (revisit for free-threaded builds).
29
+ _sink = None
30
+
31
+
32
+ def set_sink(sink):
33
+ """Install ``sink(ev, handle, payload: bytes | None)`` as the event
34
+ consumer; pass None to detach. Returns the previous sink."""
35
+ global _sink
36
+ previous = _sink
37
+ _sink = sink
38
+ return previous
39
+
40
+
41
+ @ffi.def_extern()
42
+ def bp_event_h(ev, handle, json):
43
+ sink = _sink
44
+ payload = ffi.string(json) if json != ffi.NULL else None
45
+ if sink is None:
46
+ logger.debug("native event %d dropped: no sink attached", ev)
47
+ return
48
+ try:
49
+ sink(ev, handle, payload)
50
+ except Exception:
51
+ # Raising into the C caller would be undefined behavior.
52
+ logger.exception("event sink raised; event %d dropped", ev)
Binary file
baresip/audio.py ADDED
@@ -0,0 +1,270 @@
1
+ #
2
+ # Copyright (c) 2026, Daily
3
+ #
4
+ # SPDX-License-Identifier: BSD-2-Clause
5
+ #
6
+
7
+ """Programmatic PCM: read and write a call's audio as plain bytes.
8
+
9
+ Every :class:`~baresip.call.Call` exposes a :class:`CallAudio` at
10
+ ``call.audio``. Receive audio — the decoded PCM the far end is sending —
11
+ is always tapped and readable, whatever audio driver the configuration
12
+ selected. Transmit audio comes from Python only when the configuration
13
+ selects ``audio_source aumem`` (the default ``Config``); under any other
14
+ source, :meth:`CallAudio.write` accepts nothing.
15
+
16
+ PCM is signed 16-bit interleaved, native byte order. Rates and channel
17
+ counts are whatever the call negotiated — :meth:`CallAudio.info` reports
18
+ them per direction. The buffers never block: a read returns what is
19
+ there, a write queues what fits. A reader that falls more than half a
20
+ buffer behind is skipped forward — oldest audio dropped — so live audio
21
+ stays live.
22
+
23
+ Health is watched for you: the stack samples every call's counters once
24
+ per second and reports damage done by the application's pacing — writing
25
+ too slowly mid-utterance, or reading too slowly — as at most one warning
26
+ per direction per second, delivered to
27
+ :meth:`Call.on_audio_warning <baresip.call.Call.on_audio_warning>`
28
+ callbacks as :class:`AudioWarning`. The raw counters behind the warnings
29
+ are always available from :meth:`CallAudio.stats`. A direction the
30
+ application never uses is a choice, not a fault: writing nothing
31
+ transmits silence without warning, and receive warnings begin only once
32
+ the application has read from the call at all — audio arriving for a
33
+ reader that never existed is dropped quietly (and counted).
34
+ """
35
+
36
+ import errno
37
+ from dataclasses import dataclass
38
+
39
+ from baresip._native import ffi, lib
40
+ from baresip.errors import AudioNotActive, AudioRestarted
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class AudioInfo:
45
+ """A snapshot of one call's audio streams.
46
+
47
+ Parameters:
48
+ tx_ready: Python may feed the call (the aumem source is up).
49
+ rx_ready: Decoded receive audio is being tapped.
50
+ tx_sample_rate: Transmit rate in Hz (0 until ``tx_ready``).
51
+ tx_channels: Transmit channel count.
52
+ tx_ptime_ms: The transmit packet time — a natural write pace.
53
+ rx_sample_rate: Receive rate in Hz (0 until ``rx_ready``).
54
+ rx_channels: Receive channel count.
55
+ tx_buffered: Bytes written but not yet transmitted.
56
+ rx_buffered: Bytes received but not yet read.
57
+ tx_capacity: Transmit buffer size in bytes.
58
+ rx_capacity: Receive buffer size in bytes.
59
+ """
60
+
61
+ tx_ready: bool
62
+ rx_ready: bool
63
+ tx_sample_rate: int
64
+ tx_channels: int
65
+ tx_ptime_ms: int
66
+ rx_sample_rate: int
67
+ rx_channels: int
68
+ tx_buffered: int
69
+ rx_buffered: int
70
+ tx_capacity: int
71
+ rx_capacity: int
72
+
73
+
74
+ @dataclass(frozen=True)
75
+ class AudioStats:
76
+ """Health counters for one call's audio, per direction.
77
+
78
+ Counters are cumulative for the current streams; a renegotiation that
79
+ replaces a direction resets its counters, on the same lifetime the
80
+ epoch tracks.
81
+
82
+ Parameters:
83
+ tx_silence_frames: Transmit frames sent as pure silence because
84
+ nothing was buffered. Idle, not an error — this grows
85
+ whenever the application has nothing to say.
86
+ tx_starved_frames: Transmit frames padded mid-frame: audio was
87
+ flowing and ran dry. The signature of a writer that cannot
88
+ keep pace; this is what transmit warnings key off.
89
+ tx_rejected_bytes: Bytes :meth:`CallAudio.write` could not take
90
+ (buffer full) — the same shortfall its return value reports.
91
+ tx_buffered: Bytes written but not yet transmitted.
92
+ tx_high_water: Deepest transmit fill seen so far.
93
+ rx_dropped_bytes: Received bytes discarded because the buffer was
94
+ full — nothing is reading.
95
+ rx_discarded_bytes: Received bytes skipped by the catch-up that
96
+ keeps a slow reader live — something is reading, too slowly.
97
+ rx_buffered: Bytes received but not yet read.
98
+ rx_high_water: Deepest receive fill seen so far.
99
+ """
100
+
101
+ tx_silence_frames: int
102
+ tx_starved_frames: int
103
+ tx_rejected_bytes: int
104
+ tx_buffered: int
105
+ tx_high_water: int
106
+ rx_dropped_bytes: int
107
+ rx_discarded_bytes: int
108
+ rx_buffered: int
109
+ rx_high_water: int
110
+
111
+
112
+ @dataclass(frozen=True)
113
+ class AudioWarning:
114
+ """One audio health warning, as delivered to ``on_audio_warning``.
115
+
116
+ Parameters:
117
+ direction: ``"tx"`` — the application is not feeding audio fast
118
+ enough — or ``"rx"`` — it is not reading fast enough.
119
+ message: The full human-readable description, including how much
120
+ audio was affected in the sampled second.
121
+ """
122
+
123
+ direction: str
124
+ message: str
125
+
126
+
127
+ class CallAudio:
128
+ """One call's PCM streams. Obtained via ``call.audio``, never built.
129
+
130
+ Safe to use from any thread — including threads that never touch
131
+ the event loop — with at most one reader and one writer at a time.
132
+ Operations raise :class:`~baresip.errors.AudioNotActive` while the
133
+ call has no media (or after it closed), and
134
+ :class:`~baresip.errors.AudioRestarted` once mid-call renegotiation
135
+ has replaced the streams; after the latter, the next operation binds
136
+ to the new streams automatically.
137
+ """
138
+
139
+ def __init__(self, call_handle: int):
140
+ """Bind to a call's audio slot. Library-internal.
141
+
142
+ Args:
143
+ call_handle: The native handle of the owning call.
144
+ """
145
+ self._handle = call_handle
146
+ # The native slot stamps its streams with an epoch that advances
147
+ # whenever they are torn down and replaced (mid-call
148
+ # renegotiation). We remember the epoch we bound to and pass it
149
+ # with every read and write; the native side refuses a mismatch
150
+ # with ESTALE, which _checked() turns into AudioRestarted. None
151
+ # means unbound — the next operation probes the slot and binds
152
+ # to whatever streams are current.
153
+ self._bound_epoch: int | None = None
154
+
155
+ def __repr__(self) -> str:
156
+ return f"<CallAudio call={self._handle:#x}>"
157
+
158
+ def info(self) -> AudioInfo:
159
+ """Probe the streams: readiness, formats, and buffer depths.
160
+
161
+ Raises:
162
+ AudioNotActive: the call has no audio (yet, or anymore).
163
+ """
164
+ info = ffi.new("struct bp_audio_info *")
165
+ if lib.bp_audio_probe(self._handle, info) != 0:
166
+ self._bound_epoch = None
167
+ raise AudioNotActive("no audio is active on this call")
168
+ self._bound_epoch = info.epoch
169
+ return AudioInfo(
170
+ tx_ready=bool(info.tx_ready),
171
+ rx_ready=bool(info.rx_ready),
172
+ tx_sample_rate=info.tx_srate,
173
+ tx_channels=info.tx_ch,
174
+ tx_ptime_ms=info.tx_ptime,
175
+ rx_sample_rate=info.rx_srate,
176
+ rx_channels=info.rx_ch,
177
+ tx_buffered=info.tx_fill,
178
+ rx_buffered=info.rx_fill,
179
+ tx_capacity=info.tx_capacity,
180
+ rx_capacity=info.rx_capacity,
181
+ )
182
+
183
+ def stats(self) -> AudioStats:
184
+ """Snapshot the health counters; see :class:`AudioStats`.
185
+
186
+ Raises:
187
+ AudioNotActive: the call has no audio (yet, or anymore).
188
+ """
189
+ st = ffi.new("struct bp_audio_stats *")
190
+ if lib.bp_audio_stats_get(self._handle, st) != 0:
191
+ self._bound_epoch = None
192
+ raise AudioNotActive("no audio is active on this call")
193
+ self._bound_epoch = st.epoch
194
+ return AudioStats(
195
+ tx_silence_frames=st.tx_silence_frames,
196
+ tx_starved_frames=st.tx_starved_frames,
197
+ tx_rejected_bytes=st.tx_rejected,
198
+ tx_buffered=st.tx_fill,
199
+ tx_high_water=st.tx_high_water,
200
+ rx_dropped_bytes=st.rx_dropped,
201
+ rx_discarded_bytes=st.rx_discarded,
202
+ rx_buffered=st.rx_fill,
203
+ rx_high_water=st.rx_high_water,
204
+ )
205
+
206
+ def write(self, pcm) -> int:
207
+ """Queue PCM for transmission; returns the bytes accepted.
208
+
209
+ Never blocks: what does not fit in the buffer is not taken, and
210
+ the transmit clock sends silence whenever the buffer runs dry —
211
+ feed it steadily rather than far ahead.
212
+
213
+ Args:
214
+ pcm: A bytes-like object of 16-bit interleaved samples.
215
+
216
+ Raises:
217
+ AudioNotActive: the call has no audio (yet, or anymore).
218
+ AudioRestarted: renegotiation replaced the streams.
219
+ """
220
+ if not pcm:
221
+ return 0
222
+ epoch = self._ensure_bound()
223
+ n = lib.bp_audio_write(self._handle, epoch, ffi.from_buffer("uint8_t[]", pcm), len(pcm))
224
+ return self._checked(n)
225
+
226
+ def read(self, max_bytes: int) -> bytes:
227
+ """Take up to ``max_bytes`` of received PCM; b"" when none yet.
228
+
229
+ Never blocks. An empty result simply means nothing has arrived
230
+ since the last read — sleep a frame and try again.
231
+
232
+ Args:
233
+ max_bytes: Upper bound on the returned length.
234
+
235
+ Raises:
236
+ AudioNotActive: the call has no audio (yet, or anymore).
237
+ AudioRestarted: renegotiation replaced the streams.
238
+ """
239
+ if max_bytes <= 0:
240
+ raise ValueError("max_bytes must be positive")
241
+ epoch = self._ensure_bound()
242
+ buf = ffi.new("uint8_t[]", max_bytes)
243
+ n = self._checked(lib.bp_audio_read(self._handle, epoch, buf, max_bytes))
244
+ return bytes(ffi.buffer(buf, n))
245
+
246
+ def _ensure_bound(self) -> int:
247
+ """The epoch to hand to a native read or write.
248
+
249
+ Probes first when unbound — a fresh object, or the previous
250
+ operation failed — so every operation speaks to the current
251
+ streams, or raises AudioNotActive from the probe itself.
252
+ """
253
+ if self._bound_epoch is None:
254
+ self.info()
255
+ return self._bound_epoch
256
+
257
+ def _checked(self, n: int) -> int:
258
+ """Pass a native byte count through, unbinding on failure.
259
+
260
+ Any failure drops the binding so the next operation re-probes.
261
+ ESTALE — the slot's epoch moved past ours because renegotiation
262
+ replaced the streams — becomes AudioRestarted; anything else
263
+ means no slot serves this call and becomes AudioNotActive.
264
+ """
265
+ if n >= 0:
266
+ return n
267
+ self._bound_epoch = None
268
+ if -n == errno.ESTALE:
269
+ raise AudioRestarted("the call's audio was renegotiated; buffered data was lost")
270
+ raise AudioNotActive("no audio is active on this call")