blob: 42ac308e04ee39aaf5a75315f1d8de5a5ed32fa0 [file] [log] [blame]
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -05001/*
2 * Copyright (C) 2022 Savoir-faire Linux Inc.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU Affero General Public License as
6 * published by the Free Software Foundation; either version 3 of the
7 * License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU Affero General Public License for more details.
13 *
14 * You should have received a copy of the GNU Affero General Public
15 * License along with this program. If not, see
16 * <https://www.gnu.org/licenses/>.
17 */
18
19import { WebRtcIceCandidate, WebRtcSdp, WebSocketMessageType } from 'jami-web-common';
20import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
21
simonf353ef42022-11-28 23:14:53 -050022import LoadingPage from '../components/Loading';
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -050023import { WithChildren } from '../utils/utils';
simon71d1c0a2022-11-24 15:28:33 -050024import { useAuthContext } from './AuthProvider';
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -050025import { ConversationContext } from './ConversationProvider';
simonf353ef42022-11-28 23:14:53 -050026import { IWebSocketContext, WebSocketContext } from './WebSocketProvider';
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -050027
28interface IWebRtcContext {
Charlieb837e8f2022-11-28 19:18:46 -050029 iceConnectionState: RTCIceConnectionState | undefined;
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -050030
simon9076a9a2022-11-29 17:13:01 -050031 mediaDevices: Record<MediaDeviceKind, MediaDeviceInfo[]>;
32 localStream: MediaStream | undefined;
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -050033 remoteStreams: readonly MediaStream[] | undefined;
simon9076a9a2022-11-29 17:13:01 -050034 getUserMedia: () => Promise<void>;
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -050035
simon9076a9a2022-11-29 17:13:01 -050036 sendWebRtcOffer: () => Promise<void>;
37 closeConnection: () => void;
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -050038}
39
40const defaultWebRtcContext: IWebRtcContext = {
Charlieb837e8f2022-11-28 19:18:46 -050041 iceConnectionState: undefined,
simon9076a9a2022-11-29 17:13:01 -050042 mediaDevices: {
43 audioinput: [],
44 audiooutput: [],
45 videoinput: [],
46 },
47 localStream: undefined,
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -050048 remoteStreams: undefined,
simon9076a9a2022-11-29 17:13:01 -050049 getUserMedia: async () => {},
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -050050 sendWebRtcOffer: async () => {},
simon9076a9a2022-11-29 17:13:01 -050051 closeConnection: () => {},
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -050052};
53
54export const WebRtcContext = createContext<IWebRtcContext>(defaultWebRtcContext);
55
56export default ({ children }: WithChildren) => {
simon71d1c0a2022-11-24 15:28:33 -050057 const { account } = useAuthContext();
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -050058 const [webRtcConnection, setWebRtcConnection] = useState<RTCPeerConnection | undefined>();
simonf353ef42022-11-28 23:14:53 -050059 const webSocket = useContext(WebSocketContext);
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -050060
61 useEffect(() => {
simon71d1c0a2022-11-24 15:28:33 -050062 if (!webRtcConnection && account) {
63 const iceServers: RTCIceServer[] = [];
64
65 if (account.getDetails()['TURN.enable'] === 'true') {
66 iceServers.push({
67 urls: 'turn:' + account.getDetails()['TURN.server'],
68 username: account.getDetails()['TURN.username'],
69 credential: account.getDetails()['TURN.password'],
70 });
71 }
72
73 if (account.getDetails()['STUN.enable'] === 'true') {
74 iceServers.push({
75 urls: 'stun:' + account.getDetails()['STUN.server'],
76 });
77 }
78
simon9076a9a2022-11-29 17:13:01 -050079 setWebRtcConnection(new RTCPeerConnection({ iceServers }));
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -050080 }
simon71d1c0a2022-11-24 15:28:33 -050081 }, [account, webRtcConnection]);
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -050082
simonf353ef42022-11-28 23:14:53 -050083 if (!webRtcConnection || !webSocket) {
84 return <LoadingPage />;
85 }
86
87 return (
88 <WebRtcProvider webRtcConnection={webRtcConnection} webSocket={webSocket}>
89 {children}
90 </WebRtcProvider>
91 );
92};
93
94const WebRtcProvider = ({
95 children,
96 webRtcConnection,
97 webSocket,
98}: WithChildren & {
99 webRtcConnection: RTCPeerConnection;
100 webSocket: IWebSocketContext;
101}) => {
102 const { conversation, conversationId } = useContext(ConversationContext);
simon9076a9a2022-11-29 17:13:01 -0500103 const [localStream, setLocalStream] = useState<MediaStream>();
simonf353ef42022-11-28 23:14:53 -0500104 const [remoteStreams, setRemoteStreams] = useState<readonly MediaStream[]>();
Charlieb837e8f2022-11-28 19:18:46 -0500105 const [iceConnectionState, setIceConnectionState] = useState<RTCIceConnectionState | undefined>();
simon9076a9a2022-11-29 17:13:01 -0500106 const [mediaDevices, setMediaDevices] = useState<Record<MediaDeviceKind, MediaDeviceInfo[]>>(
107 defaultWebRtcContext.mediaDevices
108 );
simonf353ef42022-11-28 23:14:53 -0500109
110 // TODO: This logic will have to change to support multiple people in a call
111 const contactUri = useMemo(() => conversation.getFirstMember().contact.getUri(), [conversation]);
112
simon9076a9a2022-11-29 17:13:01 -0500113 const getMediaDevices = useCallback(async () => {
114 try {
115 const devices = await navigator.mediaDevices.enumerateDevices();
116 const newMediaDevices: Record<MediaDeviceKind, MediaDeviceInfo[]> = {
117 audioinput: [],
118 audiooutput: [],
119 videoinput: [],
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500120 };
121
simon9076a9a2022-11-29 17:13:01 -0500122 for (const device of devices) {
123 newMediaDevices[device.kind].push(device);
124 }
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500125
simon9076a9a2022-11-29 17:13:01 -0500126 return newMediaDevices;
127 } catch (e) {
128 throw new Error('Could not get media devices', { cause: e });
129 }
130 }, []);
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500131
simon9076a9a2022-11-29 17:13:01 -0500132 useEffect(() => {
133 if (iceConnectionState !== 'connected' && iceConnectionState !== 'completed') {
134 return;
135 }
136
137 const updateMediaDevices = async () => {
138 try {
139 const newMediaDevices = await getMediaDevices();
140 setMediaDevices(newMediaDevices);
141 } catch (e) {
142 console.error('Could not update media devices:', e);
143 }
144 };
145
146 navigator.mediaDevices.addEventListener('devicechange', updateMediaDevices);
147 updateMediaDevices();
148
149 return () => {
150 navigator.mediaDevices.removeEventListener('devicechange', updateMediaDevices);
151 };
152 }, [getMediaDevices, iceConnectionState]);
153
154 const getUserMedia = useCallback(async () => {
155 const devices = await getMediaDevices();
156
157 const shouldGetAudio = devices.audioinput.length !== 0;
158 const shouldGetVideo = devices.videoinput.length !== 0;
159
160 if (!shouldGetAudio && !shouldGetVideo) {
161 return;
162 }
163
164 try {
165 const stream = await navigator.mediaDevices.getUserMedia({
166 audio: shouldGetAudio,
167 video: shouldGetVideo,
168 });
169
170 for (const track of stream.getTracks()) {
171 track.enabled = false;
172 webRtcConnection.addTrack(track, stream);
173 }
174
175 setLocalStream(stream);
176 } catch (e) {
177 throw new Error('Could not get media devices', { cause: e });
178 }
179 }, [webRtcConnection, getMediaDevices]);
180
181 const sendWebRtcOffer = useCallback(async () => {
182 const sdp = await webRtcConnection.createOffer({
183 offerToReceiveAudio: true,
184 offerToReceiveVideo: true,
185 });
186
187 const webRtcOffer: WebRtcSdp = {
188 contactId: contactUri,
189 conversationId: conversationId,
190 sdp,
191 };
192
193 await webRtcConnection.setLocalDescription(new RTCSessionDescription(sdp));
194 console.info('Sending WebRtcOffer', webRtcOffer);
195 webSocket.send(WebSocketMessageType.WebRtcOffer, webRtcOffer);
196 }, [webRtcConnection, webSocket, conversationId, contactUri]);
197
198 const sendWebRtcAnswer = useCallback(async () => {
199 const sdp = await webRtcConnection.createAnswer({
200 offerToReceiveAudio: true,
201 offerToReceiveVideo: true,
202 });
203
204 const webRtcAnswer: WebRtcSdp = {
205 contactId: contactUri,
206 conversationId: conversationId,
207 sdp,
208 };
209
210 await webRtcConnection.setLocalDescription(new RTCSessionDescription(sdp));
211 console.info('Sending WebRtcAnswer', webRtcAnswer);
212 webSocket.send(WebSocketMessageType.WebRtcAnswer, webRtcAnswer);
213 }, [contactUri, conversationId, webRtcConnection, webSocket]);
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500214
simonf353ef42022-11-28 23:14:53 -0500215 /* WebSocket Listeners */
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500216
simonf353ef42022-11-28 23:14:53 -0500217 useEffect(() => {
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500218 const webRtcOfferListener = async (data: WebRtcSdp) => {
219 console.info('Received event on WebRtcOffer', data);
Charliec18d6402022-11-27 13:01:04 -0500220 if (data.conversationId !== conversationId) {
221 console.warn('Wrong incoming conversationId, ignoring action');
222 return;
223 }
224
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500225 await webRtcConnection.setRemoteDescription(new RTCSessionDescription(data.sdp));
simon9076a9a2022-11-29 17:13:01 -0500226 await sendWebRtcAnswer();
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500227 };
228
229 const webRtcAnswerListener = async (data: WebRtcSdp) => {
230 console.info('Received event on WebRtcAnswer', data);
Charliec18d6402022-11-27 13:01:04 -0500231 if (data.conversationId !== conversationId) {
232 console.warn('Wrong incoming conversationId, ignoring action');
233 return;
234 }
235
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500236 await webRtcConnection.setRemoteDescription(new RTCSessionDescription(data.sdp));
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500237 };
simon9076a9a2022-11-29 17:13:01 -0500238
simonf353ef42022-11-28 23:14:53 -0500239 webSocket.bind(WebSocketMessageType.WebRtcOffer, webRtcOfferListener);
240 webSocket.bind(WebSocketMessageType.WebRtcAnswer, webRtcAnswerListener);
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500241
simonf353ef42022-11-28 23:14:53 -0500242 return () => {
243 webSocket.unbind(WebSocketMessageType.WebRtcOffer, webRtcOfferListener);
244 webSocket.unbind(WebSocketMessageType.WebRtcAnswer, webRtcAnswerListener);
245 };
246 }, [webSocket, webRtcConnection, sendWebRtcAnswer, conversationId]);
247
248 useEffect(() => {
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500249 const webRtcIceCandidateListener = async (data: WebRtcIceCandidate) => {
Charliec18d6402022-11-27 13:01:04 -0500250 if (data.conversationId !== conversationId) {
251 console.warn('Wrong incoming conversationId, ignoring action');
252 return;
253 }
254
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500255 await webRtcConnection.addIceCandidate(data.candidate);
256 };
257
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500258 webSocket.bind(WebSocketMessageType.WebRtcIceCandidate, webRtcIceCandidateListener);
259
260 return () => {
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500261 webSocket.unbind(WebSocketMessageType.WebRtcIceCandidate, webRtcIceCandidateListener);
262 };
simonf353ef42022-11-28 23:14:53 -0500263 }, [webRtcConnection, webSocket, conversationId]);
264
265 /* WebRTC Listeners */
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500266
267 useEffect(() => {
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500268 const iceCandidateEventListener = (event: RTCPeerConnectionIceEvent) => {
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500269 if (event.candidate) {
270 const webRtcIceCandidate: WebRtcIceCandidate = {
271 contactId: contactUri,
Charliec18d6402022-11-27 13:01:04 -0500272 conversationId: conversationId,
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500273 candidate: event.candidate,
274 };
275
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500276 webSocket.send(WebSocketMessageType.WebRtcIceCandidate, webRtcIceCandidate);
277 }
278 };
simonf353ef42022-11-28 23:14:53 -0500279 webRtcConnection.addEventListener('icecandidate', iceCandidateEventListener);
280
281 return () => {
282 webRtcConnection.removeEventListener('icecandidate', iceCandidateEventListener);
283 };
284 }, [webRtcConnection, webSocket, contactUri, conversationId]);
285
286 useEffect(() => {
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500287 const trackEventListener = (event: RTCTrackEvent) => {
288 console.info('Received WebRTC event on track', event);
289 setRemoteStreams(event.streams);
290 };
291
simon9076a9a2022-11-29 17:13:01 -0500292 const iceConnectionStateChangeEventListener = (event: Event) => {
293 console.info(`Received WebRTC event on iceconnectionstatechange: ${webRtcConnection.iceConnectionState}`, event);
Charlieb837e8f2022-11-28 19:18:46 -0500294 setIceConnectionState(webRtcConnection.iceConnectionState);
simonfeaa1db2022-11-26 20:13:18 -0500295 };
296
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500297 webRtcConnection.addEventListener('track', trackEventListener);
MichelleSS55164202022-11-25 18:36:14 -0500298 webRtcConnection.addEventListener('iceconnectionstatechange', iceConnectionStateChangeEventListener);
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500299
300 return () => {
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500301 webRtcConnection.removeEventListener('track', trackEventListener);
MichelleSS55164202022-11-25 18:36:14 -0500302 webRtcConnection.removeEventListener('iceconnectionstatechange', iceConnectionStateChangeEventListener);
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500303 };
simonf353ef42022-11-28 23:14:53 -0500304 }, [webRtcConnection]);
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500305
simon9076a9a2022-11-29 17:13:01 -0500306 const closeConnection = useCallback(() => {
307 const localTracks = localStream?.getTracks();
308 if (localTracks) {
309 for (const track of localTracks) {
310 track.stop();
311 }
312 }
313
314 webRtcConnection.close();
315 }, [webRtcConnection, localStream]);
316
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500317 return (
318 <WebRtcContext.Provider
319 value={{
Charlieb837e8f2022-11-28 19:18:46 -0500320 iceConnectionState,
simon9076a9a2022-11-29 17:13:01 -0500321 mediaDevices,
322 localStream,
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500323 remoteStreams,
simon9076a9a2022-11-29 17:13:01 -0500324 getUserMedia,
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500325 sendWebRtcOffer,
simon9076a9a2022-11-29 17:13:01 -0500326 closeConnection,
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500327 }}
328 >
329 {children}
330 </WebRtcContext.Provider>
331 );
332};