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