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/__init__.py +93 -0
- metzler/__main__.py +18 -0
- metzler/cli.py +262 -0
- metzler/config.py +42 -0
- metzler/discovery.py +525 -0
- metzler/media/__init__.py +1 -0
- metzler/media/g711.py +59 -0
- metzler/media/intercom.py +340 -0
- metzler/media/local.py +219 -0
- metzler/media/rtp.py +106 -0
- metzler/media/rtsp.py +73 -0
- metzler/media/rtsp_puller.py +128 -0
- metzler/media/rtsp_server.py +254 -0
- metzler/media/srtp.py +123 -0
- metzler/provider.py +500 -0
- metzler/py.typed +0 -0
- metzler/sip/__init__.py +1 -0
- metzler/sip/digest.py +45 -0
- metzler/sip/message.py +81 -0
- metzler/sip/sdp.py +89 -0
- metzler/station/__init__.py +6 -0
- metzler/station/bridge.py +284 -0
- metzler/station/call.py +52 -0
- metzler/station/core.py +574 -0
- metzler/station/door_unlock.py +42 -0
- metzler/station/ha_answer.py +92 -0
- metzler/station/ha_media.py +95 -0
- metzler/station/inbound.py +90 -0
- metzler/station/local_answer.py +97 -0
- metzler/station/outbound.py +137 -0
- metzler/station/registration.py +167 -0
- metzler/station/station.py +33 -0
- metzler/station/teardown.py +87 -0
- vdm10_python-0.1.0.dist-info/METADATA +86 -0
- vdm10_python-0.1.0.dist-info/RECORD +38 -0
- vdm10_python-0.1.0.dist-info/WHEEL +4 -0
- vdm10_python-0.1.0.dist-info/entry_points.txt +4 -0
- vdm10_python-0.1.0.dist-info/licenses/LICENSE +674 -0
metzler/media/rtsp.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""The intercom media channel: hikvision-style RTSP.
|
|
2
|
+
|
|
3
|
+
Indoor-to-indoor calls carry no RTP in SIP; after the ACK each station pulls the
|
|
4
|
+
other's rtsp://<ip>:554/ch1/main/av_stream. RtspServer is our side of that pull,
|
|
5
|
+
RtspPuller pulls the caller's stream.
|
|
6
|
+
|
|
7
|
+
This module holds the wire format shared by both sides: the DESCRIBE SDP a real
|
|
8
|
+
indoor unit serves and the request/reply framing helpers."""
|
|
9
|
+
|
|
10
|
+
#
|
|
11
|
+
# Intercom calls don't use talkback RTP: after ACK each station pulls the other's
|
|
12
|
+
# rtsp://<ip>/ch1/main/av_stream (Basic auth admin:<extension password>), which
|
|
13
|
+
# carries H264 video (trackID=1) + PCMU mic audio (trackID=2), interleaved TCP.
|
|
14
|
+
_RTSP_SDP_HEAD = (
|
|
15
|
+
"v=0\r\no=- 0 0 IN IP4 0.0.0.0\r\ns=HIK Media Server\r\n"
|
|
16
|
+
"i=HIK Media Server Session Description : standard\r\ne=NONE\r\n"
|
|
17
|
+
"c=IN IP4 0.0.0.0\r\nt=0 0\r\na=control:*\r\na=range:npt=0.0-\r\n"
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
_RTSP_SDP_VIDEO = (
|
|
22
|
+
"m=video 0 RTP/AVP 96\r\ni=Video Media\r\na=rtpmap:96 H264/90000\r\n"
|
|
23
|
+
"a=fmtp:96 profile-level-id=4D0014;packetization-mode=0\r\na=control:trackID=1\r\n"
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
_RTSP_SDP_AUDIO = "m=audio 0 RTP/AVP 0\r\ni=Audio Media\r\na=rtpmap:0 PCMU/8000\r\na=control:trackID=2\r\n"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
_RTSP_SDP_TAIL = (
|
|
31
|
+
"a=Media_header:MEDIAINFO=494D4B48010100000400000110710110401F000000FA0000"
|
|
32
|
+
"00000000000000000000000000000000000000;\r\na=appversion:1.0\r\n"
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# a real indoor station's :554 always advertises BOTH tracks in DESCRIBE (the
|
|
37
|
+
# hikvision client TCP-RSTs on an audio-only SDP within ~2 ms) but then serves
|
|
38
|
+
# ONLY PCMU audio on the wire - indoor->indoor calls carry no video transport.
|
|
39
|
+
RTSP_SDP = _RTSP_SDP_HEAD + _RTSP_SDP_AUDIO + _RTSP_SDP_TAIL
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
RTSP_SDP_AV = _RTSP_SDP_HEAD + _RTSP_SDP_VIDEO + _RTSP_SDP_AUDIO + _RTSP_SDP_TAIL
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def rtsp_reply(conn, cseq, code="200 OK", extra="", body=None):
|
|
46
|
+
r = f"RTSP/1.0 {code}\r\nCSeq: {cseq}\r\n{extra}"
|
|
47
|
+
if body is not None:
|
|
48
|
+
r += f"Content-Type: application/sdp\r\nContent-Length: {len(body)}\r\n\r\n{body}"
|
|
49
|
+
else:
|
|
50
|
+
r += "\r\n"
|
|
51
|
+
conn.sendall(r.encode())
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def read_rtsp_request(conn, buf):
|
|
55
|
+
"""return (request_bytes, rest) skipping $-interleaved RTCP; None on close"""
|
|
56
|
+
while b"\r\n\r\n" not in buf:
|
|
57
|
+
d = conn.recv(8192)
|
|
58
|
+
if not d:
|
|
59
|
+
return None, b""
|
|
60
|
+
buf += d
|
|
61
|
+
i = buf.find(b"\r\n\r\n") + 4
|
|
62
|
+
req, buf = buf[:i], buf[i:]
|
|
63
|
+
while buf[:1] == b"$" and len(buf) >= 4:
|
|
64
|
+
ln = int.from_bytes(buf[2:4], "big")
|
|
65
|
+
if len(buf) < 4 + ln:
|
|
66
|
+
break
|
|
67
|
+
buf = buf[4 + ln :]
|
|
68
|
+
return req, buf
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def rtsp_header(lines, name):
|
|
72
|
+
"""value of an RTSP header (case-insensitive) or ''"""
|
|
73
|
+
return next((line.split(":", 1)[1].strip() for line in lines if line.lower().startswith(name + ":")), "")
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Pulling the caller's rtsp://<ip>:554 stream (the callee side of the symmetric pull)."""
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import logging
|
|
5
|
+
import re
|
|
6
|
+
import socket
|
|
7
|
+
import threading
|
|
8
|
+
|
|
9
|
+
from metzler.media.rtsp import read_rtsp_request
|
|
10
|
+
|
|
11
|
+
log = logging.getLogger("indoor")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class RtspPuller(threading.Thread):
|
|
15
|
+
"""pulls the caller's rtsp://<caller>:554 stream -> their audio to the speaker,
|
|
16
|
+
their video to ffplay. The callee side of the symmetric intercom pull."""
|
|
17
|
+
|
|
18
|
+
def __init__(self, o, host, on_audio, on_video):
|
|
19
|
+
super().__init__(daemon=True)
|
|
20
|
+
self.o, self.host = o, host
|
|
21
|
+
self.on_audio, self.on_video = on_audio, on_video
|
|
22
|
+
self.running = True
|
|
23
|
+
self.conn = None
|
|
24
|
+
self.seen = set()
|
|
25
|
+
|
|
26
|
+
def run(self):
|
|
27
|
+
self.uri = f"rtsp://{self.host}:{self.o.rtsp_port}/ch1/main/av_stream"
|
|
28
|
+
self.tok = base64.b64encode(f"admin:{self.o.password}".encode()).decode()
|
|
29
|
+
self.buf, self.session, self.cseq = b"", "", 0
|
|
30
|
+
try:
|
|
31
|
+
self.conn = socket.create_connection((self.host, self.o.rtsp_port), timeout=5)
|
|
32
|
+
except OSError as e:
|
|
33
|
+
log.warning("cannot reach caller's RTSP %s: %s", self.uri, e)
|
|
34
|
+
return
|
|
35
|
+
try:
|
|
36
|
+
self._negotiate()
|
|
37
|
+
self._receive()
|
|
38
|
+
except OSError as e:
|
|
39
|
+
log.warning("RTSP pull of %s failed: %s", self.uri, e)
|
|
40
|
+
try:
|
|
41
|
+
self.conn.close()
|
|
42
|
+
except OSError:
|
|
43
|
+
pass
|
|
44
|
+
log.info("RTSP pull of %s ended", self.uri)
|
|
45
|
+
|
|
46
|
+
def _request(self, method, url, extra=""):
|
|
47
|
+
conn = self.conn
|
|
48
|
+
assert conn is not None # set by run() before _negotiate/_receive
|
|
49
|
+
self.cseq += 1
|
|
50
|
+
conn.sendall(
|
|
51
|
+
(
|
|
52
|
+
f"{method} {url} RTSP/1.0\r\nCSeq: {self.cseq}\r\n"
|
|
53
|
+
f"Authorization: Basic {self.tok}\r\n"
|
|
54
|
+
+ (f"Session: {self.session}\r\n" if self.session else "")
|
|
55
|
+
+ extra
|
|
56
|
+
+ "\r\n"
|
|
57
|
+
).encode()
|
|
58
|
+
)
|
|
59
|
+
r, self.buf = read_rtsp_request(conn, self.buf)
|
|
60
|
+
r = r.decode(errors="replace") if r else ""
|
|
61
|
+
m = re.search(r"Session:\s*([^;\s]+)", r)
|
|
62
|
+
if m:
|
|
63
|
+
self.session = m.group(1) # the session id is issued by SETUP
|
|
64
|
+
return r
|
|
65
|
+
|
|
66
|
+
def _negotiate(self):
|
|
67
|
+
"""OPTIONS -> DESCRIBE -> SETUP per track (interleaved TCP) -> PLAY"""
|
|
68
|
+
self._request("OPTIONS", self.uri)
|
|
69
|
+
r = self._request("DESCRIBE", self.uri, "Accept: application/sdp\r\n")
|
|
70
|
+
# figure out which control names the server uses (trackID=1/2 or 0/1)
|
|
71
|
+
tracks = re.findall(r"a=control:(\S+)", r) or ["trackID=1", "trackID=2"]
|
|
72
|
+
tracks = [t for t in tracks if t != "*"][:2]
|
|
73
|
+
for i, t in enumerate(tracks):
|
|
74
|
+
self._request(
|
|
75
|
+
"SETUP", f"{self.uri}/{t}", f"Transport: RTP/AVP/TCP;unicast;interleaved={i * 2}-{i * 2 + 1}\r\n"
|
|
76
|
+
)
|
|
77
|
+
r = self._request("PLAY", self.uri, "Range: npt=0.000-\r\n")
|
|
78
|
+
log.info(
|
|
79
|
+
"pulling caller's stream %s (session %s): %s",
|
|
80
|
+
self.uri,
|
|
81
|
+
self.session or "?",
|
|
82
|
+
r.split("\r\n")[0] if r else "no reply",
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
def _receive(self):
|
|
86
|
+
conn = self.conn
|
|
87
|
+
assert conn is not None
|
|
88
|
+
conn.settimeout(5)
|
|
89
|
+
while self.running:
|
|
90
|
+
try:
|
|
91
|
+
d = conn.recv(65535)
|
|
92
|
+
except TimeoutError:
|
|
93
|
+
continue
|
|
94
|
+
except OSError:
|
|
95
|
+
break
|
|
96
|
+
if not d:
|
|
97
|
+
break
|
|
98
|
+
self.buf += d
|
|
99
|
+
self._drain_frames()
|
|
100
|
+
|
|
101
|
+
def _drain_frames(self):
|
|
102
|
+
"""split $-interleaved frames: {'$', channel, u16 length, RTP}"""
|
|
103
|
+
while len(self.buf) >= 4 and self.buf[:1] == b"$":
|
|
104
|
+
ch, ln = self.buf[1], int.from_bytes(self.buf[2:4], "big")
|
|
105
|
+
if len(self.buf) < 4 + ln:
|
|
106
|
+
break
|
|
107
|
+
frame, self.buf = self.buf[4 : 4 + ln], self.buf[4 + ln :]
|
|
108
|
+
if len(frame) >= 13:
|
|
109
|
+
self._on_frame(ch, frame, ln)
|
|
110
|
+
|
|
111
|
+
def _on_frame(self, ch, frame, ln):
|
|
112
|
+
pt = frame[1] & 0x7F
|
|
113
|
+
if ch not in self.seen:
|
|
114
|
+
self.seen.add(ch)
|
|
115
|
+
log.info("caller stream: first frame on channel %d, PT %d, %dB", ch, pt, ln)
|
|
116
|
+
if ch < 2 and self.on_video:
|
|
117
|
+
self.on_video(frame) # whole RTP packet (seq/ts kept)
|
|
118
|
+
elif pt == 0 and self.on_audio:
|
|
119
|
+
self.on_audio(frame[12:])
|
|
120
|
+
|
|
121
|
+
def stop(self):
|
|
122
|
+
self.running = False
|
|
123
|
+
try:
|
|
124
|
+
if self.conn:
|
|
125
|
+
self.conn.sendall(b"TEARDOWN rtsp://x RTSP/1.0\r\nCSeq: 99\r\n\r\n")
|
|
126
|
+
self.conn.close()
|
|
127
|
+
except OSError:
|
|
128
|
+
pass
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"""Our :554 - the RTSP server the calling station pulls our audio from."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import random
|
|
5
|
+
import re
|
|
6
|
+
import socket
|
|
7
|
+
import struct
|
|
8
|
+
import subprocess
|
|
9
|
+
import threading
|
|
10
|
+
import time
|
|
11
|
+
|
|
12
|
+
from metzler.media.rtsp import RTSP_SDP_AV, read_rtsp_request, rtsp_header, rtsp_reply
|
|
13
|
+
|
|
14
|
+
log = logging.getLogger("indoor")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _spawn_test_video():
|
|
18
|
+
"""ffmpeg: black 320x240 H264 test stream on stdout (None without ffmpeg)"""
|
|
19
|
+
try:
|
|
20
|
+
return subprocess.Popen(
|
|
21
|
+
[
|
|
22
|
+
"ffmpeg",
|
|
23
|
+
"-loglevel",
|
|
24
|
+
"error",
|
|
25
|
+
"-re",
|
|
26
|
+
"-f",
|
|
27
|
+
"lavfi",
|
|
28
|
+
"-i",
|
|
29
|
+
"color=c=black:s=320x240:r=12.5",
|
|
30
|
+
"-c:v",
|
|
31
|
+
"libx264",
|
|
32
|
+
"-profile:v",
|
|
33
|
+
"main",
|
|
34
|
+
"-level",
|
|
35
|
+
"2.0",
|
|
36
|
+
"-x264-params",
|
|
37
|
+
"keyint=25",
|
|
38
|
+
"-f",
|
|
39
|
+
"h264",
|
|
40
|
+
"-",
|
|
41
|
+
],
|
|
42
|
+
stdout=subprocess.PIPE,
|
|
43
|
+
stderr=subprocess.DEVNULL,
|
|
44
|
+
)
|
|
45
|
+
except OSError:
|
|
46
|
+
return None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _annexb_nals(data):
|
|
50
|
+
"""split an annex-B byte stream at its 00 00 01 / 00 00 00 01 start codes"""
|
|
51
|
+
for part in re.split(b"\x00\x00\x01|\x00\x00\x00\x01", data):
|
|
52
|
+
if part:
|
|
53
|
+
yield part
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class RtspServer(threading.Thread):
|
|
57
|
+
"""hikvision-style RTSP server on :554 - the caller pulls our stream here.
|
|
58
|
+
DESCRIBE always advertises video+audio (mandatory for their client); the
|
|
59
|
+
data path sends only 320B/40ms PCMU, exactly like a real indoor unit."""
|
|
60
|
+
|
|
61
|
+
def __init__(self, o):
|
|
62
|
+
super().__init__(daemon=True)
|
|
63
|
+
self.o = o
|
|
64
|
+
self.sdp = RTSP_SDP_AV
|
|
65
|
+
self.mic = None # callable -> 160B ulaw, set while a call runs
|
|
66
|
+
self.ls = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
67
|
+
self.ls.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
68
|
+
self.ls.bind((o.local_ip, o.rtsp_port))
|
|
69
|
+
self.ls.listen(4)
|
|
70
|
+
self.running = True
|
|
71
|
+
|
|
72
|
+
def run(self):
|
|
73
|
+
while self.running:
|
|
74
|
+
try:
|
|
75
|
+
conn, addr = self.ls.accept()
|
|
76
|
+
except OSError:
|
|
77
|
+
return
|
|
78
|
+
threading.Thread(target=self.handle, args=(conn, addr), daemon=True).start()
|
|
79
|
+
|
|
80
|
+
def handle(self, conn, addr):
|
|
81
|
+
log.info("RTSP client connected: %s:%d", *addr)
|
|
82
|
+
conn.settimeout(30)
|
|
83
|
+
sess = _RtspSession(self, conn)
|
|
84
|
+
buf = b""
|
|
85
|
+
try:
|
|
86
|
+
while True:
|
|
87
|
+
req, buf = read_rtsp_request(conn, buf)
|
|
88
|
+
if req is None or not sess.dispatch(req, addr):
|
|
89
|
+
break
|
|
90
|
+
except (OSError, TimeoutError):
|
|
91
|
+
pass
|
|
92
|
+
sess.playing[0] = False
|
|
93
|
+
try:
|
|
94
|
+
conn.close()
|
|
95
|
+
except OSError:
|
|
96
|
+
pass
|
|
97
|
+
log.info("RTSP client %s:%d disconnected", *addr)
|
|
98
|
+
|
|
99
|
+
def _send(self, conn, wlock, chan, rtp):
|
|
100
|
+
f = b"$" + bytes([chan]) + len(rtp).to_bytes(2, "big") + rtp
|
|
101
|
+
with wlock:
|
|
102
|
+
conn.sendall(f)
|
|
103
|
+
|
|
104
|
+
def _nal_rtp(self, nal, seq, ts, ssrc):
|
|
105
|
+
"""packetize one annex-B NAL into PT96 RTP packet(s) (FU-A when needed)"""
|
|
106
|
+
out = []
|
|
107
|
+
hdr = lambda m, s, t: struct.pack(">BBHII", 0x80, 96 | (m << 7), s, t, ssrc)
|
|
108
|
+
if len(nal) <= 1300:
|
|
109
|
+
out.append(hdr(1, seq[0], ts) + nal)
|
|
110
|
+
seq[0] += 1
|
|
111
|
+
else:
|
|
112
|
+
ind, nal_type = nal[0] & 0xE0 | 28, nal[0] & 0x1F
|
|
113
|
+
body = nal[1:]
|
|
114
|
+
while body:
|
|
115
|
+
part, body = body[:1300], body[1300:]
|
|
116
|
+
fu = nal_type | (0x80 if not out else 0) | (0x40 if not body else 0)
|
|
117
|
+
fuh = (ind << 8) | fu
|
|
118
|
+
out.append(hdr(0 if body else 1, seq[0], ts) + fuh.to_bytes(2, "big") + part)
|
|
119
|
+
seq[0] += 1
|
|
120
|
+
return out
|
|
121
|
+
|
|
122
|
+
def stream(self, conn, wlock, playing, chmap, ssrcs):
|
|
123
|
+
"""send the stream exactly like a real indoor unit serves it:
|
|
124
|
+
the SDP advertises video+audio (their client requires the video track),
|
|
125
|
+
but on the wire the unit emits ONLY PCMU audio - 320B payloads, 40 ms,
|
|
126
|
+
ts += 320 @8kHz - never a single video RTP packet (verified from a
|
|
127
|
+
live pull of the main indoor's :554 during an extension call:
|
|
128
|
+
1.5 MB, all ch2 PT0 320B, zero ch0). The RTP ssrc must equal the one
|
|
129
|
+
we declared in the SETUP reply or their player drops the packets."""
|
|
130
|
+
seq_a = [random.getrandbits(15)]
|
|
131
|
+
ts_a = [random.getrandbits(32)]
|
|
132
|
+
ssrc = ssrcs.get("audio", random.getrandbits(32))
|
|
133
|
+
ch_a = chmap.get("audio")
|
|
134
|
+
ch_v = chmap.get("video")
|
|
135
|
+
if getattr(self.o, "rtsp_video", False) and ch_v is not None:
|
|
136
|
+
threading.Thread(
|
|
137
|
+
target=self._video_feed,
|
|
138
|
+
args=(conn, wlock, playing, ch_v, ssrcs.get("video", random.getrandbits(32))),
|
|
139
|
+
daemon=True,
|
|
140
|
+
).start()
|
|
141
|
+
next_a = 0.0
|
|
142
|
+
while playing[0]:
|
|
143
|
+
try:
|
|
144
|
+
if self.mic and ch_a is not None:
|
|
145
|
+
if time.time() < next_a:
|
|
146
|
+
time.sleep(min(next_a - time.time(), 0.02))
|
|
147
|
+
continue
|
|
148
|
+
payload = self.mic() + self.mic() # 2 x 160B = 40 ms
|
|
149
|
+
rtp = struct.pack(">BBHII", 0x80, 0, seq_a[0] & 0xFFFF, ts_a[0] & 0xFFFFFFFF, ssrc) + payload
|
|
150
|
+
self._send(conn, wlock, ch_a, rtp)
|
|
151
|
+
seq_a[0] += 1
|
|
152
|
+
ts_a[0] += 320
|
|
153
|
+
next_a = time.time() + 0.04
|
|
154
|
+
else:
|
|
155
|
+
time.sleep(0.01)
|
|
156
|
+
except OSError:
|
|
157
|
+
break
|
|
158
|
+
|
|
159
|
+
def _video_feed(self, conn, wlock, playing, ch_v, ssrc):
|
|
160
|
+
"""optional (--rtsp-video): ffmpeg-generated H264 like a door/camera unit
|
|
161
|
+
would send. Main profile @2.0 320x240, annex-B, packetized via _nal_rtp."""
|
|
162
|
+
proc = _spawn_test_video()
|
|
163
|
+
if not proc:
|
|
164
|
+
return
|
|
165
|
+
seq = [random.getrandbits(15)]
|
|
166
|
+
ts = [random.getrandbits(32)]
|
|
167
|
+
buf = b""
|
|
168
|
+
try:
|
|
169
|
+
while playing[0]:
|
|
170
|
+
chunk = proc.stdout.read(4096)
|
|
171
|
+
if not chunk:
|
|
172
|
+
break
|
|
173
|
+
buf += chunk
|
|
174
|
+
i = buf.rfind(b"\x00\x00\x01")
|
|
175
|
+
if i < 4:
|
|
176
|
+
continue
|
|
177
|
+
ready, buf = buf[:i], buf[i:]
|
|
178
|
+
for nal in _annexb_nals(ready):
|
|
179
|
+
for rtp in self._nal_rtp(nal, seq, ts[0], ssrc):
|
|
180
|
+
self._send(conn, wlock, ch_v, rtp)
|
|
181
|
+
ts[0] += 3600 # 40 ms @90kHz
|
|
182
|
+
except OSError:
|
|
183
|
+
pass
|
|
184
|
+
finally:
|
|
185
|
+
proc.terminate()
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
class _RtspSession:
|
|
189
|
+
"""state of one client connection to RtspServer: one method per RTSP verb"""
|
|
190
|
+
|
|
191
|
+
def __init__(self, server, conn):
|
|
192
|
+
self.server, self.conn = server, conn
|
|
193
|
+
self.id = str(random.getrandbits(31))
|
|
194
|
+
self.playing = [False]
|
|
195
|
+
self.chmap = {} # 'audio'/'video' -> interleaved base channel
|
|
196
|
+
self.ssrcs = {} # 'audio'/'video' -> ssrc declared in SETUP reply
|
|
197
|
+
self.ssrc_base = random.getrandbits(32)
|
|
198
|
+
self.wlock = threading.Lock()
|
|
199
|
+
|
|
200
|
+
def dispatch(self, req, addr):
|
|
201
|
+
"""handle one request; False once the client tore the session down"""
|
|
202
|
+
try:
|
|
203
|
+
lines = req.decode(errors="replace").split("\r\n")
|
|
204
|
+
method, url = lines[0].split()[:2]
|
|
205
|
+
except (ValueError, IndexError, AttributeError) as e:
|
|
206
|
+
log.debug("unparseable RTSP request from %s: %s", addr, e)
|
|
207
|
+
return True
|
|
208
|
+
handler = getattr(self, "on_" + method.lower(), None)
|
|
209
|
+
if handler:
|
|
210
|
+
return handler(rtsp_header(lines, "cseq") or "0", url, lines) is not False
|
|
211
|
+
return True
|
|
212
|
+
|
|
213
|
+
def _reply(self, cseq, extra="", body=None):
|
|
214
|
+
rtsp_reply(self.conn, cseq, extra=f"Session: {self.id}\r\n{extra}", body=body)
|
|
215
|
+
|
|
216
|
+
def on_options(self, cseq, url, lines):
|
|
217
|
+
rtsp_reply(self.conn, cseq, extra="Public: OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE\r\n")
|
|
218
|
+
|
|
219
|
+
def on_describe(self, cseq, url, lines):
|
|
220
|
+
self._reply(cseq, body=self.server.sdp)
|
|
221
|
+
|
|
222
|
+
def on_setup(self, cseq, url, lines):
|
|
223
|
+
il = re.search(r"interleaved=(\d+)-(\d+)", rtsp_header(lines, "transport"))
|
|
224
|
+
ch = il.group(0).split("=", 1)[1] if il else "0-1"
|
|
225
|
+
track = (
|
|
226
|
+
"video"
|
|
227
|
+
if "trackID=1" in url
|
|
228
|
+
else "audio"
|
|
229
|
+
if "trackID=2" in url
|
|
230
|
+
else "audio"
|
|
231
|
+
if "video" not in self.chmap
|
|
232
|
+
else "video"
|
|
233
|
+
)
|
|
234
|
+
self.chmap[track] = int(ch.split("-")[0])
|
|
235
|
+
self.ssrcs.setdefault(track, (self.ssrc_base + (0 if track == "video" else 1)) & 0xFFFFFFFF)
|
|
236
|
+
self._reply(cseq, f"Transport: RTP/AVP/TCP;unicast;interleaved={ch};ssrc={self.ssrcs[track]:08x}\r\n")
|
|
237
|
+
|
|
238
|
+
def on_play(self, cseq, url, lines):
|
|
239
|
+
self._reply(cseq)
|
|
240
|
+
if not self.playing[0]:
|
|
241
|
+
self.playing[0] = True
|
|
242
|
+
threading.Thread(
|
|
243
|
+
target=self.server.stream,
|
|
244
|
+
args=(self.conn, self.wlock, self.playing, self.chmap, self.ssrcs),
|
|
245
|
+
daemon=True,
|
|
246
|
+
).start()
|
|
247
|
+
|
|
248
|
+
def on_pause(self, cseq, url, lines):
|
|
249
|
+
self.playing[0] = False
|
|
250
|
+
self._reply(cseq)
|
|
251
|
+
|
|
252
|
+
def on_teardown(self, cseq, url, lines):
|
|
253
|
+
self.on_pause(cseq, url, lines)
|
|
254
|
+
return False
|
metzler/media/srtp.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""SDES-SRTP (RFC 3711, AES_CM_128_HMAC_SHA1_80) for the provider media leg.
|
|
2
|
+
|
|
3
|
+
AES comes from the optional `cryptography` package; it is imported lazily so the
|
|
4
|
+
simulator still runs on a bare Python install (plain RTP then)."""
|
|
5
|
+
|
|
6
|
+
import base64
|
|
7
|
+
import hashlib
|
|
8
|
+
import hmac
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
import struct
|
|
12
|
+
|
|
13
|
+
SRTP_SUITE = "AES_CM_128_HMAC_SHA1_80"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def srtp_available():
|
|
17
|
+
"""SRTP needs AES from the optional 'cryptography' package; everything
|
|
18
|
+
else in this script is stdlib, so it still runs standalone without it"""
|
|
19
|
+
try:
|
|
20
|
+
import cryptography.hazmat.primitives.ciphers # noqa: F401
|
|
21
|
+
|
|
22
|
+
return True
|
|
23
|
+
except ImportError:
|
|
24
|
+
return False
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _aes_ctr(key, iv, data):
|
|
28
|
+
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
|
29
|
+
|
|
30
|
+
return Cipher(algorithms.AES(key), modes.CTR(iv)).encryptor().update(data)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Srtp:
|
|
34
|
+
"""One direction of an RFC 3711 SRTP stream, suite AES_CM_128_HMAC_SHA1_80
|
|
35
|
+
(the SDES default Linphone accepts). Key-derivation rate 0, no MKI.
|
|
36
|
+
protect(): RTP -> SRTP for sending; unprotect(): SRTP -> RTP or None if
|
|
37
|
+
the auth tag fails. RTCP is not protected (the bridge sends none)."""
|
|
38
|
+
|
|
39
|
+
TAG = 10
|
|
40
|
+
|
|
41
|
+
def __init__(self, master_key, master_salt):
|
|
42
|
+
prf = lambda label, n: _aes_ctr(master_key, self._kdf_iv(master_salt, label), b"\0" * n)
|
|
43
|
+
self.k_e, self.k_a, self.k_s = prf(0, 16), prf(1, 20), prf(2, 14)
|
|
44
|
+
self.roc = 0
|
|
45
|
+
self.last_seq = None
|
|
46
|
+
|
|
47
|
+
@staticmethod
|
|
48
|
+
def _kdf_iv(salt, label):
|
|
49
|
+
x = int.from_bytes(salt, "big") ^ (label << 48)
|
|
50
|
+
return (x << 16).to_bytes(16, "big")
|
|
51
|
+
|
|
52
|
+
@classmethod
|
|
53
|
+
def from_inline(cls, b64):
|
|
54
|
+
raw = base64.b64decode(b64)
|
|
55
|
+
return cls(raw[:16], raw[16:30])
|
|
56
|
+
|
|
57
|
+
@staticmethod
|
|
58
|
+
def _hdr_len(pkt):
|
|
59
|
+
n = 12 + 4 * (pkt[0] & 0x0F)
|
|
60
|
+
if pkt[0] & 0x10: # header extension
|
|
61
|
+
n += 4 + 4 * struct.unpack(">H", pkt[n + 2 : n + 4])[0]
|
|
62
|
+
return n
|
|
63
|
+
|
|
64
|
+
def _iv(self, ssrc, index):
|
|
65
|
+
x = (int.from_bytes(self.k_s, "big") << 16) ^ (ssrc << 64) ^ (index << 16)
|
|
66
|
+
return x.to_bytes(16, "big")
|
|
67
|
+
|
|
68
|
+
def _tag(self, authed, roc):
|
|
69
|
+
return hmac.new(self.k_a, authed + struct.pack(">I", roc), hashlib.sha1).digest()[: self.TAG]
|
|
70
|
+
|
|
71
|
+
def protect(self, pkt):
|
|
72
|
+
seq, ssrc = struct.unpack(">H", pkt[2:4])[0], struct.unpack(">I", pkt[8:12])[0]
|
|
73
|
+
if self.last_seq is not None and seq < self.last_seq and self.last_seq - seq > 0x8000:
|
|
74
|
+
self.roc = (self.roc + 1) & 0xFFFFFFFF # sequence wrapped
|
|
75
|
+
self.last_seq = seq
|
|
76
|
+
h = self._hdr_len(pkt)
|
|
77
|
+
enc = pkt[:h] + _aes_ctr(self.k_e, self._iv(ssrc, (self.roc << 16) | seq), pkt[h:])
|
|
78
|
+
return enc + self._tag(enc, self.roc)
|
|
79
|
+
|
|
80
|
+
def _guess_roc(self, seq):
|
|
81
|
+
"""RFC 3711 appendix A index estimate"""
|
|
82
|
+
if self.last_seq is None:
|
|
83
|
+
return self.roc
|
|
84
|
+
if self.last_seq < 0x8000:
|
|
85
|
+
return self.roc - 1 if seq - self.last_seq > 0x8000 and self.roc else self.roc
|
|
86
|
+
return self.roc + 1 if self.last_seq - 0x8000 > seq else self.roc
|
|
87
|
+
|
|
88
|
+
def unprotect(self, pkt):
|
|
89
|
+
if len(pkt) < 12 + self.TAG:
|
|
90
|
+
return None
|
|
91
|
+
seq, ssrc = struct.unpack(">H", pkt[2:4])[0], struct.unpack(">I", pkt[8:12])[0]
|
|
92
|
+
body, tag = pkt[: -self.TAG], pkt[-self.TAG :]
|
|
93
|
+
roc = self._guess_roc(seq)
|
|
94
|
+
if not hmac.compare_digest(self._tag(body, roc), tag):
|
|
95
|
+
return None
|
|
96
|
+
if roc > self.roc or (roc == self.roc and (self.last_seq is None or seq > self.last_seq)):
|
|
97
|
+
self.roc, self.last_seq = roc, seq
|
|
98
|
+
h = self._hdr_len(body)
|
|
99
|
+
return body[:h] + _aes_ctr(self.k_e, self._iv(ssrc, (roc << 16) | seq), body[h:])
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class SrtpSession:
|
|
103
|
+
"""both directions of one media stream: tx from our offered key, rx from
|
|
104
|
+
the key in the peer's answer (a=crypto). `inline` is our SDP key."""
|
|
105
|
+
|
|
106
|
+
def __init__(self):
|
|
107
|
+
raw = os.urandom(30)
|
|
108
|
+
self.inline = base64.b64encode(raw).decode()
|
|
109
|
+
self.tx = Srtp(raw[:16], raw[16:])
|
|
110
|
+
self.rx = None
|
|
111
|
+
|
|
112
|
+
def crypto_attr(self):
|
|
113
|
+
return f"a=crypto:1 {SRTP_SUITE} inline:{self.inline}\r\n"
|
|
114
|
+
|
|
115
|
+
def accept_answer(self, media):
|
|
116
|
+
"""bind the rx key from the answered m= line; False if the peer
|
|
117
|
+
answered without SRTP (plain RTP fallback)"""
|
|
118
|
+
for a in media.get("attrs", []):
|
|
119
|
+
m = re.match(r"crypto:\d+ (\S+) inline:([A-Za-z0-9+/=]+)", a)
|
|
120
|
+
if m and m.group(1) == SRTP_SUITE:
|
|
121
|
+
self.rx = Srtp.from_inline(m.group(2))
|
|
122
|
+
return True
|
|
123
|
+
return False
|