|
@@ -0,0 +1,600 @@
|
|
1
|
+// Copyright Epic Games, Inc. All Rights Reserved.
|
|
2
|
+
|
|
3
|
+function webRtcPlayer(parOptions) {
|
|
4
|
+ parOptions = typeof parOptions !== 'undefined' ? parOptions : {};
|
|
5
|
+
|
|
6
|
+ var self = this;
|
|
7
|
+ const urlParams = new URLSearchParams(window.location.search);
|
|
8
|
+
|
|
9
|
+ //**********************
|
|
10
|
+ //Config setup
|
|
11
|
+ //**********************
|
|
12
|
+ this.cfg = typeof parOptions.peerConnectionOptions !== 'undefined' ? parOptions.peerConnectionOptions : {};
|
|
13
|
+ this.cfg.sdpSemantics = 'unified-plan';
|
|
14
|
+ // this.cfg.rtcAudioJitterBufferMaxPackets = 10;
|
|
15
|
+ // this.cfg.rtcAudioJitterBufferFastAccelerate = true;
|
|
16
|
+ // this.cfg.rtcAudioJitterBufferMinDelayMs = 0;
|
|
17
|
+
|
|
18
|
+ // If this is true in Chrome 89+ SDP is sent that is incompatible with UE Pixel Streaming 4.26 and below.
|
|
19
|
+ // However 4.27 Pixel Streaming does not need this set to false as it supports `offerExtmapAllowMixed`.
|
|
20
|
+ // tdlr; uncomment this line for older versions of Pixel Streaming that need Chrome 89+.
|
|
21
|
+ this.cfg.offerExtmapAllowMixed = false;
|
|
22
|
+
|
|
23
|
+ this.forceTURN = urlParams.has('ForceTURN');
|
|
24
|
+ if (this.forceTURN) {
|
|
25
|
+ console.log("Forcing TURN usage by setting ICE Transport Policy in peer connection config.");
|
|
26
|
+ this.cfg.iceTransportPolicy = "relay";
|
|
27
|
+ }
|
|
28
|
+
|
|
29
|
+ this.cfg.bundlePolicy = "balanced";
|
|
30
|
+ this.forceMaxBundle = urlParams.has('ForceMaxBundle');
|
|
31
|
+ if (this.forceMaxBundle) {
|
|
32
|
+ this.cfg.bundlePolicy = "max-bundle";
|
|
33
|
+ }
|
|
34
|
+
|
|
35
|
+ //**********************
|
|
36
|
+ //Variables
|
|
37
|
+ //**********************
|
|
38
|
+ this.pcClient = null;
|
|
39
|
+ this.dcClient = null;
|
|
40
|
+ this.tnClient = null;
|
|
41
|
+
|
|
42
|
+ this.sdpConstraints = {
|
|
43
|
+ offerToReceiveAudio: 1, //Note: if you don't need audio you can get improved latency by turning this off.
|
|
44
|
+ offerToReceiveVideo: 1,
|
|
45
|
+ voiceActivityDetection: false
|
|
46
|
+ };
|
|
47
|
+
|
|
48
|
+ // See https://www.w3.org/TR/webrtc/#dom-rtcdatachannelinit for values (this is needed for Firefox to be consistent with Chrome.)
|
|
49
|
+ this.dataChannelOptions = { ordered: true };
|
|
50
|
+
|
|
51
|
+ // This is useful if the video/audio needs to autoplay (without user input) as browsers do not allow autoplay non-muted of sound sources without user interaction.
|
|
52
|
+ this.startVideoMuted = typeof parOptions.startVideoMuted !== 'undefined' ? parOptions.startVideoMuted : false;
|
|
53
|
+ this.autoPlayAudio = typeof parOptions.autoPlayAudio !== 'undefined' ? parOptions.autoPlayAudio : true;
|
|
54
|
+
|
|
55
|
+ // To enable mic in browser use SSL/localhost and have ?useMic in the query string.
|
|
56
|
+ this.useMic = urlParams.has('useMic');
|
|
57
|
+ if (!this.useMic) {
|
|
58
|
+ console.log("Microphone access is not enabled. Pass ?useMic in the url to enable it.");
|
|
59
|
+ }
|
|
60
|
+
|
|
61
|
+ // When ?useMic check for SSL or localhost
|
|
62
|
+ let isLocalhostConnection = location.hostname === "localhost" || location.hostname === "127.0.0.1";
|
|
63
|
+ let isHttpsConnection = location.protocol === 'https:';
|
|
64
|
+ if (this.useMic && !isLocalhostConnection && !isHttpsConnection) {
|
|
65
|
+ this.useMic = false;
|
|
66
|
+ console.error("Microphone access in the browser will not work if you are not on HTTPS or localhost. Disabling mic access.");
|
|
67
|
+ console.error("For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'");
|
|
68
|
+ }
|
|
69
|
+
|
|
70
|
+ // Prefer SFU or P2P connection
|
|
71
|
+ this.preferSFU = urlParams.has('preferSFU');
|
|
72
|
+ console.log(this.preferSFU ?
|
|
73
|
+ "The browser will signal it would prefer an SFU connection. Remove ?preferSFU from the url to signal for P2P usage." :
|
|
74
|
+ "The browser will signal for a P2P connection. Pass ?preferSFU in the url to signal for SFU usage.");
|
|
75
|
+
|
|
76
|
+ // Latency tester
|
|
77
|
+ this.latencyTestTimings =
|
|
78
|
+ {
|
|
79
|
+ TestStartTimeMs: null,
|
|
80
|
+ UEReceiptTimeMs: null,
|
|
81
|
+ UEEncodeMs: null,
|
|
82
|
+ UECaptureToSendMs: null,
|
|
83
|
+ UETransmissionTimeMs: null,
|
|
84
|
+ BrowserReceiptTimeMs: null,
|
|
85
|
+ FrameDisplayDeltaTimeMs: null,
|
|
86
|
+ Reset: function () {
|
|
87
|
+ this.TestStartTimeMs = null;
|
|
88
|
+ this.UEReceiptTimeMs = null;
|
|
89
|
+ this.UEEncodeMs = null,
|
|
90
|
+ this.UECaptureToSendMs = null,
|
|
91
|
+ this.UETransmissionTimeMs = null;
|
|
92
|
+ this.BrowserReceiptTimeMs = null;
|
|
93
|
+ this.FrameDisplayDeltaTimeMs = null;
|
|
94
|
+ },
|
|
95
|
+ SetUETimings: function (UETimings) {
|
|
96
|
+ this.UEReceiptTimeMs = UETimings.ReceiptTimeMs;
|
|
97
|
+ this.UEEncodeMs = UETimings.EncodeMs,
|
|
98
|
+ this.UECaptureToSendMs = UETimings.CaptureToSendMs,
|
|
99
|
+ this.UETransmissionTimeMs = UETimings.TransmissionTimeMs;
|
|
100
|
+ this.BrowserReceiptTimeMs = Date.now();
|
|
101
|
+ this.OnAllLatencyTimingsReady(this);
|
|
102
|
+ },
|
|
103
|
+ SetFrameDisplayDeltaTime: function (DeltaTimeMs) {
|
|
104
|
+ if (this.FrameDisplayDeltaTimeMs == null) {
|
|
105
|
+ this.FrameDisplayDeltaTimeMs = Math.round(DeltaTimeMs);
|
|
106
|
+ this.OnAllLatencyTimingsReady(this);
|
|
107
|
+ }
|
|
108
|
+ },
|
|
109
|
+ OnAllLatencyTimingsReady: function (Timings) { }
|
|
110
|
+ }
|
|
111
|
+
|
|
112
|
+ //**********************
|
|
113
|
+ //Functions
|
|
114
|
+ //**********************
|
|
115
|
+
|
|
116
|
+ //Create Video element and expose that as a parameter
|
|
117
|
+ this.createWebRtcVideo = function () {
|
|
118
|
+ var video = document.createElement('video');
|
|
119
|
+
|
|
120
|
+ video.id = "streamingVideo";
|
|
121
|
+ video.playsInline = true;
|
|
122
|
+ video.disablepictureinpicture = true;
|
|
123
|
+ // video.muted = self.startVideoMuted;
|
|
124
|
+ // 音频
|
|
125
|
+ video.muted = true;
|
|
126
|
+ // 开启全屏
|
|
127
|
+ video.style.width = "100%"
|
|
128
|
+ video.style.height = "100%"
|
|
129
|
+ video.style.objectFit = "fill"
|
|
130
|
+ video.style.margin = 0;
|
|
131
|
+ video.style.padding = 0;
|
|
132
|
+ video.style.top = 0;
|
|
133
|
+ video.style.left = 0;
|
|
134
|
+ video.style.position = "relative";
|
|
135
|
+ video.style.zIndex = 100;
|
|
136
|
+ video.style.cursor = "pointer";
|
|
137
|
+ // video.style.overflow="hidden";
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+ video.addEventListener('loadedmetadata', function (e) {
|
|
141
|
+ if (self.onVideoInitialised) {
|
|
142
|
+ self.onVideoInitialised();
|
|
143
|
+ }
|
|
144
|
+ }, true);
|
|
145
|
+
|
|
146
|
+ // Check if request video frame callback is supported
|
|
147
|
+ if ('requestVideoFrameCallback' in HTMLVideoElement.prototype) {
|
|
148
|
+ // The API is supported!
|
|
149
|
+
|
|
150
|
+ const onVideoFrameReady = (now, metadata) => {
|
|
151
|
+
|
|
152
|
+ if (metadata.receiveTime && metadata.expectedDisplayTime) {
|
|
153
|
+ const receiveToCompositeMs = metadata.presentationTime - metadata.receiveTime;
|
|
154
|
+ self.aggregatedStats.receiveToCompositeMs = receiveToCompositeMs;
|
|
155
|
+ }
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+ // Re-register the callback to be notified about the next frame.
|
|
159
|
+ video.requestVideoFrameCallback(onVideoFrameReady);
|
|
160
|
+ };
|
|
161
|
+
|
|
162
|
+ // Initially register the callback to be notified about the first frame.
|
|
163
|
+ video.requestVideoFrameCallback(onVideoFrameReady);
|
|
164
|
+ }
|
|
165
|
+
|
|
166
|
+ return video;
|
|
167
|
+ }
|
|
168
|
+
|
|
169
|
+ this.video = this.createWebRtcVideo();
|
|
170
|
+ this.availableVideoStreams = new Map();
|
|
171
|
+
|
|
172
|
+ function onsignalingstatechange(state) {
|
|
173
|
+ console.info('Signaling state change. |', state.srcElement.signalingState, "|")
|
|
174
|
+ };
|
|
175
|
+
|
|
176
|
+ function oniceconnectionstatechange(state) {
|
|
177
|
+ console.info('Browser ICE connection |', state.srcElement.iceConnectionState, '|')
|
|
178
|
+ };
|
|
179
|
+
|
|
180
|
+ function onicegatheringstatechange(state) {
|
|
181
|
+ console.info('Browser ICE gathering |', state.srcElement.iceGatheringState, '|')
|
|
182
|
+ };
|
|
183
|
+
|
|
184
|
+ function handleOnTrack(e) {
|
|
185
|
+ if (e.track) {
|
|
186
|
+ console.log('Got track. | Kind=' + e.track.kind + ' | Id=' + e.track.id + ' | readyState=' + e.track.readyState + ' |');
|
|
187
|
+ }
|
|
188
|
+
|
|
189
|
+ if (e.track.kind == "audio") {
|
|
190
|
+ handleOnAudioTrack(e.streams[0]);
|
|
191
|
+ return;
|
|
192
|
+ }
|
|
193
|
+ else (e.track.kind == "video")
|
|
194
|
+ {
|
|
195
|
+ for (const s of e.streams) {
|
|
196
|
+ if (!self.availableVideoStreams.has(s.id)) {
|
|
197
|
+ self.availableVideoStreams.set(s.id, s);
|
|
198
|
+ }
|
|
199
|
+ }
|
|
200
|
+
|
|
201
|
+ self.video.srcObject = e.streams[0];
|
|
202
|
+
|
|
203
|
+ // All tracks are added "muted" by WebRTC/browser and become unmuted when media is being sent
|
|
204
|
+ e.track.onunmute = () => {
|
|
205
|
+ self.video.srcObject = e.streams[0];
|
|
206
|
+ self.onNewVideoTrack(e.streams);
|
|
207
|
+ }
|
|
208
|
+ }
|
|
209
|
+ };
|
|
210
|
+
|
|
211
|
+ function handleOnAudioTrack(audioMediaStream) {
|
|
212
|
+ // do nothing the video has the same media stream as the audio track we have here (they are linked)
|
|
213
|
+ if (self.video.srcObject == audioMediaStream) {
|
|
214
|
+ return;
|
|
215
|
+ }
|
|
216
|
+ // video element has some other media stream that is not associated with this audio track
|
|
217
|
+ else if (self.video.srcObject && self.video.srcObject !== audioMediaStream) {
|
|
218
|
+ // create a new audio element
|
|
219
|
+ let audioElem = document.createElement("Audio");
|
|
220
|
+ audioElem.srcObject = audioMediaStream;
|
|
221
|
+
|
|
222
|
+ // there is no way to autoplay audio (even muted), so we defer audio until first click
|
|
223
|
+ if (!self.autoPlayAudio) {
|
|
224
|
+
|
|
225
|
+ let clickToPlayAudio = function () {
|
|
226
|
+ audioElem.play();
|
|
227
|
+ self.video.removeEventListener("click", clickToPlayAudio);
|
|
228
|
+ };
|
|
229
|
+
|
|
230
|
+ self.video.addEventListener("click", clickToPlayAudio);
|
|
231
|
+ }
|
|
232
|
+ // we assume the user has clicked somewhere on the page and autoplaying audio will work
|
|
233
|
+ else {
|
|
234
|
+ audioElem.play();
|
|
235
|
+ }
|
|
236
|
+ console.log('Created new audio element to play seperate audio stream.');
|
|
237
|
+ }
|
|
238
|
+
|
|
239
|
+ }
|
|
240
|
+
|
|
241
|
+ function onDataChannel(dataChannelEvent) {
|
|
242
|
+ // This is the primary data channel code path when we are "receiving"
|
|
243
|
+ console.log("Data channel created for us by browser as we are a receiving peer.");
|
|
244
|
+ self.dcClient = dataChannelEvent.channel;
|
|
245
|
+ setupDataChannelCallbacks(self.dcClient);
|
|
246
|
+ }
|
|
247
|
+
|
|
248
|
+ function createDataChannel(pc, label, options) {
|
|
249
|
+ // This is the primary data channel code path when we are "offering"
|
|
250
|
+ let datachannel = pc.createDataChannel(label, options);
|
|
251
|
+ console.log(`Created datachannel (${label})`);
|
|
252
|
+ setupDataChannelCallbacks(datachannel);
|
|
253
|
+ return datachannel;
|
|
254
|
+ }
|
|
255
|
+
|
|
256
|
+ function setupDataChannelCallbacks(datachannel) {
|
|
257
|
+ try {
|
|
258
|
+ // Inform browser we would like binary data as an ArrayBuffer (FF chooses Blob by default!)
|
|
259
|
+ datachannel.binaryType = "arraybuffer";
|
|
260
|
+
|
|
261
|
+ datachannel.onopen = function (e) {
|
|
262
|
+ console.log("Data channel connected");
|
|
263
|
+ if (self.onDataChannelConnected) {
|
|
264
|
+ self.onDataChannelConnected();
|
|
265
|
+ }
|
|
266
|
+ }
|
|
267
|
+
|
|
268
|
+ datachannel.onclose = function (e) {
|
|
269
|
+ console.log("Data channel connected", e);
|
|
270
|
+ }
|
|
271
|
+
|
|
272
|
+ datachannel.onmessage = function (e) {
|
|
273
|
+ if (self.onDataChannelMessage) {
|
|
274
|
+ self.onDataChannelMessage(e.data);
|
|
275
|
+ }
|
|
276
|
+ }
|
|
277
|
+
|
|
278
|
+ datachannel.onerror = function (e) {
|
|
279
|
+ console.error("Data channel error", e);
|
|
280
|
+ }
|
|
281
|
+
|
|
282
|
+ return datachannel;
|
|
283
|
+ } catch (e) {
|
|
284
|
+ console.warn('No data channel', e);
|
|
285
|
+ return null;
|
|
286
|
+ }
|
|
287
|
+ }
|
|
288
|
+
|
|
289
|
+ function onicecandidate(e) {
|
|
290
|
+ let candidate = e.candidate;
|
|
291
|
+ if (candidate && candidate.candidate) {
|
|
292
|
+ console.log("%c[Browser ICE candidate]", "background: violet; color: black", "| Type=", candidate.type, "| Protocol=", candidate.protocol, "| Address=", candidate.address, "| Port=", candidate.port, "|");
|
|
293
|
+ self.onWebRtcCandidate(candidate);
|
|
294
|
+ }
|
|
295
|
+ };
|
|
296
|
+
|
|
297
|
+ function handleCreateOffer(pc) {
|
|
298
|
+ pc.createOffer(self.sdpConstraints).then(function (offer) {
|
|
299
|
+
|
|
300
|
+ // Munging is where we modifying the sdp string to set parameters that are not exposed to the browser's WebRTC API
|
|
301
|
+ mungeSDPOffer(offer);
|
|
302
|
+
|
|
303
|
+ // Set our munged SDP on the local peer connection so it is "set" and will be send across
|
|
304
|
+ pc.setLocalDescription(offer);
|
|
305
|
+ if (self.onWebRtcOffer) {
|
|
306
|
+ self.onWebRtcOffer(offer);
|
|
307
|
+ }
|
|
308
|
+ },
|
|
309
|
+ function () { console.warn("Couldn't create offer") });
|
|
310
|
+ }
|
|
311
|
+
|
|
312
|
+ function mungeSDPOffer(offer) {
|
|
313
|
+
|
|
314
|
+ // turn off video-timing sdp sent from browser
|
|
315
|
+ //offer.sdp = offer.sdp.replace("http://www.webrtc.org/experiments/rtp-hdrext/playout-delay", "");
|
|
316
|
+
|
|
317
|
+ // this indicate we support stereo (Chrome needs this)
|
|
318
|
+ offer.sdp = offer.sdp.replace('useinbandfec=1', 'useinbandfec=1;stereo=1;sprop-maxcapturerate=48000');
|
|
319
|
+
|
|
320
|
+ }
|
|
321
|
+
|
|
322
|
+ function setupPeerConnection(pc) {
|
|
323
|
+ //Setup peerConnection events
|
|
324
|
+ pc.onsignalingstatechange = onsignalingstatechange;
|
|
325
|
+ pc.oniceconnectionstatechange = oniceconnectionstatechange;
|
|
326
|
+ pc.onicegatheringstatechange = onicegatheringstatechange;
|
|
327
|
+
|
|
328
|
+ pc.ontrack = handleOnTrack;
|
|
329
|
+ pc.onicecandidate = onicecandidate;
|
|
330
|
+ pc.ondatachannel = onDataChannel;
|
|
331
|
+ };
|
|
332
|
+
|
|
333
|
+ function generateAggregatedStatsFunction() {
|
|
334
|
+ if (!self.aggregatedStats)
|
|
335
|
+ self.aggregatedStats = {};
|
|
336
|
+
|
|
337
|
+ return function (stats) {
|
|
338
|
+ //console.log('Printing Stats');
|
|
339
|
+
|
|
340
|
+ let newStat = {};
|
|
341
|
+
|
|
342
|
+ stats.forEach(stat => {
|
|
343
|
+ // console.log(JSON.stringify(stat, undefined, 4));
|
|
344
|
+ if (stat.type == 'inbound-rtp'
|
|
345
|
+ && !stat.isRemote
|
|
346
|
+ && (stat.mediaType == 'video' || stat.id.toLowerCase().includes('video'))) {
|
|
347
|
+
|
|
348
|
+ newStat.timestamp = stat.timestamp;
|
|
349
|
+ newStat.bytesReceived = stat.bytesReceived;
|
|
350
|
+ newStat.framesDecoded = stat.framesDecoded;
|
|
351
|
+ newStat.packetsLost = stat.packetsLost;
|
|
352
|
+ newStat.bytesReceivedStart = self.aggregatedStats && self.aggregatedStats.bytesReceivedStart ? self.aggregatedStats.bytesReceivedStart : stat.bytesReceived;
|
|
353
|
+ newStat.framesDecodedStart = self.aggregatedStats && self.aggregatedStats.framesDecodedStart ? self.aggregatedStats.framesDecodedStart : stat.framesDecoded;
|
|
354
|
+ newStat.timestampStart = self.aggregatedStats && self.aggregatedStats.timestampStart ? self.aggregatedStats.timestampStart : stat.timestamp;
|
|
355
|
+
|
|
356
|
+ if (self.aggregatedStats && self.aggregatedStats.timestamp) {
|
|
357
|
+ if (self.aggregatedStats.bytesReceived) {
|
|
358
|
+ // bitrate = bits received since last time / number of ms since last time
|
|
359
|
+ //This is automatically in kbits (where k=1000) since time is in ms and stat we want is in seconds (so a '* 1000' then a '/ 1000' would negate each other)
|
|
360
|
+ newStat.bitrate = 8 * (newStat.bytesReceived - self.aggregatedStats.bytesReceived) / (newStat.timestamp - self.aggregatedStats.timestamp);
|
|
361
|
+ newStat.bitrate = Math.floor(newStat.bitrate);
|
|
362
|
+ newStat.lowBitrate = self.aggregatedStats.lowBitrate && self.aggregatedStats.lowBitrate < newStat.bitrate ? self.aggregatedStats.lowBitrate : newStat.bitrate
|
|
363
|
+ newStat.highBitrate = self.aggregatedStats.highBitrate && self.aggregatedStats.highBitrate > newStat.bitrate ? self.aggregatedStats.highBitrate : newStat.bitrate
|
|
364
|
+ }
|
|
365
|
+
|
|
366
|
+ if (self.aggregatedStats.bytesReceivedStart) {
|
|
367
|
+ newStat.avgBitrate = 8 * (newStat.bytesReceived - self.aggregatedStats.bytesReceivedStart) / (newStat.timestamp - self.aggregatedStats.timestampStart);
|
|
368
|
+ newStat.avgBitrate = Math.floor(newStat.avgBitrate);
|
|
369
|
+ }
|
|
370
|
+
|
|
371
|
+ if (self.aggregatedStats.framesDecoded) {
|
|
372
|
+ // framerate = frames decoded since last time / number of seconds since last time
|
|
373
|
+ newStat.framerate = (newStat.framesDecoded - self.aggregatedStats.framesDecoded) / ((newStat.timestamp - self.aggregatedStats.timestamp) / 1000);
|
|
374
|
+ newStat.framerate = Math.floor(newStat.framerate);
|
|
375
|
+ newStat.lowFramerate = self.aggregatedStats.lowFramerate && self.aggregatedStats.lowFramerate < newStat.framerate ? self.aggregatedStats.lowFramerate : newStat.framerate
|
|
376
|
+ newStat.highFramerate = self.aggregatedStats.highFramerate && self.aggregatedStats.highFramerate > newStat.framerate ? self.aggregatedStats.highFramerate : newStat.framerate
|
|
377
|
+ }
|
|
378
|
+
|
|
379
|
+ if (self.aggregatedStats.framesDecodedStart) {
|
|
380
|
+ newStat.avgframerate = (newStat.framesDecoded - self.aggregatedStats.framesDecodedStart) / ((newStat.timestamp - self.aggregatedStats.timestampStart) / 1000);
|
|
381
|
+ newStat.avgframerate = Math.floor(newStat.avgframerate);
|
|
382
|
+ }
|
|
383
|
+ }
|
|
384
|
+ }
|
|
385
|
+
|
|
386
|
+ //Read video track stats
|
|
387
|
+ if (stat.type == 'track' && (stat.trackIdentifier == 'video_label' || stat.kind == 'video')) {
|
|
388
|
+ newStat.framesDropped = stat.framesDropped;
|
|
389
|
+ newStat.framesReceived = stat.framesReceived;
|
|
390
|
+ newStat.framesDroppedPercentage = stat.framesDropped / stat.framesReceived * 100;
|
|
391
|
+ newStat.frameHeight = stat.frameHeight;
|
|
392
|
+ newStat.frameWidth = stat.frameWidth;
|
|
393
|
+ newStat.frameHeightStart = self.aggregatedStats && self.aggregatedStats.frameHeightStart ? self.aggregatedStats.frameHeightStart : stat.frameHeight;
|
|
394
|
+ newStat.frameWidthStart = self.aggregatedStats && self.aggregatedStats.frameWidthStart ? self.aggregatedStats.frameWidthStart : stat.frameWidth;
|
|
395
|
+ }
|
|
396
|
+
|
|
397
|
+ if (stat.type == 'candidate-pair' && stat.hasOwnProperty('currentRoundTripTime') && stat.currentRoundTripTime != 0) {
|
|
398
|
+ newStat.currentRoundTripTime = stat.currentRoundTripTime;
|
|
399
|
+ }
|
|
400
|
+ });
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+ if (self.aggregatedStats.receiveToCompositeMs) {
|
|
404
|
+ newStat.receiveToCompositeMs = self.aggregatedStats.receiveToCompositeMs;
|
|
405
|
+ self.latencyTestTimings.SetFrameDisplayDeltaTime(self.aggregatedStats.receiveToCompositeMs);
|
|
406
|
+ }
|
|
407
|
+
|
|
408
|
+ self.aggregatedStats = newStat;
|
|
409
|
+
|
|
410
|
+ if (self.onAggregatedStats)
|
|
411
|
+ self.onAggregatedStats(newStat)
|
|
412
|
+ }
|
|
413
|
+ };
|
|
414
|
+
|
|
415
|
+ let setupTransceiversAsync = async function (pc) {
|
|
416
|
+
|
|
417
|
+ let hasTransceivers = pc.getTransceivers().length > 0;
|
|
418
|
+
|
|
419
|
+ // Setup a transceiver for getting UE video
|
|
420
|
+ pc.addTransceiver("video", { direction: "recvonly" });
|
|
421
|
+
|
|
422
|
+ // Setup a transceiver for sending mic audio to UE and receiving audio from UE
|
|
423
|
+ if (!self.useMic) {
|
|
424
|
+ pc.addTransceiver("audio", { direction: "recvonly" });
|
|
425
|
+ }
|
|
426
|
+ else {
|
|
427
|
+ let audioSendOptions = self.useMic ?
|
|
428
|
+ {
|
|
429
|
+ autoGainControl: false,
|
|
430
|
+ channelCount: 1,
|
|
431
|
+ echoCancellation: false,
|
|
432
|
+ latency: 0,
|
|
433
|
+ noiseSuppression: false,
|
|
434
|
+ sampleRate: 48000,
|
|
435
|
+ volume: 1.0
|
|
436
|
+ } : false;
|
|
437
|
+
|
|
438
|
+ // Note using mic on android chrome requires SSL or chrome://flags/ "unsafely-treat-insecure-origin-as-secure"
|
|
439
|
+ const stream = await navigator.mediaDevices.getUserMedia({ video: false, audio: audioSendOptions });
|
|
440
|
+ if (stream) {
|
|
441
|
+ if (hasTransceivers) {
|
|
442
|
+ for (let transceiver of pc.getTransceivers()) {
|
|
443
|
+ if (transceiver && transceiver.receiver && transceiver.receiver.track && transceiver.receiver.track.kind === "audio") {
|
|
444
|
+ for (const track of stream.getTracks()) {
|
|
445
|
+ if (track.kind && track.kind == "audio") {
|
|
446
|
+ transceiver.sender.replaceTrack(track);
|
|
447
|
+ transceiver.direction = "sendrecv";
|
|
448
|
+ }
|
|
449
|
+ }
|
|
450
|
+ }
|
|
451
|
+ }
|
|
452
|
+ }
|
|
453
|
+ else {
|
|
454
|
+ for (const track of stream.getTracks()) {
|
|
455
|
+ if (track.kind && track.kind == "audio") {
|
|
456
|
+ pc.addTransceiver(track, { direction: "sendrecv" });
|
|
457
|
+ }
|
|
458
|
+ }
|
|
459
|
+ }
|
|
460
|
+ }
|
|
461
|
+ else {
|
|
462
|
+ pc.addTransceiver("audio", { direction: "recvonly" });
|
|
463
|
+ }
|
|
464
|
+ }
|
|
465
|
+ };
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+ //**********************
|
|
469
|
+ //Public functions
|
|
470
|
+ //**********************
|
|
471
|
+
|
|
472
|
+ this.setVideoEnabled = function (enabled) {
|
|
473
|
+ self.video.srcObject.getTracks().forEach(track => track.enabled = enabled);
|
|
474
|
+ }
|
|
475
|
+
|
|
476
|
+ this.startLatencyTest = function (onTestStarted) {
|
|
477
|
+ // Can't start latency test without a video element
|
|
478
|
+ if (!self.video) {
|
|
479
|
+ return;
|
|
480
|
+ }
|
|
481
|
+
|
|
482
|
+ self.latencyTestTimings.Reset();
|
|
483
|
+ self.latencyTestTimings.TestStartTimeMs = Date.now();
|
|
484
|
+ onTestStarted(self.latencyTestTimings.TestStartTimeMs);
|
|
485
|
+ }
|
|
486
|
+
|
|
487
|
+ //This is called when revceiving new ice candidates individually instead of part of the offer
|
|
488
|
+ this.handleCandidateFromServer = function (iceCandidate) {
|
|
489
|
+ let candidate = new RTCIceCandidate(iceCandidate);
|
|
490
|
+
|
|
491
|
+ console.log("%c[Unreal ICE candidate]", "background: pink; color: black", "| Type=", candidate.type, "| Protocol=", candidate.protocol, "| Address=", candidate.address, "| Port=", candidate.port, "|");
|
|
492
|
+
|
|
493
|
+ // if forcing TURN, reject any candidates not relay
|
|
494
|
+ if (self.forceTURN) {
|
|
495
|
+ // check if no relay address is found, if so, we are assuming it means no TURN server
|
|
496
|
+ if (candidate.candidate.indexOf("relay") < 0) {
|
|
497
|
+ console.warn("Dropping candidate because it was not TURN relay.", "| Type=", candidate.type, "| Protocol=", candidate.protocol, "| Address=", candidate.address, "| Port=", candidate.port, "|")
|
|
498
|
+ return;
|
|
499
|
+ }
|
|
500
|
+ }
|
|
501
|
+
|
|
502
|
+ self.pcClient.addIceCandidate(candidate).catch(function (e) {
|
|
503
|
+ console.error("Failed to add ICE candidate", e);
|
|
504
|
+ });
|
|
505
|
+ };
|
|
506
|
+
|
|
507
|
+ //Called externaly to create an offer for the server
|
|
508
|
+ this.createOffer = function () {
|
|
509
|
+ if (self.pcClient) {
|
|
510
|
+ console.log("Closing existing PeerConnection")
|
|
511
|
+ self.pcClient.close();
|
|
512
|
+ self.pcClient = null;
|
|
513
|
+ }
|
|
514
|
+ self.pcClient = new RTCPeerConnection(self.cfg);
|
|
515
|
+ setupPeerConnection(self.pcClient);
|
|
516
|
+
|
|
517
|
+ setupTransceiversAsync(self.pcClient).finally(function () {
|
|
518
|
+ self.dcClient = createDataChannel(self.pcClient, 'cirrus', self.dataChannelOptions);
|
|
519
|
+ handleCreateOffer(self.pcClient);
|
|
520
|
+ });
|
|
521
|
+
|
|
522
|
+ };
|
|
523
|
+
|
|
524
|
+ //Called externaly when an offer is received from the server
|
|
525
|
+ this.receiveOffer = function (offer) {
|
|
526
|
+ var offerDesc = new RTCSessionDescription(offer);
|
|
527
|
+
|
|
528
|
+ if (!self.pcClient) {
|
|
529
|
+ console.log("Creating a new PeerConnection in the browser.")
|
|
530
|
+ self.pcClient = new RTCPeerConnection(self.cfg);
|
|
531
|
+ setupPeerConnection(self.pcClient);
|
|
532
|
+
|
|
533
|
+ // Put things here that happen post transceiver setup
|
|
534
|
+ self.pcClient.setRemoteDescription(offerDesc)
|
|
535
|
+ .then(() => {
|
|
536
|
+ setupTransceiversAsync(self.pcClient).finally(function () {
|
|
537
|
+ self.pcClient.createAnswer()
|
|
538
|
+ .then(answer => self.pcClient.setLocalDescription(answer))
|
|
539
|
+ .then(() => {
|
|
540
|
+ if (self.onWebRtcAnswer) {
|
|
541
|
+ self.onWebRtcAnswer(self.pcClient.currentLocalDescription);
|
|
542
|
+ }
|
|
543
|
+ })
|
|
544
|
+ .then(() => {
|
|
545
|
+ let receivers = self.pcClient.getReceivers();
|
|
546
|
+ for (let receiver of receivers) {
|
|
547
|
+ receiver.playoutDelayHint = 0;
|
|
548
|
+ }
|
|
549
|
+ })
|
|
550
|
+ .catch((error) => console.error("createAnswer() failed:", error));
|
|
551
|
+ });
|
|
552
|
+ });
|
|
553
|
+ }
|
|
554
|
+ };
|
|
555
|
+
|
|
556
|
+ //Called externaly when an answer is received from the server
|
|
557
|
+ this.receiveAnswer = function (answer) {
|
|
558
|
+ var answerDesc = new RTCSessionDescription(answer);
|
|
559
|
+ self.pcClient.setRemoteDescription(answerDesc);
|
|
560
|
+
|
|
561
|
+ let receivers = self.pcClient.getReceivers();
|
|
562
|
+ for (let receiver of receivers) {
|
|
563
|
+ receiver.playoutDelayHint = 0;
|
|
564
|
+ }
|
|
565
|
+ };
|
|
566
|
+
|
|
567
|
+ this.close = function () {
|
|
568
|
+ if (self.pcClient) {
|
|
569
|
+ console.log("Closing existing peerClient")
|
|
570
|
+ self.pcClient.close();
|
|
571
|
+ self.pcClient = null;
|
|
572
|
+ }
|
|
573
|
+ if (self.aggregateStatsIntervalId)
|
|
574
|
+ clearInterval(self.aggregateStatsIntervalId);
|
|
575
|
+ }
|
|
576
|
+
|
|
577
|
+ //Sends data across the datachannel
|
|
578
|
+ this.send = function (data) {
|
|
579
|
+ if (self.dcClient && self.dcClient.readyState == 'open') {
|
|
580
|
+ //console.log('Sending data on dataconnection', self.dcClient)
|
|
581
|
+ self.dcClient.send(data);
|
|
582
|
+ }
|
|
583
|
+ };
|
|
584
|
+
|
|
585
|
+ this.getStats = function (onStats) {
|
|
586
|
+ if (self.pcClient && onStats) {
|
|
587
|
+ self.pcClient.getStats(null).then((stats) => {
|
|
588
|
+ onStats(stats);
|
|
589
|
+ });
|
|
590
|
+ }
|
|
591
|
+ }
|
|
592
|
+
|
|
593
|
+ this.aggregateStats = function (checkInterval) {
|
|
594
|
+ let calcAggregatedStats = generateAggregatedStatsFunction();
|
|
595
|
+ let printAggregatedStats = () => { self.getStats(calcAggregatedStats); }
|
|
596
|
+ self.aggregateStatsIntervalId = setInterval(printAggregatedStats, checkInterval);
|
|
597
|
+ }
|
|
598
|
+}
|
|
599
|
+
|
|
600
|
+export default webRtcPlayer
|