vdm10-python 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.
metzler/sip/sdp.py ADDED
@@ -0,0 +1,89 @@
1
+ """SDP parsing and the hicore answer templates (private a= attributes)."""
2
+
3
+ import re
4
+ from typing import cast
5
+
6
+
7
+ def parse_sdp(body):
8
+ """-> {ip, media:[{type, port, formats}]}"""
9
+ ip = None
10
+ media = []
11
+ cur = None
12
+ for line in body.splitlines():
13
+ line = line.strip()
14
+ if line.startswith("c=IN IP4 "):
15
+ if cur is not None:
16
+ cur["ip"] = line.split()[-1]
17
+ else:
18
+ ip = line.split()[-1]
19
+ elif line.startswith("m="):
20
+ p = line[2:].split()
21
+ cur = {
22
+ "type": p[0],
23
+ "port": int(p[1]),
24
+ "proto": p[2] if len(p) > 2 else "RTP/AVP",
25
+ "formats": p[3:],
26
+ "ip": ip,
27
+ }
28
+ media.append(cur)
29
+ elif cur is not None and line.startswith("a="):
30
+ cast(list, cur.setdefault("attrs", [])).append(line[2:])
31
+ return {"ip": ip, "media": media}
32
+
33
+
34
+ def media_addr(sdp, mtype):
35
+ """-> (ip, port) of the first media line of `mtype`, or None"""
36
+ m = next((m for m in sdp["media"] if m["type"] == mtype), None)
37
+ return ((m["ip"] or sdp["ip"]), m["port"]) if m else None
38
+
39
+
40
+ def telephone_event_pt(sdp):
41
+ """negotiated telephone-event PT from an answer's audio m-line, or None.
42
+ The answer may remap the offered 101 - and may drop the codec entirely
43
+ (peer then sends DTMF in-band or as SIP INFO)."""
44
+ m = next((m for m in sdp["media"] if m["type"] == "audio"), None)
45
+ if not m:
46
+ return None
47
+ for a in m.get("attrs", []):
48
+ mm = re.match(r"rtpmap:(\d+)\s+telephone-event", a)
49
+ if mm:
50
+ return int(mm.group(1))
51
+ return None
52
+
53
+
54
+ def sdp_answer_firmware(num, ip, audio_port, video_port):
55
+ """the exact template hicore emits (FUN_000dd18c)"""
56
+ return (
57
+ f"v=0\r\no={num} 0 0 IN IP4 {ip}\r\ns=Talk session\r\nc=IN IP4 {ip}\r\nt=0 0\r\n"
58
+ "a=doorFloor:0\r\na=responseType:0\r\na=doorType:0\r\n"
59
+ "a=isSpecialType:0\r\na=isConfirm:0\r\n"
60
+ f"m=audio {audio_port} RTP/AVP 0 2 101\r\na=rtpmap:0 PCMU/8000\r\n"
61
+ "a=rtpmap:2 G726-32/8000\r\na=rtpmap:101 telephone-event/8000\r\n"
62
+ "a=fmtp:101 0-16\r\na=sendrecv\r\n"
63
+ f"m=video {video_port} RTP/AVP 96\r\na=rtpmap:96 H264/90000\r\n"
64
+ "a=fmtp:96 packetization-mode=1;profile-level-id=4D001E\r\na=sendrecv\r\n"
65
+ )
66
+
67
+
68
+ def sdp_answer_talkback(serial, ip, audio_port=None, video_port=None, opts=None):
69
+ """the real 200 OK SDP a hicore station emits when answering an EXTENSION call
70
+ (sess+0x7c == 3 -> FUN_000dd18c header-only path, sip_client.c ~5968/6160).
71
+ Header-only SDP + the same private session attrs as the offer:
72
+ doorFloor:0 responseType:<wait outcome> doorType:0 isSpecialType:<2|0> isConfirm:0
73
+ responseType = FUN_000dc2dc wait outcome: 0 = answered (200); the caller copies
74
+ attr#1 -> sess+0x78 and attr#3 -> sess+0xcc and posts {+0x78,+0x7c,+0xcc} to the
75
+ GUI (msg 0x80f; byte0==4 routes to the videocall window, else the initiate
76
+ window).
77
+
78
+ isSpecialType — VERIFIED ON THE WIRE (real indoor 10000000001 @ .47, both
79
+ its offer and its 200 OK send 2): 2 = "no remote video exists" -> the
80
+ caller's videocallProc skips the remote-video rect -> audio-call UI.
81
+ 0 -> video rect drawn -> "video session" UI. Real indoor stations claim
82
+ the special-model flag (isSpecialModel -> product-code band, FUN_00064da8).
83
+ Default 2 to match; INDOOR_SPECIAL_TYPE overrides for A/B tests."""
84
+ special = getattr(opts, "special_type", "2")
85
+ return (
86
+ f"v=0\r\no={serial} 0 0 IN IP4 {ip}\r\ns=Talk session\r\nc=IN IP4 {ip}\r\nt=0 0\r\n"
87
+ "a=doorFloor:0\r\na=responseType:0\r\na=doorType:0\r\n"
88
+ f"a=isSpecialType:{special}\r\na=isConfirm:0\r\n"
89
+ )
@@ -0,0 +1,6 @@
1
+ """The simulated indoor station (see station.station.IndoorStation)."""
2
+
3
+ from metzler.station.call import Call
4
+ from metzler.station.station import IndoorStation
5
+
6
+ __all__ = ["Call", "IndoorStation"]
@@ -0,0 +1,284 @@
1
+ """Incoming intercom/door call -> SIP provider bridge."""
2
+
3
+ import logging
4
+ import re
5
+ import threading
6
+
7
+ from metzler.media.intercom import SipIntercomMedia
8
+ from metzler.media.rtp import RtpRelay
9
+ from metzler.provider import SipProvider
10
+ from metzler.sip.message import userpart
11
+ from metzler.sip.sdp import (
12
+ media_addr,
13
+ parse_sdp,
14
+ sdp_answer_firmware,
15
+ sdp_answer_talkback,
16
+ telephone_event_pt,
17
+ )
18
+ from metzler.station.call import Call
19
+
20
+ log = logging.getLogger("indoor")
21
+
22
+
23
+ class ProviderBridgeMixin:
24
+ """Incoming intercom/door call -> SIP provider bridge."""
25
+
26
+ def on_invite(self, pkt, addr):
27
+ sdp = parse_sdp(pkt.body)
28
+ log.info(
29
+ "INVITE from %s: From=%s Subject=%r sdp-ip=%s media-lines=%d",
30
+ addr,
31
+ pkt.get("From"),
32
+ pkt.get("Subject"),
33
+ sdp["ip"],
34
+ len(sdp["media"]),
35
+ )
36
+ if self._retransmitted_invite(pkt, addr):
37
+ return
38
+ if self._provider_loop_guard(pkt, addr):
39
+ return
40
+ self._log_incoming(pkt, addr)
41
+ self.send(self.in_dialog_response(pkt, "100 Trying"), addr)
42
+
43
+ call = Call(self, pkt, addr)
44
+ self.calls[call.id] = call
45
+
46
+ ringing = self.in_dialog_response(pkt, "180 Ringing", extra_to_tag=call.to_tag)
47
+ ringing.set("Allow-Events", "talk, hold")
48
+ self.reply(call, ringing)
49
+
50
+ remote_sdp = parse_sdp(pkt.body)
51
+ door_a = next((m for m in remote_sdp["media"] if m["type"] == "audio"), None)
52
+ door_v = next((m for m in remote_sdp["media"] if m["type"] == "video"), None)
53
+ if self._park_call(call, pkt, door_a, door_v, remote_sdp):
54
+ return
55
+ self._attach_bridge_media(call, remote_sdp, door_a, door_v)
56
+ log.info("call classified: %s", "door (video to provider)" if call.door else "intercom (audio only)")
57
+ if self.provider:
58
+ call.trunk = self.provider # prov_* describes the provider leg until the fritz leg wins
59
+ self.provider.invite(call)
60
+ if self.fritz and self.o.fritz_target:
61
+ self.fritz.invite(call) # --fritz: the fritzfon races every bridged call
62
+
63
+ def _log_incoming(self, pkt, addr):
64
+ """mode banner for an accepted INVITE: headset / ha_mode / provider bridging"""
65
+ if self.local_mode:
66
+ log.info("incoming call (headset mode, auto-answer=%s)", self.o.auto_answer)
67
+ elif getattr(self.o, "ha_mode", False) and not (self.provider or self.fritz):
68
+ log.info("incoming call (ha_mode - parking for explicit HA answer)")
69
+ elif getattr(self.o, "ha_mode", False):
70
+ log.info("incoming call (ha_mode + trunk race - first answer wins)")
71
+ else:
72
+ log.info(
73
+ "incoming call INVITE from %s — bridging via %s:%d to %s", addr, *self.provider.proxy, self.o.sip_target
74
+ )
75
+
76
+ def _park_call(self, call, pkt, door_a, door_v, remote_sdp):
77
+ """non-trunk paths: ha_mode parks the call ringing for an explicit
78
+ answer_call/hangup_call (no provider leg, no local answer - note that
79
+ auto_answer="off" alone only gates answer_locally inside local_mode,
80
+ so without this branch the no-provider path would hit provider.invite);
81
+ local_mode hands the call to answer_locally on a thread.
82
+ Returns True when the call was handled and must NOT be bridged."""
83
+ if getattr(self.o, "ha_mode", False):
84
+ call.door = bool(door_a) or self._is_door_call(pkt)
85
+ call.kind = "door" if door_a else "intercom"
86
+ self._fire_event("ring", call)
87
+ if not (self.provider or (self.fritz and self.o.fritz_target)):
88
+ log.info(
89
+ "call %s parked ringing (ha_mode, %s) - awaiting explicit answer",
90
+ call.id,
91
+ "door" if call.door else "intercom",
92
+ )
93
+ return True
94
+ # ha_mode + trunk(s): park for HA *and* ring the provider/fritz
95
+ # legs - whichever side 200-OKs first wins, the loser is CANCELed
96
+ # (provider win -> provider_answered; HA win -> answer_call +
97
+ # _end_provider_leg). Fall through to the bridge path.
98
+ log.info(
99
+ "call %s parked ringing + racing trunk legs (ha_mode, %s)",
100
+ call.id,
101
+ "door" if call.door else "intercom",
102
+ )
103
+ return False
104
+ if self.local_mode:
105
+ threading.Thread(target=self.answer_locally, args=(call, door_a, door_v, remote_sdp), daemon=True).start()
106
+ return True
107
+ return False
108
+
109
+ def _provider_loop_guard(self, pkt, addr):
110
+ """True if this INVITE must not be bridged to the provider (handled here)"""
111
+ if not (self.provider or self.fritz):
112
+ return False
113
+ # our own provider call forked back at us (the proxy rings every contact
114
+ # on the account, including ours). Silently ignore it: a non-responding
115
+ # branch keeps the call in "trying" state, giving pushed mobile devices
116
+ # time to wake and register (a 486 would end the call as busy instantly)
117
+ if self.provider and self.provider.owns(pkt.get("Call-ID")):
118
+ log.debug("ignoring our own provider fork (Call-ID %s)", pkt.get("Call-ID"))
119
+ return True
120
+ # same for a racing leg to the fritzfon: we registered as its SIP
121
+ # account, so the box forks our own INVITE right back at us
122
+ if self.fritz and self.fritz.owns(pkt.get("Call-ID")):
123
+ log.debug("ignoring our own fritz fork (Call-ID %s)", pkt.get("Call-ID"))
124
+ return True
125
+ # an inbound call from either SIP side (someone dialing the provider
126
+ # account, or a fritz phone calling our extension) is bridged to
127
+ # --inbound-target or declined (486 inside) - the trunk object is
128
+ # remembered on the call so its SDP answers use that leg's identity
129
+ for trunk in (self.provider, self.fritz):
130
+ if trunk and trunk.is_provider_addr(addr):
131
+ self.inbound_provider_call(pkt, addr, trunk)
132
+ return True
133
+ return False
134
+
135
+ def _retransmitted_invite(self, pkt, addr):
136
+ """True if this INVITE is a UDP retransmit of a transaction we already
137
+ serve - resend the last response instead of leaking a second Call
138
+ (and its media threads) on top of the first"""
139
+ call = self.calls.get(pkt.get("Call-ID"))
140
+ if call:
141
+ self.send(call.last_resp or self.in_dialog_response(pkt, "100 Trying"), addr)
142
+ return True
143
+ resp = self.ended_resp(pkt.get("Call-ID"))
144
+ if resp is not None:
145
+ self.send(resp, addr)
146
+ return True
147
+ return False
148
+
149
+ def _attach_bridge_media(self, call, remote_sdp, door_a, door_v):
150
+ """door calls relay RTP on both legs; intercom calls pull the caller's
151
+ RTSP PCMU and expose the SIP peer's audio on our :554. An outdoor
152
+ caller (door call over the header-only dialect) additionally gets a
153
+ video leg forwarding the door's pulled H264 to the provider."""
154
+ call.door = bool(door_a) or self._is_door_call(call.invite)
155
+ if door_a:
156
+ call.kind = "door"
157
+ call.audio = RtpRelay()
158
+ call.video = RtpRelay()
159
+ call.audio.start()
160
+ call.video.start()
161
+ call.audio.set_peer(a=(door_a["ip"] or remote_sdp["ip"], door_a["port"]))
162
+ if door_v:
163
+ call.video.set_peer(a=(door_v["ip"] or remote_sdp["ip"], door_v["port"]))
164
+ else:
165
+ call.kind = "intercom"
166
+ call.media = SipIntercomMedia(self.o, self.rtsp, remote_sdp["ip"] or call.addr[0], video=call.door)
167
+ call.media.on_dtmf = lambda d, c=call: self._dtmf_digit(c, d)
168
+
169
+ @staticmethod
170
+ def _caller_class(pkt):
171
+ """caller number class, firmware FUN_000f9ce0: '1000000000N' -> 3
172
+ (room/extension); else sscanf('%01d%03d%02d%03d%02d') -> f3!=0 && f4==0
173
+ -> 1 (door/outdoor station). Other classes collapse to 0."""
174
+ num = userpart(pkt.get("From") or "")
175
+ if num.startswith("1000000000"):
176
+ return 3
177
+ if len(num) == 11 and num.isdigit() and int(num[4:6]) != 0 and int(num[6:9]) == 0:
178
+ return 1
179
+ return 0
180
+
181
+ @classmethod
182
+ def _is_door_call(cls, pkt):
183
+ """call originated by an outdoor station. Firmware signals, any of:
184
+ caller number class 1; Subject 'call to app' (vs 'call to extension');
185
+ a=doorType:>0 in the header-only offer. A class-3 caller (room/
186
+ extension unit) is NEVER a door - the main indoor stamps doorType:1
187
+ on extension calls too, and those must stay audio-only."""
188
+ cls_ = cls._caller_class(pkt)
189
+ if cls_ == 3:
190
+ return False
191
+ if cls_ == 1:
192
+ return True
193
+ if "call to app" in (pkt.get("Subject") or "").lower():
194
+ return True
195
+ m = re.search(r"a=doorType:(\d+)", pkt.body)
196
+ return bool(m and int(m.group(1)))
197
+
198
+ def provider_answered(self, call, resp):
199
+ """provider leg got 200 OK: answer the indoor caller in its own dialect,
200
+ ACK the provider, then connect the media (already running if a 18x
201
+ early-media response primed it)"""
202
+ resp_sdp = parse_sdp(resp.body)
203
+ prov_a = media_addr(resp_sdp, "audio")
204
+ ok = self.in_dialog_response(call.invite, "200 OK", ctype="application/sdp", extra_to_tag=call.to_tag)
205
+ ok.body = self._indoor_answer(call, resp_sdp, prov_a)
206
+ self.reply(call, ok)
207
+ (call.trunk or self.provider).ack(call, resp) # the winning leg's trunk
208
+ call.prov_established = True
209
+ call.state = "established"
210
+ self._fire_event("answered", call)
211
+ if not call.provider_media:
212
+ self._bind_srtp(call, resp_sdp)
213
+ self._connect_media(call, prov_a, media_addr(resp_sdp, "video"))
214
+
215
+ def early_media(self, call, resp):
216
+ """a 18x response carrying SDP (183 Session Progress or 180+SDP):
217
+ the callee's media address is known — latch it and start streaming.
218
+ Door video reaches the app while it still rings; the indoor leg keeps
219
+ ringing until the provider's 200 OK."""
220
+ if call.provider_media:
221
+ return
222
+ resp_sdp = parse_sdp(resp.body)
223
+ prov_a, prov_v = media_addr(resp_sdp, "audio"), media_addr(resp_sdp, "video")
224
+ log.info("early media on provider leg (%s): audio %s, video %s", resp.status_line, prov_a, prov_v)
225
+ self._bind_srtp(call, resp_sdp)
226
+ self._connect_media(call, prov_a, prov_v)
227
+
228
+ def _bind_srtp(self, call, resp_sdp):
229
+ if call.kind == "intercom":
230
+ streams = [("audio", call.media)]
231
+ if call.media.video:
232
+ streams.append(("video", call.media.video))
233
+ else:
234
+ streams = [("audio", call.audio), ("video", call.video)]
235
+ modes = {
236
+ kind: SipProvider.bind_srtp(
237
+ media, next((m for m in resp_sdp["media"] if m["type"] == kind and m["port"]), None)
238
+ )
239
+ for kind, media in streams
240
+ }
241
+ log.info("provider media protection: %s", ", ".join(f"{k}={v}" for k, v in modes.items()))
242
+ if call.kind == "intercom":
243
+ pt = telephone_event_pt(resp_sdp)
244
+ call.media.dtmf_pt = pt
245
+ log.info("provider telephone-event: %s", f"PT {pt}" if pt is not None else "not negotiated")
246
+
247
+ def _indoor_answer(self, call, resp_sdp, prov_a):
248
+ """the caller's 200 OK body in its own dialect: header-only with the
249
+ private attrs for intercom calls, firmware-style m= lines for door calls"""
250
+ if call.kind == "intercom":
251
+ return sdp_answer_talkback(self.o.serial, self.o.local_ip, opts=self.o)
252
+ return sdp_answer_firmware(self.o.username, self.o.local_ip, call.audio.port_a, call.video.port_a)
253
+
254
+ def _connect_media(self, call, prov_a, prov_v):
255
+ """latch the provider media peers and start the media threads"""
256
+ call.provider_media = True
257
+ if call.kind == "intercom":
258
+ # SipIntercomMedia feeds provider audio to rtsp.mic; the caller
259
+ # pulls :554 and hears the SIP peer
260
+ if prov_a:
261
+ call.media.set_provider(prov_a)
262
+ if call.media.video:
263
+ call.media.video.peer = prov_v # None kills the leg (fritz win)
264
+ call.media.start()
265
+ log.info(
266
+ "%s media streaming (rtsp :%d, peer audio %s video %s)",
267
+ "door" if call.door else "intercom",
268
+ self.o.rtsp_port,
269
+ prov_a,
270
+ prov_v,
271
+ )
272
+ else:
273
+ if prov_a:
274
+ call.audio.set_peer(b=prov_a)
275
+ if prov_v:
276
+ call.video.set_peer(b=prov_v)
277
+ log.info(
278
+ "call established: door <-> SIP %s (audio %d<->%s, video %d<->%s)",
279
+ self.o.sip_domain,
280
+ call.audio.port_a,
281
+ call.audio.peer_b,
282
+ call.video.port_a,
283
+ call.video.peer_b,
284
+ )
@@ -0,0 +1,52 @@
1
+ """State of one bridged call (intercom/door leg + provider leg)."""
2
+
3
+ import time
4
+
5
+ from metzler.sip.message import call_id, tag
6
+
7
+
8
+ class Call:
9
+ def __init__(self, station, invite, addr):
10
+ self.st = station
11
+ self.invite = invite # parsed incoming INVITE packet
12
+ self.addr = addr # door-side SIP addr
13
+ self.id = invite.get("Call-ID")
14
+ self.created = time.time() # for the janitor's ring timeout
15
+ self.to_tag = tag()
16
+ self.state = "early" # early -> bridging -> established -> ended
17
+ self.last_resp = None # last response to invite (resent on retransmit)
18
+ self.audio = self.video = None # RtpRelay pair (door calls, created lazily)
19
+ self.media = None # SipIntercomMedia (intercom calls)
20
+ self.local = None # IntercomMedia/LocalMediaBridge (local mode)
21
+ self.kind = None # "door" | "intercom"
22
+ self.door = False # caller is an outdoor station (doorbell)
23
+ self.inbound = False # SIP app -> intercom call (reversed bridge)
24
+ self.trunk = None # SIP leg this call uses/won (provider or fritz)
25
+ self.fritz_leg = None # racing door-call fritz leg dict (until it wins)
26
+ self.out_cid = None # Call-ID of our outbound intercom leg (inbound)
27
+ self.provider_media = False # provider peers latched + media streaming
28
+ self.prov_call_id = call_id()
29
+ self.prov_from = None # our From on the provider leg
30
+ self.prov_to = None # remote To (with tag) from 200 OK
31
+ self.prov_uri = None # remote Contact URI (route target)
32
+ self.prov_peer = None # provider RTP (ip, port) for audio
33
+ self.prov_auths = 0 # digest retries on the provider leg
34
+ self.prov_branch = None # Via branch of the current INVITE txn
35
+ self.prov_cseq = 0 # CSeq of the current INVITE (for ACKs)
36
+ self.prov_plain = False # True after a 488 -> re-offered without SRTP
37
+ self.prov_established = False # trunk leg got 200 OK (BYE it, not CANCEL)
38
+ self.dtmf = "" # recent trunk-leg digits (Signal=/RFC4733)
39
+ self.dtmf_ts = 0.0 # last digit time - sequences expire
40
+ self.unlock_ts = 0.0 # last unlock send (duplicate-transport guard)
41
+ self.end_reason = None # set before _close_call: cancel|bye|timeout|declined|error|shutdown
42
+
43
+ def stop(self):
44
+ self.state = "ended"
45
+ if self.audio:
46
+ self.audio.stop()
47
+ if self.video:
48
+ self.video.stop()
49
+ if self.media:
50
+ self.media.stop()
51
+ if self.local:
52
+ self.local.stop()