add back (commented out ) bundle
[toast/stream2beamer.git] / laplace_client.py
1 #!/usr/bin/python3
2
3 import argparse
4 import asyncio
5 import json
6 import logging
7 import pathlib
8 import ssl
9 import sys
10
11 import websockets
12
13 import gi
14 gi.require_version('Gst', '1.0')
15 from gi.repository import Gst
16 gi.require_version('GstWebRTC', '1.0')
17 from gi.repository import GstWebRTC
18 gi.require_version('GstSdp', '1.0')
19 from gi.repository import GstSdp
20
21
22 log = logging.getLogger(__name__)
23
24
25 class WebRTCClient:
26
27     def __init__(self, uri: str):
28         self.uri = uri
29         self.ssl_context = ssl.SSLContext()
30         self.ssl_context.check_hostname = False
31         self.ssl_context.verify_mode = ssl.CERT_NONE
32         self.websocket = None
33         self.session_id = None
34
35     def send_sdp_offer(self, offer):
36         text = offer.sdp.as_text()
37         log.info(f'send_sdp_offer with {text}')
38         msg = json.dumps({
39             'SessionID': self.session_id,
40             'Type': "gotAnswer",
41             'Value': json.dumps({
42                 'type': 'answer',
43                 'sdp': text
44             })
45         })
46         loop = asyncio.new_event_loop()
47         loop.run_until_complete(self.websocket.send(msg))
48         loop.close()
49
50     def on_offer_created(self, promise, _, __):
51         log.info('on_offer_created')
52         promise.wait()
53         reply = promise.get_reply()
54         offer = reply.get_value('offer')
55         promise = Gst.Promise.new()
56         self.webrtc.emit('set-local-description', offer, promise)
57         promise.interrupt()
58         self.send_sdp_offer(offer)
59
60     def on_negotiation_needed(self, element):
61         log.info('on_negotiation_needed')
62         promise = Gst.Promise.new_with_change_func(self.on_offer_created, element, None)
63         element.emit('create-offer', None, promise)
64
65     def send_ice_candidate_message(self, _, mlineindex, candidate):
66         icemsg = json.dumps({
67             'SessionID': self.session_id,
68             'Type': 'addCalleeIceCandidate',
69             'Value': json.dumps({
70                 "candidate": candidate,
71                 "sdpMid": "0",
72                 "sdpMLineIndex": mlineindex,
73                 })
74             })
75         log.info(f'send_ice_candidate_message with {icemsg}')
76         loop = asyncio.new_event_loop()
77         loop.run_until_complete(self.websocket.send(icemsg))
78         loop.close()
79
80     def on_incoming_decodebin_stream(self, _, pad):
81         log.info('on_incoming_decodebin_stream')
82         if not pad.has_current_caps():
83             log.info(pad, 'has no caps, ignoring')
84             return
85
86         caps = pad.get_current_caps()
87         assert (len(caps))
88         s = caps[0]
89         name = s.get_name()
90         if name.startswith('video'):
91             q = Gst.ElementFactory.make('queue')
92             conv = Gst.ElementFactory.make('videoconvert')
93             sink = Gst.ElementFactory.make('autovideosink')
94             self.pipe.add(q, conv, sink)
95             self.pipe.sync_children_states()
96             pad.link(q.get_static_pad('sink'))
97             q.link(conv)
98             conv.link(sink)
99         elif name.startswith('audio'):
100             q = Gst.ElementFactory.make('queue')
101             conv = Gst.ElementFactory.make('audioconvert')
102             resample = Gst.ElementFactory.make('audioresample')
103             sink = Gst.ElementFactory.make('autoaudiosink')
104             self.pipe.add(q, conv, resample, sink)
105             self.pipe.sync_children_states()
106             pad.link(q.get_static_pad('sink'))
107             q.link(conv)
108             conv.link(resample)
109             resample.link(sink)
110
111     def on_incoming_stream(self, _, pad):
112         log.info('on_incoming_stream')
113         if pad.direction != Gst.PadDirection.SRC:
114             return
115         decodebin = Gst.ElementFactory.make('decodebin')
116         decodebin.connect('pad-added', self.on_incoming_decodebin_stream)
117         self.pipe.add(decodebin)
118         decodebin.sync_state_with_parent()
119         self.webrtc.link(decodebin)
120
121     def start_pipeline(self):
122         self.webrtc = Gst.ElementFactory.make('webrtcbin', 'laplace')
123         # self.webrtc.set_property("bundle-policy", 3)
124         direction = GstWebRTC.WebRTCRTPTransceiverDirection.RECVONLY
125         video_caps = Gst.caps_from_string("application/x-rtp,media=video,encoding-name=VP8/9000,payload=96")
126         audio_caps = Gst.caps_from_string("application/x-rtp,media=audio,encoding-name=OPUS,clock-rate=48000,payload=111")
127         self.webrtc.emit('add-transceiver', direction, video_caps)
128         self.webrtc.emit('add-transceiver', direction, audio_caps)
129         self.pipe = Gst.Pipeline.new("pipeline")
130         Gst.Bin.do_add_element(self.pipe, self.webrtc)
131         self.webrtc.connect('on-negotiation-needed', self.on_negotiation_needed)
132         self.webrtc.connect('on-ice-candidate', self.send_ice_candidate_message)
133         self.webrtc.connect('pad-added', self.on_incoming_stream)
134         self.pipe.set_state(Gst.State.PLAYING)
135         self.webrtc.emit('create-data-channel', 'laplace', None)
136     
137     def close_pipeline(self):
138         self.pipe.set_state(Gst.State.NULL)
139         self.pipe = None
140         self.webrtc = None
141     
142     def handle_sdp(self, sdp):
143         log.info(f'handle_sdp: {sdp}')
144         res, sdpmsg = GstSdp.SDPMessage.new()
145         GstSdp.sdp_message_parse_buffer(bytes(sdp.encode()), sdpmsg)
146         answer = GstWebRTC.WebRTCSessionDescription.new(GstWebRTC.WebRTCSDPType.ANSWER, sdpmsg)
147         promise = Gst.Promise.new()
148         self.webrtc.emit('set-remote-description', answer, promise)
149         promise.interrupt()
150
151     def handle_ice(self, ice):
152         log.info(f'handle_ice: {ice}')
153         candidate = ice['candidate']
154         sdpmlineindex = ice['sdpMLineIndex']
155         self.webrtc.emit('add-ice-candidate', sdpmlineindex, candidate)
156
157     async def run(self):
158         async with websockets.connect(self.uri, ssl=self.ssl_context) as websocket:
159             self.websocket = websocket
160             self.start_pipeline()
161             async for msg in websocket:
162                 msg_json = json.loads(msg)
163                 msg_type = msg_json['Type']
164                 msg_value = msg_json['Value']
165                 session_id = msg_json['SessionID']
166                 log.info(f"receive for session {session_id} type {msg_type}")
167                 if msg_type == 'newSession':
168                     self.session_id = session_id
169                 elif msg_type == 'gotOffer':
170                     value_json = json.loads(msg_value)
171                     sdp = value_json['sdp']
172                     self.handle_sdp(sdp)
173                 elif msg_type == 'addCallerIceCandidate':
174                     value_json = json.loads(msg_value)
175                     self.handle_ice(value_json)
176         self.close_pipeline()
177         self.websocket = None
178         self.session_id = None
179
180
181 def check_plugins():
182     for plugin in ["opus", "vpx", "nice", "webrtc", "dtls", "srtp", "rtp",
183                    "rtpmanager", "videotestsrc", "audiotestsrc"]:
184         if Gst.Registry.get().find_plugin(plugin) is None:
185             print('Missing gstreamer plugin:', plugin)
186             return False
187     return True
188
189
190 def main():
191     logging.basicConfig(level=logging.INFO, format='%(asctime)-15s %(message)s')
192     Gst.init(None)
193     if not check_plugins():
194         sys.exit(1)
195     parser = argparse.ArgumentParser()
196     parser.add_argument('--uri', default='wss://localhost:2222/ws_connect?id=cug',
197         help='Signalling server URI')
198     args = parser.parse_args()
199     c = WebRTCClient(args.uri)
200     loop = asyncio.get_event_loop()
201     loop.run_until_complete(c.run())
202
203
204 if __name__=='__main__':
205     main()