Remove audio path.
[toast/stream2beamer.git] / lagarde.py
1 #!/usr/bin/python3
2
3 import argparse
4 import asyncio
5 import json
6 import logging
7 import ssl
8 import queue
9 from typing import Optional, List
10
11 import gi
12 import websockets
13
14 gi.require_version('Gst', '1.0')
15 from gi.repository import Gst
16
17 gi.require_version('GstWebRTC', '1.0')
18 from gi.repository import GstWebRTC
19
20 gi.require_version('GstSdp', '1.0')
21 from gi.repository import GstSdp
22
23 gi.require_version('GstRtspServer', '1.0')
24 from gi.repository import Gst, GstRtspServer, GObject, GLib
25
26 log = logging.getLogger(__name__)
27
28
29 class GstreamerRtspServer():
30     def __init__(self):
31         server = GstRtspServer.RTSPServer()
32         server.set_address("::")
33         server.set_service('8554')  # port as string
34         factory = GstRtspServer.RTSPMediaFactory()
35         factory.set_launch("intervideosrc ! decodebin ! theoraenc ! queue ! rtptheorapay name=pay0")
36         factory.set_shared(True)
37         mountPoints = server.get_mount_points()
38         mountPoints.add_factory("/cug", factory)
39         server.attach()
40         self.server = server
41
42
43 class Lagarde:
44     def __init__(self):
45         self.sdp_offer: Optional[str] = None
46         self.websocket: Optional[websockets.client.WebSocketClientProtocol] = None
47         self.session_id = None
48         self.received_ice_candidates = queue.Queue()
49         self.generated_ice_candidates = queue.Queue()
50         self.user_fragments: Optional[List] = None
51         self.mids: Optional[List] = None
52         self.pipe = None
53         self.webrtcbin = None
54
55     def on_negotiation_needed(self, element):
56         log.debug('on_negotiation_needed')
57
58     def on_ice_candidate(self, element, mlineindex, candidate):
59         log.debug('on_ice_candidate')
60         self.generated_ice_candidates.put_nowait((mlineindex, candidate))
61
62     def webrtcbin_pad_added(self, element, pad):
63         log.debug('webrtcbin_pad_added')
64         if pad.direction != Gst.PadDirection.SRC:
65             return
66         decodebin = Gst.ElementFactory.make('decodebin')
67         decodebin.connect('pad-added', self.decodebin_pad_added)
68         self.pipe.add(decodebin)
69         decodebin.sync_state_with_parent()
70         self.webrtcbin.link(decodebin)
71
72     def decodebin_pad_added(self, element, pad):
73         log.debug('decodebin_pad_added')
74         if not pad.has_current_caps():
75             log.debug(pad, 'has no caps, ignoring')
76             return
77
78         caps = pad.get_current_caps()
79         padsize = caps.get_size()
80         for i in range(padsize):
81             s = caps.get_structure(i) # Gst.Structure
82             name = s.get_name()
83             if name.startswith('video'):
84                 q = Gst.ElementFactory.make('queue')
85                 conv = Gst.ElementFactory.make('videoconvert')
86                 sink = Gst.ElementFactory.make('intervideosink')
87                 self.pipe.add(q)
88                 self.pipe.add(conv)
89                 self.pipe.add(sink)
90                 self.pipe.sync_children_states()
91                 pad.link(q.get_static_pad('sink'))
92                 q.link(conv)
93                 conv.link(sink)
94
95     async def listen_to_gstreamer_bus(self):
96         self.webrtcbin = Gst.ElementFactory.make('webrtcbin', 'laplace')
97         self.pipe = Gst.Pipeline.new("pipeline")
98         Gst.Bin.do_add_element(self.pipe, self.webrtcbin)
99         bus = Gst.Pipeline.get_bus(self.pipe)
100         self.webrtcbin.connect('on-negotiation-needed', self.on_negotiation_needed)
101         self.webrtcbin.connect('on-ice-candidate', self.on_ice_candidate)
102         self.webrtcbin.connect('pad-added', self.webrtcbin_pad_added)
103         self.pipe.set_state(Gst.State.PLAYING)
104         try:
105             while True:
106                 if bus.have_pending():
107                     msg = bus.pop()
108                     if msg.type == Gst.MessageType.ERROR:
109                         log.error(f'Error from gstreamer message bus: {msg.get_structure()}')
110                         return
111                     elif msg.type == Gst.MessageType.EOS:  # end of stream
112                         log.info(f'Gstreamer message bus reports end of stream')
113                         return
114                 elif self.sdp_offer is not None:
115                     res, sm = GstSdp.SDPMessage.new()
116                     assert res == GstSdp.SDPResult.OK
117                     GstSdp.sdp_message_parse_buffer(bytes(self.sdp_offer.encode()), sm)
118                     # the three lines above can also be done this way in new versions of GStreamer:
119                     # sm = GstSdp.SDPMessage.new_from_text(sdp_offer)
120                     rd = GstWebRTC.WebRTCSessionDescription.new(GstWebRTC.WebRTCSDPType.OFFER, sm)
121                     gst_promise = Gst.Promise.new()
122                     self.webrtcbin.emit('set-remote-description', rd, gst_promise)
123                     await asyncio.get_event_loop().run_in_executor(None, gst_promise.wait)
124                     self.sdp_offer = None
125
126                     gst_promise = Gst.Promise.new()
127                     self.webrtcbin.emit('create-answer', None, gst_promise)
128                     result = await asyncio.get_event_loop().run_in_executor(None, gst_promise.wait)
129                     assert result == Gst.PromiseResult.REPLIED
130                     reply = gst_promise.get_reply()
131                     answer = reply.get_value('answer')
132                     sdp_message = answer.sdp
133                     self.user_fragments = [sdp_message.get_media(i).get_attribute_val('ice-ufrag')
134                                           for i in range(sdp_message.medias_len())]
135                     self.mids = [sdp_message.get_media(i).get_attribute_val('mid')
136                                           for i in range(sdp_message.medias_len())]
137                     sdp_answer = sdp_message.as_text()
138                     log.info(f'Send SDP answer:\n{sdp_answer}')
139                     sdp_answer_msg = json.dumps({
140                         'SessionID': self.session_id,
141                         'Type': "gotAnswer",
142                         'Value': json.dumps({
143                             'type': 'answer',
144                             'sdp': sdp_answer
145                         })
146                     })
147                     gst_promise = Gst.Promise.new()
148                     self.webrtcbin.emit('set-local-description', answer, gst_promise)
149                     await asyncio.get_event_loop().run_in_executor(None, gst_promise.wait)
150                     gst_promise.get_reply()
151                     await self.websocket.send(sdp_answer_msg)
152
153                 elif self.received_ice_candidates.qsize() > 0:
154                     ic = self.received_ice_candidates.get_nowait()
155                     if ic['candidate'] != '':
156                         self.webrtcbin.emit('add-ice-candidate', ic['sdpMLineIndex'], ic['candidate'])
157
158                 elif self.generated_ice_candidates.qsize() > 0:
159                     mlineindex, candidate = self.generated_ice_candidates.get_nowait()
160                     icemsg_value = json.dumps({
161                         "candidate": candidate,
162                         "sdpMid": self.mids[mlineindex],
163                         "sdpMLineIndex": mlineindex,
164                         "usernameFragment": self.user_fragments[mlineindex],
165                     })
166                     icemsg = json.dumps({
167                         'SessionID': self.session_id,
168                         'Type': 'addCalleeIceCandidate',
169                         'Value': icemsg_value,
170                     })
171                     log.info(f'Send ICE candidate: {icemsg_value}')
172                     await self.websocket.send(icemsg)
173
174                 else:
175                     await asyncio.sleep(0.1)
176         finally:
177             self.pipe.set_state(Gst.State.NULL)
178
179     async def talk_to_websocket(self, uri):
180         async for msg in self.websocket:
181             msg_json = json.loads(msg)
182             msg_type = msg_json['Type']
183             msg_value = msg_json['Value']
184             assert self.session_id is None or self.session_id == msg_json['SessionID']
185             if msg_type == 'newSession':
186                 self.session_id = msg_json['SessionID']
187                 log.info(f"New session {self.session_id}")
188             elif msg_type == 'gotOffer':
189                 value_json = json.loads(msg_value)
190                 sdp = value_json['sdp']
191                 log.info(f'Got SDP offer:\n{sdp}')
192                 self.sdp_offer = sdp
193             elif msg_type == 'addCallerIceCandidate':
194                 value_json = json.loads(msg_value)
195                 log.info(f'Got ICE candidate: {value_json}')
196                 self.received_ice_candidates.put_nowait(value_json)
197             elif msg_type == 'roomNotFound':
198                 log.error(f'The room was not found: {uri}')
199                 return
200             elif msg_type == 'roomClosed':
201                 log.info(f'Oh noes, the room went away (session {self.session_id})!')
202                 self.session_id = None
203                 return
204             else:
205                 log.error(f'Unknown message type {msg_type}')
206
207     async def run(self, uri):
208         ssl_context = ssl.SSLContext()
209         ssl_context.check_hostname = False
210         ssl_context.verify_mode = ssl.CERT_NONE
211         try:
212             async with websockets.connect(uri, ssl=ssl_context) as self.websocket:
213                 talk_to_websocket_task = asyncio.Task(self.talk_to_websocket(uri))
214                 listen_to_gstreamer_bus_task = asyncio.Task(self.listen_to_gstreamer_bus())
215                 main_loop = asyncio.Task(gstreamer_main_loop())
216                 done, pending = await asyncio.wait(
217                     [talk_to_websocket_task, listen_to_gstreamer_bus_task, main_loop],
218                     return_when=asyncio.FIRST_COMPLETED)
219                 for d in done:
220                     d.result()
221                 for p in pending:
222                     p.cancel()
223         except OSError as e:
224             print(e)
225
226
227 async def gstreamer_main_loop():
228     """Does the equivalent of the following lines in an async friendly way:
229         loop = GLib.MainLoop()
230         loop.run()
231     """
232     gst_loop = GLib.MainLoop()
233     context = gst_loop.get_context()
234     while True:
235         events_dispatched = context.iteration(False)
236         await asyncio.sleep(0. if events_dispatched else 0.01)
237
238
239 def main():
240     logging.basicConfig(level=logging.INFO, format='%(asctime)-15s %(message)s')
241     parser = argparse.ArgumentParser()
242     parser.add_argument('--uri', default='wss://localhost:1234/ws_connect?id=cug',
243                         help='Signalling server URI')
244     args = parser.parse_args()
245
246     Gst.init(None)
247     rtsp = GstreamerRtspServer()
248     lagarde = Lagarde()
249     asyncio.run(lagarde.run(args.uri), debug=True)
250
251
252 if __name__ == '__main__':
253     main()