Clean up imports.
[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 from typing import Optional, List
9
10 import gi
11 import websockets
12
13 gi.require_version('Gst', '1.0')
14 from gi.repository import Gst
15
16 gi.require_version('GstWebRTC', '1.0')
17 from gi.repository import GstWebRTC
18
19 gi.require_version('GstSdp', '1.0')
20 from gi.repository import GstSdp
21
22 log = logging.getLogger(__name__)
23
24
25 class Lagarde:
26     def __init__(self):
27         self.sdp_offer: Optional[str] = None
28         self.websocket: Optional[websockets.client.WebSocketClientProtocol] = None
29         self.session_id = None
30         self.received_ice_candidates = []
31         self.generated_ice_candidates = []
32         self.user_fragments: Optional[List] = None
33         self.mids: Optional[List] = None
34         self.pipe = None
35         self.webrtcbin = None
36
37     def on_negotiation_needed(self, element):
38         log.info('on_negotiation_needed')
39
40     def on_ice_candidate(self, element, mlineindex, candidate):
41         log.info('on_ice_candidate')
42         self.generated_ice_candidates.append((mlineindex, candidate))
43
44     def webrtcbin_pad_added(self, element, pad):
45         log.info('webrtcbin_pad_added')
46         if pad.direction != Gst.PadDirection.SRC:
47             return
48         decodebin = Gst.ElementFactory.make('decodebin')
49         decodebin.connect('pad-added', self.decodebin_pad_added)
50         self.pipe.add(decodebin)
51         decodebin.sync_state_with_parent()
52         self.webrtcbin.link(decodebin)
53
54     def decodebin_pad_added(self, element, pad):
55         log.info('decodebin_pad_added')
56         if not pad.has_current_caps():
57             log.info(pad, 'has no caps, ignoring')
58             return
59
60         caps = pad.get_current_caps()
61         # assert (len(caps)) # we have a Gst.Caps object and it has no length
62         # s = caps[0] # also, it's not a list
63         padsize = caps.get_size()
64         assert(padsize > 0)
65         for i in range(padsize): # pythonic?!
66             s = caps.get_structure(i) # Gst.Structure
67             name = s.get_name()
68             if name.startswith('video'):
69                 q = Gst.ElementFactory.make('queue')
70                 conv = Gst.ElementFactory.make('videoconvert')
71                 # sink = Gst.ElementFactory.make('autovideosink') # needs XDG_RUNTIME_DIR
72                 sink = Gst.ElementFactory.make('xvimagesink')
73                 self.pipe.add(q)
74                 self.pipe.add(conv)
75                 self.pipe.add(sink)
76                 self.pipe.sync_children_states()
77                 pad.link(q.get_static_pad('sink'))
78                 q.link(conv)
79                 conv.link(sink)
80             elif name.startswith('audio'):
81                 q = Gst.ElementFactory.make('queue')
82                 conv = Gst.ElementFactory.make('audioconvert')
83                 resample = Gst.ElementFactory.make('audioresample')
84                 sink = Gst.ElementFactory.make('autoaudiosink')
85                 self.pipe.add(q)
86                 self.pipe.add(conv)
87                 self.pipe.add(resample)
88                 self.pipe.add(sink)
89                 self.pipe.sync_children_states()
90                 pad.link(q.get_static_pad('sink'))
91                 q.link(conv)
92                 conv.link(resample)
93                 resample.link(sink)
94
95     async def listen_to_gstreamer_bus(self):
96         Gst.init(None)
97         self.webrtcbin = Gst.ElementFactory.make('webrtcbin', 'laplace')
98         self.pipe = Gst.Pipeline.new("pipeline")
99         Gst.Bin.do_add_element(self.pipe, self.webrtcbin)
100         bus = Gst.Pipeline.get_bus(self.pipe)
101         self.webrtcbin.connect('on-negotiation-needed', self.on_negotiation_needed)
102         self.webrtcbin.connect('on-ice-candidate', self.on_ice_candidate)
103         self.webrtcbin.connect('pad-added', self.webrtcbin_pad_added)
104         self.pipe.set_state(Gst.State.PLAYING)
105         try:
106             while True:
107                 if bus.have_pending():
108                     msg = bus.pop()  # Gst.Message, has to be unref'ed.
109                     if msg.type != Gst.MessageType.STATE_CHANGED:
110                         # log.info(f'Receive Gst.Message: {msg.type}, {msg.seqnum}, {msg.get_structure()}')
111                         # log.info(f'{webrtcbin.props.signaling_state} {webrtcbin.props.ice_gathering_state} {webrtcbin.props.ice_connection_state}')
112                         # Gst.Message.unref(msg)
113                         pass
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                     gst_promise.wait()
124                     self.sdp_offer = None
125
126                     log.info('create-answer')
127                     gst_promise = Gst.Promise.new()
128                     self.webrtcbin.emit('create-answer', None, gst_promise)
129                     result = gst_promise.wait()
130                     assert result == Gst.PromiseResult.REPLIED
131                     reply = gst_promise.get_reply()
132                     answer = reply.get_value('answer')
133                     sdp_message = answer.sdp
134                     self.user_fragments = [sdp_message.get_media(i).get_attribute_val('ice-ufrag')
135                                           for i in range(sdp_message.medias_len())]
136                     self.mids = [sdp_message.get_media(i).get_attribute_val('mid')
137                                           for i in range(sdp_message.medias_len())]
138                     sdp_answer = sdp_message.as_text()
139                     log.info(sdp_answer)
140                     sdp_answer_msg = json.dumps({
141                         'SessionID': self.session_id,
142                         'Type': "gotAnswer",
143                         'Value': json.dumps({
144                             'type': 'answer',
145                             'sdp': sdp_answer
146                         })
147                     })
148                     gst_promise = Gst.Promise.new()
149                     self.webrtcbin.emit('set-local-description', answer, gst_promise)
150                     gst_promise.wait()
151                     gst_promise.get_reply()
152                     await self.websocket.send(sdp_answer_msg)
153
154                 elif len(self.received_ice_candidates) > 0:
155                     ic = self.received_ice_candidates.pop(0)
156                     if ic['candidate'] != '':
157                         self.webrtcbin.emit('add-ice-candidate', ic['sdpMLineIndex'], ic['candidate'])
158
159                 elif len(self.generated_ice_candidates) > 0:
160                     mlineindex, candidate = self.generated_ice_candidates.pop(0)
161                     icemsg = json.dumps({
162                         'SessionID': self.session_id,
163                         'Type': 'addCalleeIceCandidate',
164                         'Value': json.dumps({
165                             "candidate": candidate,
166                             "sdpMid": self.mids[mlineindex],
167                             "sdpMLineIndex": mlineindex,
168                             "usernameFragment": self.user_fragments[mlineindex],
169                         })
170                     })
171                     log.info(f'send_ice_candidate_message with {icemsg}')
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         ssl_context = ssl.SSLContext()
181         ssl_context.check_hostname = False
182         ssl_context.verify_mode = ssl.CERT_NONE
183         async with websockets.connect(uri, ssl=ssl_context) as self.websocket:
184             async for msg in self.websocket:
185                 msg_json = json.loads(msg)
186                 msg_type = msg_json['Type']
187                 msg_value = msg_json['Value']
188                 self.session_id = msg_json['SessionID']
189                 log.info(f"receive for session {self.session_id} type {msg_type}")
190                 if msg_type == 'newSession':
191                     pass
192                 elif msg_type == 'gotOffer':
193                     value_json = json.loads(msg_value)
194                     sdp = value_json['sdp']
195                     log.info(f'SDP: {sdp}')
196                     self.sdp_offer = sdp
197                 elif msg_type == 'addCallerIceCandidate':
198                     value_json = json.loads(msg_value)
199                     log.info(f'ICE: {value_json}')
200                     self.received_ice_candidates.append(value_json)
201                 elif msg_type == 'roomClosed':
202                     log.info('Oh noes, the room went away!')
203                     # and here we should clean up
204                 else:
205                     log.error(f'Unknown message type {msg_type}')
206
207     async def run(self, uri):
208         talk_to_websocket_task = asyncio.Task(self.talk_to_websocket(uri))
209         listen_to_gstreamer_bus_task = asyncio.Task(self.listen_to_gstreamer_bus())
210         done, pending = await asyncio.wait(
211             [talk_to_websocket_task, listen_to_gstreamer_bus_task],
212             return_when=asyncio.FIRST_COMPLETED)
213         for d in done:
214             d.result()
215         for p in pending:
216             p.cancel()
217
218
219 def main():
220     logging.basicConfig(level=logging.INFO, format='%(asctime)-15s %(message)s')
221     parser = argparse.ArgumentParser()
222     parser.add_argument('--uri', default='wss://localhost:1234/ws_connect?id=cug',
223                         help='Signalling server URI')
224     args = parser.parse_args()
225     lagarde = Lagarde()
226     asyncio.run(lagarde.run(args.uri), debug=True)
227
228
229 if __name__ == '__main__':
230     main()