Add RTSP server with videotestsrc.
[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("videotestsrc ! 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('autovideosink') # needs XDG_RUNTIME_DIR
87                 sink = Gst.ElementFactory.make('xvimagesink')
88                 self.pipe.add(q)
89                 self.pipe.add(conv)
90                 self.pipe.add(sink)
91                 self.pipe.sync_children_states()
92                 pad.link(q.get_static_pad('sink'))
93                 q.link(conv)
94                 conv.link(sink)
95             elif name.startswith('audio'):
96                 q = Gst.ElementFactory.make('queue')
97                 conv = Gst.ElementFactory.make('audioconvert')
98                 resample = Gst.ElementFactory.make('audioresample')
99                 sink = Gst.ElementFactory.make('autoaudiosink')
100                 self.pipe.add(q)
101                 self.pipe.add(conv)
102                 self.pipe.add(resample)
103                 self.pipe.add(sink)
104                 self.pipe.sync_children_states()
105                 pad.link(q.get_static_pad('sink'))
106                 q.link(conv)
107                 conv.link(resample)
108                 resample.link(sink)
109
110     async def listen_to_gstreamer_bus(self):
111         self.webrtcbin = Gst.ElementFactory.make('webrtcbin', 'laplace')
112         self.pipe = Gst.Pipeline.new("pipeline")
113         Gst.Bin.do_add_element(self.pipe, self.webrtcbin)
114         bus = Gst.Pipeline.get_bus(self.pipe)
115         self.webrtcbin.connect('on-negotiation-needed', self.on_negotiation_needed)
116         self.webrtcbin.connect('on-ice-candidate', self.on_ice_candidate)
117         self.webrtcbin.connect('pad-added', self.webrtcbin_pad_added)
118         self.pipe.set_state(Gst.State.PLAYING)
119         try:
120             while True:
121                 if bus.have_pending():
122                     msg = bus.pop()
123                     if msg.type == Gst.MessageType.ERROR:
124                         log.error(f'Error from gstreamer message bus: {msg.get_structure()}')
125                         return
126                     elif msg.type == Gst.MessageType.EOS:  # end of stream
127                         log.info(f'Gstreamer message bus reports end of stream')
128                         return
129                 elif self.sdp_offer is not None:
130                     res, sm = GstSdp.SDPMessage.new()
131                     assert res == GstSdp.SDPResult.OK
132                     GstSdp.sdp_message_parse_buffer(bytes(self.sdp_offer.encode()), sm)
133                     # the three lines above can also be done this way in new versions of GStreamer:
134                     # sm = GstSdp.SDPMessage.new_from_text(sdp_offer)
135                     rd = GstWebRTC.WebRTCSessionDescription.new(GstWebRTC.WebRTCSDPType.OFFER, sm)
136                     gst_promise = Gst.Promise.new()
137                     self.webrtcbin.emit('set-remote-description', rd, gst_promise)
138                     await asyncio.get_event_loop().run_in_executor(None, gst_promise.wait)
139                     self.sdp_offer = None
140
141                     gst_promise = Gst.Promise.new()
142                     self.webrtcbin.emit('create-answer', None, gst_promise)
143                     result = await asyncio.get_event_loop().run_in_executor(None, gst_promise.wait)
144                     assert result == Gst.PromiseResult.REPLIED
145                     reply = gst_promise.get_reply()
146                     answer = reply.get_value('answer')
147                     sdp_message = answer.sdp
148                     self.user_fragments = [sdp_message.get_media(i).get_attribute_val('ice-ufrag')
149                                           for i in range(sdp_message.medias_len())]
150                     self.mids = [sdp_message.get_media(i).get_attribute_val('mid')
151                                           for i in range(sdp_message.medias_len())]
152                     sdp_answer = sdp_message.as_text()
153                     log.info(f'Send SDP answer:\n{sdp_answer}')
154                     sdp_answer_msg = json.dumps({
155                         'SessionID': self.session_id,
156                         'Type': "gotAnswer",
157                         'Value': json.dumps({
158                             'type': 'answer',
159                             'sdp': sdp_answer
160                         })
161                     })
162                     gst_promise = Gst.Promise.new()
163                     self.webrtcbin.emit('set-local-description', answer, gst_promise)
164                     await asyncio.get_event_loop().run_in_executor(None, gst_promise.wait)
165                     gst_promise.get_reply()
166                     await self.websocket.send(sdp_answer_msg)
167
168                 elif self.received_ice_candidates.qsize() > 0:
169                     ic = self.received_ice_candidates.get_nowait()
170                     if ic['candidate'] != '':
171                         self.webrtcbin.emit('add-ice-candidate', ic['sdpMLineIndex'], ic['candidate'])
172
173                 elif self.generated_ice_candidates.qsize() > 0:
174                     mlineindex, candidate = self.generated_ice_candidates.get_nowait()
175                     icemsg_value = json.dumps({
176                         "candidate": candidate,
177                         "sdpMid": self.mids[mlineindex],
178                         "sdpMLineIndex": mlineindex,
179                         "usernameFragment": self.user_fragments[mlineindex],
180                     })
181                     icemsg = json.dumps({
182                         'SessionID': self.session_id,
183                         'Type': 'addCalleeIceCandidate',
184                         'Value': icemsg_value,
185                     })
186                     log.info(f'Send ICE candidate: {icemsg_value}')
187                     await self.websocket.send(icemsg)
188
189                 else:
190                     await asyncio.sleep(0.1)
191         finally:
192             self.pipe.set_state(Gst.State.NULL)
193
194     async def talk_to_websocket(self, uri):
195         async for msg in self.websocket:
196             msg_json = json.loads(msg)
197             msg_type = msg_json['Type']
198             msg_value = msg_json['Value']
199             assert self.session_id is None or self.session_id == msg_json['SessionID']
200             if msg_type == 'newSession':
201                 self.session_id = msg_json['SessionID']
202                 log.info(f"New session {self.session_id}")
203             elif msg_type == 'gotOffer':
204                 value_json = json.loads(msg_value)
205                 sdp = value_json['sdp']
206                 log.info(f'Got SDP offer:\n{sdp}')
207                 self.sdp_offer = sdp
208             elif msg_type == 'addCallerIceCandidate':
209                 value_json = json.loads(msg_value)
210                 log.info(f'Got ICE candidate: {value_json}')
211                 self.received_ice_candidates.put_nowait(value_json)
212             elif msg_type == 'roomNotFound':
213                 log.error(f'The room was not found: {uri}')
214                 return
215             elif msg_type == 'roomClosed':
216                 log.info(f'Oh noes, the room went away (session {self.session_id})!')
217                 self.session_id = None
218                 return
219             else:
220                 log.error(f'Unknown message type {msg_type}')
221
222     async def run(self, uri):
223         ssl_context = ssl.SSLContext()
224         ssl_context.check_hostname = False
225         ssl_context.verify_mode = ssl.CERT_NONE
226         try:
227             async with websockets.connect(uri, ssl=ssl_context) as self.websocket:
228                 talk_to_websocket_task = asyncio.Task(self.talk_to_websocket(uri))
229                 listen_to_gstreamer_bus_task = asyncio.Task(self.listen_to_gstreamer_bus())
230                 main_loop = asyncio.Task(gstreamer_main_loop())
231                 done, pending = await asyncio.wait(
232                     [talk_to_websocket_task, listen_to_gstreamer_bus_task, main_loop],
233                     return_when=asyncio.FIRST_COMPLETED)
234                 for d in done:
235                     d.result()
236                 for p in pending:
237                     p.cancel()
238         except OSError as e:
239             print(e)
240
241
242 async def gstreamer_main_loop():
243     """Does the equivalent of the following lines in an async friendly way:
244         loop = GLib.MainLoop()
245         loop.run()
246     """
247     gst_loop = GLib.MainLoop()
248     context = gst_loop.get_context()
249     while True:
250         events_dispatched = context.iteration(False)
251         await asyncio.sleep(0. if events_dispatched else 0.01)
252
253
254 def main():
255     logging.basicConfig(level=logging.INFO, format='%(asctime)-15s %(message)s')
256     parser = argparse.ArgumentParser()
257     parser.add_argument('--uri', default='wss://localhost:1234/ws_connect?id=cug',
258                         help='Signalling server URI')
259     args = parser.parse_args()
260
261     Gst.init(None)
262     rtsp = GstreamerRtspServer()
263     lagarde = Lagarde()
264     asyncio.run(lagarde.run(args.uri), debug=True)
265
266
267 if __name__ == '__main__':
268     main()