Gst.Bin.add() wants only one argument
[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')
76                 self.pipe.add(q)
77                 self.pipe.add(conv)
78                 self.pipe.add(sink)
79                 self.pipe.sync_children_states()
80                 pad.link(q.get_static_pad('sink'))
81                 q.link(conv)
82                 conv.link(sink)
83             elif name.startswith('audio'):
84                 q = Gst.ElementFactory.make('queue')
85                 conv = Gst.ElementFactory.make('audioconvert')
86                 resample = Gst.ElementFactory.make('audioresample')
87                 sink = Gst.ElementFactory.make('autoaudiosink')
88                 self.pipe.add(q)
89                 self.pipe.add(conv)
90                 self.pipe.add(resample)
91                 self.pipe.add(sink)
92                 self.pipe.sync_children_states()
93                 pad.link(q.get_static_pad('sink'))
94                 q.link(conv)
95                 conv.link(resample)
96                 resample.link(sink)
97
98     async def listen_to_gstreamer_bus(self):
99         Gst.init(None)
100         self.webrtcbin = Gst.ElementFactory.make('webrtcbin', 'laplace')
101         self.pipe = Gst.Pipeline.new("pipeline")
102         Gst.Bin.do_add_element(self.pipe, self.webrtcbin)
103         bus = Gst.Pipeline.get_bus(self.pipe)
104         self.webrtcbin.connect('on-negotiation-needed', self.on_negotiation_needed)
105         self.webrtcbin.connect('on-ice-candidate', self.on_ice_candidate)
106         self.webrtcbin.connect('pad-added', self.webrtcbin_pad_added)
107         self.pipe.set_state(Gst.State.PLAYING)
108         try:
109             while True:
110                 if bus.have_pending():
111                     msg = bus.pop()  # Gst.Message, has to be unref'ed.
112                     if msg.type != Gst.MessageType.STATE_CHANGED:
113                         # log.info(f'Receive Gst.Message: {msg.type}, {msg.seqnum}, {msg.get_structure()}')
114                         # log.info(f'{webrtcbin.props.signaling_state} {webrtcbin.props.ice_gathering_state} {webrtcbin.props.ice_connection_state}')
115                         # Gst.Message.unref(msg)
116                         pass
117                 elif self.sdp_offer is not None:
118                     res, sm = GstSdp.SDPMessage.new()
119                     assert res == GstSdp.SDPResult.OK
120                     GstSdp.sdp_message_parse_buffer(bytes(self.sdp_offer.encode()), sm)
121                     # the three lines above can also be done this way in new versions of GStreamer:
122                     # sm = GstSdp.SDPMessage.new_from_text(sdp_offer)
123                     rd = GstWebRTC.WebRTCSessionDescription.new(GstWebRTC.WebRTCSDPType.OFFER, sm)
124                     gst_promise = Gst.Promise.new()
125                     self.webrtcbin.emit('set-remote-description', rd, gst_promise)
126                     gst_promise.wait()
127                     self.sdp_offer = None
128
129                     log.info('create-answer')
130                     gst_promise = Gst.Promise.new()
131                     self.webrtcbin.emit('create-answer', None, gst_promise)
132                     result = gst_promise.wait()
133                     assert result == Gst.PromiseResult.REPLIED
134                     reply = gst_promise.get_reply()
135                     answer = reply.get_value('answer')
136                     sdp_message = answer.sdp
137                     self.user_fragments = [sdp_message.get_media(i).get_attribute_val('ice-ufrag')
138                                           for i in range(sdp_message.medias_len())]
139                     self.mids = [sdp_message.get_media(i).get_attribute_val('mid')
140                                           for i in range(sdp_message.medias_len())]
141                     sdp_answer = sdp_message.as_text()
142                     log.info(sdp_answer)
143                     sdp_answer_msg = json.dumps({
144                         'SessionID': self.session_id,
145                         'Type': "gotAnswer",
146                         'Value': json.dumps({
147                             'type': 'answer',
148                             'sdp': sdp_answer
149                         })
150                     })
151                     gst_promise = Gst.Promise.new()
152                     self.webrtcbin.emit('set-local-description', answer, gst_promise)
153                     gst_promise.wait()
154                     gst_promise.get_reply()
155                     await self.websocket.send(sdp_answer_msg)
156
157                 elif len(self.received_ice_candidates) > 0:
158                     ic = self.received_ice_candidates.pop(0)
159                     if ic['candidate'] != '':
160                         self.webrtcbin.emit('add-ice-candidate', ic['sdpMLineIndex'], ic['candidate'])
161
162                 elif len(self.generated_ice_candidates) > 0:
163                     mlineindex, candidate = self.generated_ice_candidates.pop(0)
164                     icemsg = json.dumps({
165                         'SessionID': self.session_id,
166                         'Type': 'addCalleeIceCandidate',
167                         'Value': json.dumps({
168                             "candidate": candidate,
169                             "sdpMid": self.mids[mlineindex],
170                             "sdpMLineIndex": mlineindex,
171                             "usernameFragment": self.user_fragments[mlineindex],
172                         })
173                     })
174                     log.info(f'send_ice_candidate_message with {icemsg}')
175                     await self.websocket.send(icemsg)
176
177                 else:
178                     await asyncio.sleep(0.1)
179         finally:
180             self.pipe.set_state(Gst.State.NULL)
181
182     async def talk_to_websocket(self, uri):
183         ssl_context = ssl.SSLContext()
184         ssl_context.check_hostname = False
185         ssl_context.verify_mode = ssl.CERT_NONE
186         async with websockets.connect(uri, ssl=ssl_context) as self.websocket:
187             async for msg in self.websocket:
188                 msg_json = json.loads(msg)
189                 msg_type = msg_json['Type']
190                 msg_value = msg_json['Value']
191                 self.session_id = msg_json['SessionID']
192                 log.info(f"receive for session {self.session_id} type {msg_type}")
193                 if msg_type == 'newSession':
194                     pass
195                 elif msg_type == 'gotOffer':
196                     value_json = json.loads(msg_value)
197                     sdp = value_json['sdp']
198                     log.info(f'SDP: {sdp}')
199                     self.sdp_offer = sdp
200                 elif msg_type == 'addCallerIceCandidate':
201                     value_json = json.loads(msg_value)
202                     log.info(f'ICE: {value_json}')
203                     self.received_ice_candidates.append(value_json)
204                 elif msg_type == 'roomClosed':
205                     log.info('Oh noes, the room went away!')
206                     # and here we should clean up
207                 else:
208                     log.error(f'Unknown message type {msg_type}')
209
210     async def run(self, uri):
211         talk_to_websocket_task = asyncio.Task(self.talk_to_websocket(uri))
212         listen_to_gstreamer_bus_task = asyncio.Task(self.listen_to_gstreamer_bus())
213         done, pending = await asyncio.wait(
214             [talk_to_websocket_task, listen_to_gstreamer_bus_task],
215             return_when=asyncio.FIRST_COMPLETED)
216         for d in done:
217             d.result()
218         for p in pending:
219             p.cancel()
220
221
222 def main():
223     logging.basicConfig(level=logging.INFO, format='%(asctime)-15s %(message)s')
224     parser = argparse.ArgumentParser()
225     parser.add_argument('--uri', default='wss://localhost:1234/ws_connect?id=cug',
226                         help='Signalling server URI')
227     args = parser.parse_args()
228     lagarde = Lagarde()
229     asyncio.run(lagarde.run(args.uri), debug=True)
230
231
232 if __name__ == '__main__':
233     main()