WebStudio/server.py

249 lines
8.1 KiB
Python
Raw Normal View History

import asyncio
import websockets
import json
import uuid
2020-04-07 10:19:28 +00:00
import av # type: ignore
import struct
2020-04-07 10:19:28 +00:00
from aiortc import MediaStreamTrack, RTCPeerConnection, RTCSessionDescription # type: ignore
from aiortc.contrib.media import MediaBlackhole, MediaPlayer # type: ignore
import jack as Jack # type: ignore
2020-04-05 09:53:03 +00:00
import os
import re
from datetime import datetime
2020-04-07 10:19:28 +00:00
from typing import Optional, Any
2020-04-05 09:53:03 +00:00
file_contents_ex = re.compile(r"^ws=\d$")
2020-04-07 10:19:28 +00:00
def write_ob_status(status: bool) -> None:
2020-04-05 09:53:03 +00:00
if not os.path.exists("/music/ob_state.conf"):
print("OB State file does not exist. Bailing.")
return
2020-04-07 11:23:10 +00:00
with open("/music/ob_state.conf", "r+") as fd:
2020-04-05 09:53:03 +00:00
content = fd.read()
if "ws" in content:
content = re.sub(file_contents_ex, "ws=" + str(1 if status else 0), content)
else:
if len(content) > 0 and content[len(content) - 1] != "\n":
2020-04-05 09:53:03 +00:00
content += "\n"
2020-04-07 10:19:28 +00:00
content += "ws=" + str(1 if status else 0) + "\n"
2020-04-05 09:53:03 +00:00
fd.seek(0)
fd.write(content)
fd.truncate()
2020-04-07 10:19:28 +00:00
@Jack.set_error_function # type: ignore
def error(msg: str) -> None:
print("Error:", msg)
2020-04-07 10:19:28 +00:00
@Jack.set_info_function # type: ignore
def info(msg: str) -> None:
print("Info:", msg)
jack = Jack.Client("webstudio")
out1 = jack.outports.register("out_0")
out2 = jack.outports.register("out_1")
2020-04-07 10:19:28 +00:00
transfer_buffer1: Any = None
transfer_buffer2: Any = None
2020-04-07 10:19:28 +00:00
def init_buffers() -> None:
global transfer_buffer1, transfer_buffer2
transfer_buffer1 = Jack.RingBuffer(jack.samplerate * 10)
transfer_buffer2 = Jack.RingBuffer(jack.samplerate * 10)
init_buffers()
2020-04-07 10:19:28 +00:00
@jack.set_process_callback # type: ignore
def process(frames: int) -> None:
buf1 = out1.get_buffer()
piece1 = transfer_buffer1.read(len(buf1))
buf1[: len(piece1)] = piece1
buf2 = out2.get_buffer()
piece2 = transfer_buffer2.read(len(buf2))
buf2[: len(piece2)] = piece2
class JackSender(object):
2020-04-07 10:19:28 +00:00
resampler: Any
def __init__(self, track: MediaStreamTrack) -> None:
self.track = track
self.resampler = None
2020-04-02 18:26:58 +00:00
self.ended = False
2020-04-07 10:19:28 +00:00
def end(self) -> None:
2020-04-02 18:26:58 +00:00
self.ended = True
2020-04-07 10:19:28 +00:00
async def process(self) -> None:
while True:
2020-04-02 18:26:58 +00:00
if self.ended:
break
frame = await self.track.recv()
# Right, depending on the format, we may need to do some fuckery.
# Jack expects all audio to be 32 bit floating point
# while PyAV may give us audio in any format
# (my testing has shown it to be signed 16-bit)
# We use PyAV to resample it into the right format
if self.resampler is None:
self.resampler = av.audio.resampler.AudioResampler(
format="fltp", layout="stereo", rate=jack.samplerate
)
frame.pts = None # DIRTY HACK
new_frame = self.resampler.resample(frame)
transfer_buffer1.write(new_frame.planes[0])
transfer_buffer2.write(new_frame.planes[1])
current_session = None
class Session(object):
2020-04-07 10:19:28 +00:00
websocket: Optional[websockets.WebSocketServerProtocol]
sender: Optional[JackSender]
connection_state: Optional[str]
pc: Optional[Any]
def __init__(self) -> None:
2020-04-02 18:26:58 +00:00
self.websocket = None
self.sender = None
self.pc = None
self.connection_state = None
2020-04-02 18:26:58 +00:00
2020-04-07 10:19:28 +00:00
async def end(self) -> None:
2020-04-03 07:56:52 +00:00
print(self.connection_id, "going away")
2020-04-02 18:26:58 +00:00
if self.sender is not None:
self.sender.end()
2020-04-07 09:45:00 +00:00
if self.pc is not None:
await self.pc.close()
init_buffers()
2020-04-05 09:53:03 +00:00
write_ob_status(False)
2020-04-07 09:45:00 +00:00
if self.websocket is not None:
await self.websocket.send(json.dumps({"kind": "REPLACED"}))
2020-04-07 10:19:28 +00:00
def create_peerconnection(self) -> None:
self.pc = RTCPeerConnection()
2020-04-07 10:19:28 +00:00
assert self.pc is not None
2020-04-07 10:19:28 +00:00
@self.pc.on("signalingstatechange") # type: ignore
async def on_signalingstatechange() -> None:
assert self.pc is not None
print(
self.connection_id,
"Signaling state is {}".format(self.pc.signalingState),
)
2020-04-07 10:19:28 +00:00
@self.pc.on("iceconnectionstatechange") # type: ignore
async def on_iceconnectionstatechange() -> None:
2020-04-07 11:23:10 +00:00
if self.pc is None:
print(self.connection_id, "ICE connection state change, but the PC is None!")
else:
print(
self.connection_id,
"ICE connection state is {}".format(self.pc.iceConnectionState),
)
if self.pc.iceConnectionState == "failed":
await self.pc.close()
self.pc = None
if self.websocket is not None:
await self.websocket.close(1008)
return
2020-04-07 10:19:28 +00:00
@self.pc.on("track") # type: ignore
async def on_track(track: MediaStreamTrack) -> None:
2020-04-02 18:28:15 +00:00
global current_session
2020-04-03 07:56:52 +00:00
print(self.connection_id, "Received track")
if track.kind == "audio":
2020-04-03 07:56:52 +00:00
print(self.connection_id, "Adding to Jack.")
2020-04-07 10:19:28 +00:00
@track.on("ended") # type: ignore
async def on_ended() -> None:
2020-04-03 07:56:52 +00:00
print(self.connection_id, "Track {} ended".format(track.kind))
2020-04-05 09:53:03 +00:00
# TODO: this doesn't exactly handle reconnecting gracefully
self.end()
self.sender = JackSender(track)
if current_session is not None:
await current_session.end()
current_session = self
2020-04-05 09:53:03 +00:00
write_ob_status(True)
await self.sender.process()
2020-04-07 10:19:28 +00:00
async def process_ice(self, message: Any) -> None:
if self.connection_state == "HELLO" and message["kind"] == "OFFER":
offer = RTCSessionDescription(sdp=message["sdp"], type=message["type"])
print(self.connection_id, "Received offer")
2020-04-07 10:19:28 +00:00
self.create_peerconnection()
2020-04-07 10:19:28 +00:00
assert self.pc is not None
await self.pc.setRemoteDescription(offer)
answer = await self.pc.createAnswer()
await self.pc.setLocalDescription(answer)
2020-04-07 10:19:28 +00:00
assert self.websocket is not None
2020-04-07 09:45:00 +00:00
await self.websocket.send(
json.dumps(
{
"kind": "ANSWER",
"type": self.pc.localDescription.type,
"sdp": self.pc.localDescription.sdp,
}
)
)
self.connection_state = "ANSWER"
print(self.connection_id, "Sent answer")
else:
print(
self.connection_state,
"Incorrect kind {} for state {}".format(
message["kind"], self.connection_state
),
)
2020-04-07 10:19:28 +00:00
async def connect(self, websocket: websockets.WebSocketServerProtocol) -> None:
self.websocket = websocket
self.connection_id = uuid.uuid4()
self.connection_state = "HELLO"
print(self.connection_id, "Connected")
await websocket.send(
json.dumps({"kind": "HELLO", "connectionId": str(self.connection_id)})
)
async for msg in websocket:
data = json.loads(msg)
if data["kind"] == "OFFER":
await self.process_ice(data)
elif data["kind"] == "TIME":
time = datetime.now().time()
await websocket.send(json.dumps({"kind": "TIME", "time": str(time)}))
else:
print(self.connection_id, "Unknown kind {}".format(data["kind"]))
await websocket.send(
json.dumps({"kind": "ERROR", "error": "unknown_kind"})
)
2020-04-07 10:19:28 +00:00
async def serve(websocket: websockets.WebSocketServerProtocol, path: str) -> None:
if path == "/stream":
session = Session()
await session.connect(websocket)
else:
pass
2020-04-03 07:56:52 +00:00
WS_PORT = 8079
jack.activate()
2020-04-03 07:56:52 +00:00
start_server = websockets.serve(serve, "localhost", WS_PORT)
print("Shittyserver starting on port {}.".format(WS_PORT))
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()