-
Notifications
You must be signed in to change notification settings - Fork 199
/
WebGLSample.cs
430 lines (354 loc) · 12.3 KB
/
WebGLSample.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Unity.WebRTC;
using Unity.WebRTC.Samples;
using UnityEngine.UI;
using static Unity.WebRTC.MediaStream;
using Button = UnityEngine.UI.Button;
class WebGLSample : MonoBehaviour
{
#pragma warning disable 0649
[SerializeField]
private Button startButton;
[SerializeField]
private Button callButton;
[SerializeField]
private Button restartButton;
[SerializeField]
private Button hangUpButton;
[SerializeField]
private Text localCandidateId;
[SerializeField]
private Text remoteCandidateId;
[SerializeField]
private Camera cam;
[SerializeField]
private RawImage sourceImage;
[SerializeField]
private RawImage receiveImage;
[SerializeField]
private Transform rotateObject;
#pragma warning restore 0649
private RTCPeerConnection _pc1, _pc2;
private List<RTCRtpSender> pc1Senders;
private MediaStream videoStream, receiveStream;
private DelegateOnIceConnectionChange pc1OnIceConnectionChange;
private DelegateOnIceConnectionChange pc2OnIceConnectionChange;
private DelegateOnIceCandidate pc1OnIceCandidate;
private DelegateOnIceCandidate pc2OnIceCandidate;
private DelegateOnTrack pc2Ontrack;
private DelegateOnNegotiationNeeded pc1OnNegotiationNeeded;
private bool videoUpdateStarted;
private const int width = 1280;
private const int height = 720;
private void Awake()
{
WebRTC.Initialize(WebRTCSettings.EncoderType, WebRTCSettings.LimitTextureSize);
startButton.onClick.AddListener(OnStart);
callButton.onClick.AddListener(Call);
restartButton.onClick.AddListener(RestartIce);
hangUpButton.onClick.AddListener(HangUp);
receiveStream = new MediaStream();
}
private void OnDestroy()
{
WebRTC.Dispose();
}
private void Start()
{
pc1Senders = new List<RTCRtpSender>();
callButton.interactable = false;
restartButton.interactable = false;
hangUpButton.interactable = false;
pc1OnIceConnectionChange = state => { OnIceConnectionChange(_pc1, state); };
pc2OnIceConnectionChange = state => { OnIceConnectionChange(_pc2, state); };
pc1OnIceCandidate = candidate => { OnIceCandidate(_pc1, candidate); };
pc2OnIceCandidate = candidate => { OnIceCandidate(_pc2, candidate); };
pc2Ontrack = e => { receiveStream.AddTrack(e.Track); };
pc1OnNegotiationNeeded = () => { StartCoroutine(PeerNegotiationNeeded(_pc1)); };
receiveStream.OnAddTrack = e =>
{
if (e.Track is VideoStreamTrack track)
{
receiveImage.texture = track.InitializeReceiver(width, height);
receiveImage.color = Color.white;
}
};
}
private void OnStart()
{
startButton.interactable = false;
callButton.interactable = true;
if (videoStream == null)
{
#if !UNITY_WEBGL
Debug.LogWarning("UserMedia is only available in WebGL builds, this is equal to PeerConnectionSample");
videoStream = cam.CaptureStream(width, height, 1000000);
sourceImage.texture = cam.targetTexture;
sourceImage.color = Color.white;
#else
MediaStreamConstraints constraints = new MediaStreamConstraints();
videoStream = new MediaStream();
videoStream.AddUserMedia(constraints);
videoStream.OnAddTrack = e =>
{
if (e.Track is VideoStreamTrack track)
{
sourceImage.texture = track.InitializeReceiver(1280, 720);
sourceImage.color = Color.white;
}
};
#endif
}
}
private void Update()
{
if (rotateObject != null)
{
float t = Time.deltaTime;
rotateObject.Rotate(100 * t, 200 * t, 300 * t);
}
}
private static RTCConfiguration GetSelectedSdpSemantics()
{
RTCConfiguration config = default;
config.iceServers = new[] {new RTCIceServer {urls = new[] {"stun:stun.l.google.com:19302"}}};
return config;
}
private void OnIceConnectionChange(RTCPeerConnection pc, RTCIceConnectionState state)
{
Debug.Log($"{GetName(pc)} IceConnectionState: {state}");
if (state == RTCIceConnectionState.Connected || state == RTCIceConnectionState.Completed)
{
StartCoroutine(CheckStats(pc));
}
}
// Display the video codec that is actually used.
IEnumerator CheckStats(RTCPeerConnection pc)
{
yield return new WaitForSeconds(0.1f);
if (pc == null)
yield break;
var op = pc.GetStats();
yield return op;
if (op.IsError)
{
Debug.LogErrorFormat("RTCPeerConnection.GetStats failed: {0}", op.Error);
yield break;
}
RTCStatsReport report = op.Value;
RTCIceCandidatePairStats activeCandidatePairStats = null;
RTCIceCandidateStats remoteCandidateStats = null;
foreach (var transportStatus in report.Stats.Values.OfType<RTCTransportStats>())
{
if (report.Stats.TryGetValue(transportStatus.selectedCandidatePairId, out var tmp))
{
activeCandidatePairStats = tmp as RTCIceCandidatePairStats;
}
}
if (activeCandidatePairStats == null || string.IsNullOrEmpty(activeCandidatePairStats.remoteCandidateId))
{
yield break;
}
foreach (var iceCandidateStatus in report.Stats.Values.OfType<RTCIceCandidateStats>())
{
if (iceCandidateStatus.Id == activeCandidatePairStats.remoteCandidateId)
{
remoteCandidateStats = iceCandidateStatus;
}
}
if (remoteCandidateStats == null || string.IsNullOrEmpty(remoteCandidateStats.Id))
{
yield break;
}
Debug.Log($"{GetName(pc)} candidate stats Id:{remoteCandidateStats.Id}, Type:{remoteCandidateStats.candidateType}");
var updateText = GetName(pc) == "pc1" ? localCandidateId : remoteCandidateId;
updateText.text = remoteCandidateStats.Id;
}
IEnumerator PeerNegotiationNeeded(RTCPeerConnection pc)
{
var op = pc.CreateOffer();
yield return op;
if (!op.IsError)
{
if (pc.SignalingState != RTCSignalingState.Stable)
{
Debug.LogError($"{GetName(pc)} signaling state is not stable.");
yield break;
}
yield return StartCoroutine(OnCreateOfferSuccess(pc, op.Desc));
}
else
{
OnCreateSessionDescriptionError(op.Error);
}
}
private void AddTracks()
{
foreach (var track in videoStream.GetTracks())
{
pc1Senders.Add(_pc1.AddTrack(track, videoStream));
}
if (!videoUpdateStarted)
{
StartCoroutine(WebRTC.Update());
videoUpdateStarted = true;
}
}
private void RemoveTracks()
{
foreach (var sender in pc1Senders)
{
_pc1.RemoveTrack(sender);
}
pc1Senders.Clear();
MediaStreamTrack[] tracks = receiveStream.GetTracks().ToArray();
foreach (var track in tracks)
{
receiveStream.RemoveTrack(track);
track.Dispose();
}
}
private void Call()
{
callButton.interactable = false;
hangUpButton.interactable = true;
restartButton.interactable = true;
var configuration = GetSelectedSdpSemantics();
_pc1 = new RTCPeerConnection(ref configuration);
_pc1.OnIceCandidate = pc1OnIceCandidate;
_pc1.OnIceConnectionChange = pc1OnIceConnectionChange;
_pc1.OnNegotiationNeeded = pc1OnNegotiationNeeded;
_pc2 = new RTCPeerConnection(ref configuration);
_pc2.OnIceCandidate = pc2OnIceCandidate;
_pc2.OnIceConnectionChange = pc2OnIceConnectionChange;
_pc2.OnTrack = pc2Ontrack;
AddTracks();
}
private void RestartIce()
{
restartButton.interactable = false;
_pc1.RestartIce();
}
private void HangUp()
{
RemoveTracks();
_pc1.Close();
_pc2.Close();
_pc1.Dispose();
_pc2.Dispose();
_pc1 = null;
_pc2 = null;
callButton.interactable = true;
restartButton.interactable = false;
hangUpButton.interactable = false;
receiveImage.color = Color.black;
}
private void OnIceCandidate(RTCPeerConnection pc, RTCIceCandidate candidate)
{
GetOtherPc(pc).AddIceCandidate(candidate);
Debug.Log($"{GetName(pc)} ICE candidate:\n {candidate.Candidate}");
}
private string GetName(RTCPeerConnection pc)
{
return (pc == _pc1) ? "pc1" : "pc2";
}
private RTCPeerConnection GetOtherPc(RTCPeerConnection pc)
{
return (pc == _pc1) ? _pc2 : _pc1;
}
private IEnumerator OnCreateOfferSuccess(RTCPeerConnection pc, RTCSessionDescription desc)
{
Debug.Log($"Offer from {GetName(pc)}\n{desc.sdp}");
Debug.Log($"{GetName(pc)} setLocalDescription start");
var op = pc.SetLocalDescription(ref desc);
yield return op;
if (!op.IsError)
{
OnSetLocalSuccess(pc);
}
else
{
var error = op.Error;
OnSetSessionDescriptionError(ref error);
yield break;
}
var otherPc = GetOtherPc(pc);
Debug.Log($"{GetName(otherPc)} setRemoteDescription start");
var op2 = otherPc.SetRemoteDescription(ref desc);
yield return op2;
if (!op2.IsError)
{
OnSetRemoteSuccess(otherPc);
}
else
{
var error = op2.Error;
OnSetSessionDescriptionError(ref error);
yield break;
}
Debug.Log($"{GetName(otherPc)} createAnswer start");
// Since the 'remote' side has no media stream we need
// to pass in the right constraints in order for it to
// accept the incoming offer of audio and video.
var op3 = otherPc.CreateAnswer();
yield return op3;
if (!op3.IsError)
{
yield return OnCreateAnswerSuccess(otherPc, op3.Desc);
}
else
{
OnCreateSessionDescriptionError(op3.Error);
}
}
private void OnSetLocalSuccess(RTCPeerConnection pc)
{
Debug.Log($"{GetName(pc)} SetLocalDescription complete");
}
void OnSetSessionDescriptionError(ref RTCError error)
{
Debug.LogError($"Error Detail Type: {error.message}");
HangUp();
}
private void OnSetRemoteSuccess(RTCPeerConnection pc)
{
Debug.Log($"{GetName(pc)} SetRemoteDescription complete");
}
IEnumerator OnCreateAnswerSuccess(RTCPeerConnection pc, RTCSessionDescription desc)
{
Debug.Log($"Answer from {GetName(pc)}:\n{desc.sdp}");
Debug.Log($"{GetName(pc)} setLocalDescription start");
var op = pc.SetLocalDescription(ref desc);
yield return op;
if (!op.IsError)
{
OnSetLocalSuccess(pc);
}
else
{
var error = op.Error;
OnSetSessionDescriptionError(ref error);
}
var otherPc = GetOtherPc(pc);
Debug.Log($"{GetName(otherPc)} setRemoteDescription start");
var op2 = otherPc.SetRemoteDescription(ref desc);
yield return op2;
if (!op2.IsError)
{
OnSetRemoteSuccess(otherPc);
}
else
{
var error = op2.Error;
OnSetSessionDescriptionError(ref error);
}
}
private static void OnCreateSessionDescriptionError(RTCError error)
{
Debug.LogError($"Error Detail Type: {error.message}");
}
}