/
peerConnection.ts
1206 lines (1061 loc) · 35.4 KB
/
peerConnection.ts
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import debug from "debug";
import { cloneDeep, isEqual } from "lodash";
import Event from "rx.mini";
import * as uuid from "uuid";
import {
DISCARD_HOST,
DISCARD_PORT,
SenderDirections,
SRTP_PROFILE,
} from "./const";
import { RTCDataChannel, RTCDataChannelParameters } from "./dataChannel";
import { enumerate, EventTarget } from "./helper";
import {
RTCRtpCodecParameters,
RTCRtpCodingParameters,
RTCRtpHeaderExtensionParameters,
RTCRtpParameters,
RTCRtpReceiveParameters,
RTCRtpSimulcastParameters,
} from "./media/parameters";
import { RtpRouter } from "./media/router";
import { RTCRtpReceiver } from "./media/rtpReceiver";
import { RTCRtpSender } from "./media/rtpSender";
import {
Direction,
RTCRtpTransceiver,
TransceiverOptions,
} from "./media/rtpTransceiver";
import { MediaStream, MediaStreamTrack } from "./media/track";
import {
addSDPHeader,
GroupDescription,
MediaDescription,
SessionDescription,
SsrcDescription,
} from "./sdp";
import {
RTCCertificate,
RTCDtlsParameters,
RTCDtlsTransport,
} from "./transport/dtls";
import {
IceCandidate,
IceGathererState,
RTCIceCandidate,
RTCIceConnectionState,
RTCIceGatherer,
RTCIceParameters,
RTCIceTransport,
} from "./transport/ice";
import { RTCSctpTransport } from "./transport/sctp";
import { ConnectionState, Kind, RTCSignalingState } from "./types/domain";
import { Callback, CallbackWithValue } from "./types/util";
import {
andDirection,
parseIceServers,
reverseDirection,
reverseSimulcastDirection,
} from "./utils";
const log = debug("werift/webrtc/peerConnection");
export class RTCPeerConnection extends EventTarget {
readonly cname = uuid.v4();
iceTransport: RTCIceTransport;
dtlsTransport: RTCDtlsTransport;
sctpTransport?: RTCSctpTransport;
masterTransportEstablished = false;
configuration: Required<PeerConfig> =
cloneDeep<PeerConfig>(defaultPeerConfig);
connectionState: ConnectionState = "new";
iceConnectionState: RTCIceConnectionState = "new";
iceGatheringState: IceGathererState = "new";
signalingState: RTCSignalingState = "stable";
negotiationneeded = false;
readonly transceivers: RTCRtpTransceiver[] = [];
readonly iceGatheringStateChange = new Event<[IceGathererState]>();
readonly iceConnectionStateChange = new Event<[RTCIceConnectionState]>();
readonly signalingStateChange = new Event<[RTCSignalingState]>();
readonly connectionStateChange = new Event<[ConnectionState]>();
readonly onDataChannel = new Event<[RTCDataChannel]>();
readonly onRemoteTransceiverAdded = new Event<[RTCRtpTransceiver]>();
/**
* should use onRemoteTransceiverAdded
* @deprecated
*/
readonly onTransceiver = new Event<[RTCRtpTransceiver]>();
readonly onTransceiverAdded = new Event<[RTCRtpTransceiver]>();
readonly onIceCandidate = new Event<[RTCIceCandidate]>();
readonly onNegotiationneeded = new Event<[]>();
ondatachannel?: CallbackWithValue<RTCDataChannelEvent>;
onicecandidate?: CallbackWithValue<RTCPeerConnectionIceEvent>;
onnegotiationneeded?: CallbackWithValue<any>;
onsignalingstatechange?: CallbackWithValue<any>;
ontrack?: CallbackWithValue<RTCTrackEvent>;
onconnectionstatechange?: Callback;
private readonly router = new RtpRouter();
private readonly certificates: RTCCertificate[] = [];
private sctpRemotePort?: number;
private remoteDtls?: RTCDtlsParameters;
private remoteIce?: RTCIceParameters;
private seenMid = new Set<string>();
private currentLocalDescription?: SessionDescription;
private currentRemoteDescription?: SessionDescription;
private pendingLocalDescription?: SessionDescription;
private pendingRemoteDescription?: SessionDescription;
private isClosed = false;
private shouldNegotiationneeded = false;
constructor({
codecs,
headerExtensions,
iceServers,
iceTransportPolicy,
icePortRange,
}: Partial<PeerConfig> = {}) {
super();
if (iceServers) this.configuration.iceServers = iceServers;
if (iceTransportPolicy)
this.configuration.iceTransportPolicy = iceTransportPolicy;
if (icePortRange) {
const [min, max] = icePortRange;
if (min === max) throw new Error("should not be same value");
if (min >= max) throw new Error("The min must be less than max");
this.configuration.icePortRange = icePortRange;
}
if (codecs?.audio) this.configuration.codecs.audio = codecs.audio;
if (codecs?.video) this.configuration.codecs.video = codecs.video;
[
...(this.configuration.codecs.audio || []),
...(this.configuration.codecs.video || []),
].forEach((v, i) => {
v.payloadType = 96 + i;
});
if (headerExtensions?.audio)
this.configuration.headerExtensions.audio = headerExtensions.audio;
if (headerExtensions?.video)
this.configuration.headerExtensions.video = headerExtensions.video;
[
...(this.configuration.headerExtensions.audio || []),
...(this.configuration.headerExtensions.video || []),
].forEach((v, i) => {
v.id = 1 + i;
});
this.iceConnectionStateChange.subscribe((state) => {
switch (state) {
case "disconnected":
this.setConnectionState("disconnected");
break;
case "closed":
this.close();
break;
}
});
const { iceTransport, dtlsTransport } = this.createTransport([
SRTP_PROFILE.SRTP_AES128_CM_HMAC_SHA1_80,
]);
this.iceTransport = iceTransport;
this.dtlsTransport = dtlsTransport;
}
get localDescription() {
if (!this._localDescription) return;
return this._localDescription.toJSON();
}
get remoteDescription() {
if (!this._remoteDescription) return;
return this._remoteDescription.toJSON();
}
private get _localDescription() {
return this.pendingLocalDescription || this.currentLocalDescription;
}
private get _remoteDescription() {
return this.pendingRemoteDescription || this.currentRemoteDescription;
}
private getTransceiverByMid(mid: string) {
return this.transceivers.find((transceiver) => transceiver.mid === mid);
}
private getTransceiverByMLineIndex(index: number) {
return this.transceivers.find(
(transceiver) => transceiver.mLineIndex === index
);
}
async createOffer() {
if (this.certificates.length === 0) {
await this.dtlsTransport.setupCertificate();
}
this.transceivers.forEach((transceiver) => {
transceiver.codecs = this.configuration.codecs[transceiver.kind];
transceiver.headerExtensions =
this.configuration.headerExtensions[transceiver.kind];
});
const description = new SessionDescription();
addSDPHeader("offer", description);
// # handle existing transceivers / sctp
const currentMedia = this._localDescription
? this._localDescription.media
: [];
currentMedia.forEach((m, i) => {
const mid = m.rtp.muxId;
if (!mid) {
log("mid missing", m);
return;
}
if (m.kind === "application") {
description.media.push(
createMediaDescriptionForSctp(this.sctpTransport!, mid)
);
} else {
const transceiver = this.getTransceiverByMid(mid);
if (!transceiver) {
log("transceiver by mid not found", mid);
return;
}
transceiver.mLineIndex = i;
description.media.push(
createMediaDescriptionForTransceiver(
transceiver,
this.cname,
transceiver.direction,
mid
)
);
}
});
// # handle new transceivers / sctp
this.transceivers
.filter((t) => !description.media.find((m) => m.rtp.muxId === t.mid))
.forEach((transceiver) => {
transceiver.mLineIndex = description.media.length;
description.media.push(
createMediaDescriptionForTransceiver(
transceiver,
this.cname,
transceiver.direction,
allocateMid(this.seenMid)
)
);
});
if (
this.sctpTransport &&
!description.media.find((m) => this.sctpTransport!.mid === m.rtp.muxId)
) {
description.media.push(
createMediaDescriptionForSctp(
this.sctpTransport,
allocateMid(this.seenMid)
)
);
}
const mids = description.media
.map((m) => m.rtp.muxId)
.filter((v) => v) as string[];
const bundle = new GroupDescription("BUNDLE", mids);
description.group.push(bundle);
return description.toJSON();
}
createDataChannel(
label: string,
options: Partial<{
maxPacketLifeTime?: number;
protocol: string;
maxRetransmits?: number;
ordered: boolean;
negotiated: boolean;
id?: number;
}> = {}
): RTCDataChannel {
const base: typeof options = {
protocol: "",
ordered: true,
negotiated: false,
};
const settings: Required<typeof base> = { ...base, ...options } as any;
if (settings.maxPacketLifeTime && settings.maxRetransmits)
throw new Error("can not select both");
if (!this.sctpTransport) {
this.sctpTransport = this.createSctpTransport();
this.needNegotiation();
}
const parameters = new RTCDataChannelParameters({
id: settings.id,
label,
maxPacketLifeTime: settings.maxPacketLifeTime,
maxRetransmits: settings.maxRetransmits,
negotiated: settings.negotiated,
ordered: settings.ordered,
protocol: settings.protocol,
});
return new RTCDataChannel(this.sctpTransport, parameters);
}
removeTrack(sender: RTCRtpSender) {
if (this.isClosed) throw new Error("peer closed");
if (!this.getSenders().find(({ ssrc }) => sender.ssrc === ssrc))
throw new Error("unExist");
const transceiver = this.transceivers.find(
({ sender: { ssrc } }) => sender.ssrc === ssrc
);
if (!transceiver) throw new Error("unExist");
sender.stop();
if (transceiver.currentDirection === "recvonly") {
this.needNegotiation();
return;
}
if (transceiver.direction === "sendrecv") {
transceiver.direction = "recvonly";
} else if (
transceiver.direction === "sendonly" ||
transceiver.direction === "recvonly"
) {
transceiver.direction = "inactive";
}
this.needNegotiation();
}
private needNegotiation = async () => {
this.shouldNegotiationneeded = true;
if (this.negotiationneeded || this.signalingState !== "stable") return;
this.shouldNegotiationneeded = false;
setImmediate(() => {
this.negotiationneeded = true;
this.onNegotiationneeded.execute();
if (this.onnegotiationneeded) this.onnegotiationneeded({});
});
};
private createTransport(srtpProfiles: number[] = []) {
const iceGatherer = new RTCIceGatherer({
...parseIceServers(this.configuration.iceServers),
forceTurn: this.configuration.iceTransportPolicy === "relay",
portRange: this.configuration.icePortRange,
});
iceGatherer.onGatheringStateChange.subscribe((state) => {
this.updateIceGatheringState(state);
});
this.updateIceGatheringState(iceGatherer.gatheringState);
const iceTransport = new RTCIceTransport(iceGatherer);
iceTransport.onStateChange.subscribe((state) => {
this.updateIceConnectionState(state);
});
this.updateIceConnectionState(iceTransport.state);
iceTransport.iceGather.onIceCandidate = (candidate) => {
if (!this.localDescription) return;
const sdp = SessionDescription.parse(this.localDescription.sdp);
const media = sdp.media[0];
if (!media) {
log("media not exist");
return;
}
candidate.sdpMLineIndex = 0;
candidate.sdpMid = media.rtp.muxId;
// for chrome & firefox & maybe others
candidate.foundation = "candidate:" + candidate.foundation;
this.onIceCandidate.execute(candidate.toJSON());
if (this.onicecandidate)
this.onicecandidate({ candidate: candidate.toJSON() });
this.emit("icecandidate", { candidate });
};
const dtlsTransport = new RTCDtlsTransport(
iceTransport,
this.router,
this.certificates,
srtpProfiles
);
return { dtlsTransport, iceTransport };
}
private createSctpTransport() {
const sctp = new RTCSctpTransport(this.dtlsTransport);
sctp.mid = undefined;
sctp.onDataChannel.subscribe((channel) => {
this.onDataChannel.execute(channel);
const event: RTCDataChannelEvent = { channel };
if (this.ondatachannel) this.ondatachannel(event);
this.emit("datachannel", event);
});
return sctp;
}
async setLocalDescription(sessionDescription: {
type: "offer" | "answer";
sdp: string;
}): Promise<SessionDescription> {
// # parse and validate description
const description = SessionDescription.parse(sessionDescription.sdp);
description.type = sessionDescription.type;
this.validateDescription(description, true);
// # update signaling state
if (description.type === "offer") {
this.setSignalingState("have-local-offer");
} else if (description.type === "answer") {
this.setSignalingState("stable");
}
// # assign MID
description.media.forEach((media, i) => {
const mid = media.rtp.muxId;
if (!mid) {
throw new Error("mid not exist");
}
this.seenMid.add(mid);
if (["audio", "video"].includes(media.kind)) {
const transceiver = this.getTransceiverByMLineIndex(i);
if (transceiver) {
transceiver.mid = mid;
}
}
if (media.kind === "application" && this.sctpTransport) {
this.sctpTransport.mid = mid;
}
});
// # set ICE role
if (description.type === "offer") {
this.iceTransport.connection.iceControlling = true;
} else {
this.iceTransport.connection.iceControlling = false;
}
// One agent full, one lite: The full agent MUST take the controlling role, and the lite agent MUST take the controlled role
// RFC 8445 S6.1.1
if (this.iceTransport.connection.remoteIsLite) {
this.iceTransport.connection.iceControlling = true;
}
// # set DTLS role for mediasoup
if (description.type === "answer") {
const role = description.media.find((media) => media.dtlsParams)
?.dtlsParams?.role;
if (role) {
this.dtlsTransport.role = role;
}
}
// # configure direction
this.transceivers.forEach((t) => {
if (["answer", "pranswer"].includes(description.type)) {
const direction = andDirection(t.direction, t.offerDirection);
t.currentDirection = direction;
}
});
// for trickle ice
this.setLocal(description);
// # gather candidates
await this.iceTransport.iceGather.gather();
description.media.map((media) => {
addTransportDescription(media, this.dtlsTransport);
});
this.setLocal(description);
// connect transports
if (description.type === "answer") {
this.connect().catch((err) => {
log("connect failed", err);
this.setConnectionState("failed");
});
}
if (this.shouldNegotiationneeded) {
this.needNegotiation();
}
return description;
}
private setLocal(description: SessionDescription) {
if (description.type === "answer") {
this.currentLocalDescription = description;
this.pendingLocalDescription = undefined;
} else {
this.pendingLocalDescription = description;
}
}
async addIceCandidate(candidateMessage: RTCIceCandidate) {
const candidate = IceCandidate.fromJSON(candidateMessage);
await this.iceTransport.addRemoteCandidate(candidate);
}
private async connect() {
if (this.masterTransportEstablished || !this.dtlsTransport) return;
const dtlsTransport = this.dtlsTransport;
const iceTransport = dtlsTransport.iceTransport;
if (this.remoteIce && this.remoteDtls) {
this.setConnectionState("connecting");
await iceTransport.start(this.remoteIce).catch((err) => {
log("iceTransport.start failed", err);
throw err;
});
log("ice connected");
await dtlsTransport.start(this.remoteDtls);
if (this.sctpTransport && this.sctpRemotePort) {
await this.sctpTransport.start(this.sctpRemotePort);
await this.sctpTransport.sctp.stateChanged.connected.asPromise();
}
this.masterTransportEstablished = true;
this.setConnectionState("connected");
}
}
private localRtp(transceiver: RTCRtpTransceiver): RTCRtpParameters {
if (transceiver.mid == undefined) throw new Error();
const rtp: RTCRtpParameters = {
codecs: [],
muxId: transceiver.mid,
headerExtensions: transceiver.headerExtensions,
rtcp: { cname: this.cname, ssrc: transceiver.sender.ssrc, mux: true },
};
return rtp;
}
private remoteRtp(
remoteDescription: SessionDescription,
transceiver: RTCRtpTransceiver
): RTCRtpReceiveParameters {
if (transceiver.mLineIndex == undefined)
throw new Error("mLineIndex not assigned");
const media = remoteDescription.media[transceiver.mLineIndex];
if (!media) throw new Error("media line not exist");
const receiveParameters: RTCRtpReceiveParameters = {
codecs: transceiver.codecs,
muxId: media.rtp.muxId,
rtcp: media.rtp.rtcp,
encodings: [],
headerExtensions: [],
};
const encodings = transceiver.codecs.map(
(codec) =>
new RTCRtpCodingParameters({
ssrc: media.ssrc[0]?.ssrc,
payloadType: codec.payloadType,
})
);
receiveParameters.encodings = encodings;
receiveParameters.headerExtensions = transceiver.headerExtensions;
return receiveParameters;
}
private validateDescription(
description: SessionDescription,
isLocal: boolean
) {
if (isLocal) {
if (description.type === "offer") {
if (!["stable", "have-local-offer"].includes(this.signalingState))
throw new Error("Cannot handle offer in signaling state");
} else if (description.type === "answer") {
if (
!["have-remote-offer", "have-local-pranswer"].includes(
this.signalingState
)
) {
throw new Error("Cannot handle answer in signaling state");
}
}
} else {
if (description.type === "offer") {
if (!["stable", "have-remote-offer"].includes(this.signalingState)) {
throw new Error("Cannot handle offer in signaling state");
}
} else if (description.type === "answer") {
if (
!["have-local-offer", "have-remote-pranswer"].includes(
this.signalingState
)
) {
throw new Error("Cannot handle answer in signaling state");
}
}
}
description.media.forEach((media) => {
if (media.direction === "inactive") return;
if (
!media.iceParams ||
!media.iceParams.usernameFragment ||
!media.iceParams.password
)
throw new Error("ICE username fragment or password is missing");
});
if (["answer", "pranswer"].includes(description.type || "")) {
const offer = isLocal ? this._remoteDescription : this._localDescription;
if (!offer) throw new Error();
const offerMedia = offer.media.map((v) => [v.kind, v.rtp.muxId]);
const answerMedia = description.media.map((v) => [v.kind, v.rtp.muxId]);
if (!isEqual(offerMedia, answerMedia))
throw new Error("Media sections in answer do not match offer");
}
}
async setRemoteDescription(sessionDescription: {
type: "offer" | "answer";
sdp: string;
}) {
// # parse and validate description
const description = SessionDescription.parse(sessionDescription.sdp);
description.type = sessionDescription.type;
this.validateDescription(description, false);
// # apply description
for (const [i, media] of enumerate(description.media)) {
if (["audio", "video"].includes(media.kind)) {
const transceiver =
this.transceivers.find(
(t) =>
t.kind === media.kind &&
[undefined, media.rtp.muxId].includes(t.mid)
) ||
(() => {
// create remote transceiver
const transceiver = this.addTransceiver(media.kind, {
direction: "recvonly",
});
this.onRemoteTransceiverAdded.execute(transceiver);
this.onTransceiver.execute(transceiver);
return transceiver;
})();
if (!transceiver.mid) {
transceiver.mid = media.rtp.muxId;
transceiver.mLineIndex = i;
}
// # negotiate codecs
log("remote codecs", media.rtp.codecs);
transceiver.codecs = media.rtp.codecs.filter((remoteCodec) =>
(
this.configuration.codecs[media.kind as "audio" | "video"] || []
).find(
(localCodec) =>
localCodec.mimeType.toLowerCase() ===
remoteCodec.mimeType.toLowerCase()
)
);
log("negotiated codecs", transceiver.codecs);
if (transceiver.codecs.length === 0) {
throw new Error("negotiate codecs failed.");
}
transceiver.headerExtensions = media.rtp.headerExtensions.filter(
(extension) =>
(
this.configuration.headerExtensions[
media.kind as "video" | "audio"
] || []
).find((v) => v.uri === extension.uri)
);
transceiver.receiver.setupTWCC(media.ssrc[0]?.ssrc);
// # configure direction
const mediaDirection = media.direction || "inactive";
const direction = reverseDirection(mediaDirection);
if (["answer", "pranswer"].includes(description.type)) {
transceiver.currentDirection = direction;
} else {
transceiver.offerDirection = direction;
}
const local = this.localRtp(transceiver);
const { muxId, rtcp } = local;
if (muxId == undefined || rtcp == undefined) {
throw new Error("param missing");
}
transceiver.sender.parameters = { ...local, muxId, rtcp };
if (["recvonly", "sendrecv"].includes(transceiver.direction)) {
// register simulcast receiver
media.simulcastParameters.forEach((param) => {
this.router.registerRtpReceiverByRid(transceiver, param);
});
const params = this.remoteRtp(description, transceiver);
// register ssrc receiver
this.router.registerRtpReceiverBySsrc(transceiver, params);
}
if (["sendonly", "sendrecv"].includes(mediaDirection)) {
// assign msid
if (media.msid != undefined) {
const [streamId, trackId] = media.msid.split(" ");
transceiver.receiver.remoteStreamId = streamId;
transceiver.receiver.remoteTrackId = trackId;
this.fireOnTrack(
transceiver.receiver.track,
transceiver,
new MediaStream({
id: streamId,
tracks: [transceiver.receiver.track],
})
);
}
}
} else if (media.kind === "application") {
if (!this.sctpTransport) {
this.sctpTransport = this.createSctpTransport();
}
if (!this.sctpTransport.mid) {
this.sctpTransport.mid = media.rtp.muxId;
}
// # configure sctp
this.sctpRemotePort = media.sctpPort;
}
if (media.dtlsParams && media.iceParams) {
this.remoteDtls = media.dtlsParams;
this.remoteIce = media.iceParams;
}
// One agent full, one lite: The full agent MUST take the controlling role, and the lite agent MUST take the controlled role
// RFC 8445 S6.1.1
if (media.iceParams?.iceLite) {
this.iceTransport.connection.iceControlling = true;
}
// # add ICE candidates
media.iceCandidates.forEach(this.iceTransport.addRemoteCandidate);
await this.iceTransport.iceGather.gather();
if (media.iceCandidatesComplete) {
await this.iceTransport.addRemoteCandidate(undefined);
}
// # set DTLS role
if (description.type === "answer" && media.dtlsParams?.role) {
this.dtlsTransport.role =
media.dtlsParams.role === "client" ? "server" : "client";
}
}
// connect transports
if (description.type === "answer") {
this.connect().catch((err) => {
log("connect failed", err);
this.setConnectionState("failed");
});
}
if (description.type === "offer") {
this.setSignalingState("have-remote-offer");
} else if (description.type === "answer") {
this.setSignalingState("stable");
}
if (description.type === "answer") {
this.currentRemoteDescription = description;
this.pendingRemoteDescription = undefined;
} else {
this.pendingRemoteDescription = description;
}
this.negotiationneeded = false;
if (this.shouldNegotiationneeded) {
this.needNegotiation();
}
}
private fireOnTrack(
track: MediaStreamTrack,
transceiver: RTCRtpTransceiver,
stream: MediaStream
) {
const event: RTCTrackEvent = {
track,
streams: [stream],
transceiver,
receiver: transceiver.receiver,
};
this.emit("track", event);
if (this.ontrack) this.ontrack(event);
}
addTransceiver(
trackOrKind: Kind | MediaStreamTrack,
options: Partial<TransceiverOptions> = {}
) {
const kind =
typeof trackOrKind === "string" ? trackOrKind : trackOrKind.kind;
const direction = options.direction || "sendrecv";
const sender = new RTCRtpSender(trackOrKind, this.dtlsTransport);
const receiver = new RTCRtpReceiver(kind, this.dtlsTransport, sender.ssrc);
const transceiver = new RTCRtpTransceiver(
kind,
receiver,
sender,
direction,
this.dtlsTransport
);
transceiver.options = options;
this.router.registerRtpSender(transceiver.sender);
this.transceivers.push(transceiver);
this.onTransceiverAdded.execute(transceiver);
this.needNegotiation();
return transceiver;
}
getTransceivers() {
return this.transceivers;
}
getSenders() {
return this.getTransceivers().map((t) => t.sender);
}
getReceivers() {
return this.getTransceivers().map((t) => t.receiver);
}
// todo fix
addTrack(track: MediaStreamTrack, ms?: MediaStream) {
if (this.isClosed) throw new Error("is closed");
if (this.getSenders().find((sender) => sender.track?.uuid === track.uuid)) {
throw new Error("track exist");
}
const emptyTrackSender = this.transceivers.find(
(t) =>
t.sender.track == undefined &&
t.kind === track.kind &&
SenderDirections.includes(t.direction) === true
);
if (emptyTrackSender) {
const sender = emptyTrackSender.sender;
sender.registerTrack(track);
this.needNegotiation();
return sender;
}
const notSendTransceiver = this.transceivers.find(
(t) =>
t.sender.track == undefined &&
t.kind === track.kind &&
SenderDirections.includes(t.direction) === false &&
!t.usedForSender
);
if (notSendTransceiver) {
const sender = notSendTransceiver.sender;
sender.registerTrack(track);
switch (notSendTransceiver.direction) {
case "recvonly":
notSendTransceiver.direction = "sendrecv";
break;
case "inactive":
notSendTransceiver.direction = "sendonly";
break;
}
this.needNegotiation();
return sender;
} else {
const transceiver = this.addTransceiver(track, { direction: "sendrecv" });
this.needNegotiation();
return transceiver.sender;
}
}
async createAnswer() {
this.assertNotClosed();
if (
!["have-remote-offer", "have-local-pranswer"].includes(
this.signalingState
) ||
!this.dtlsTransport
)
throw new Error("createAnswer failed");
if (this.certificates.length === 0) {
await this.dtlsTransport.setupCertificate();
}
const description = new SessionDescription();
addSDPHeader("answer", description);
this._remoteDescription?.media.forEach((remoteM) => {
let dtlsTransport!: RTCDtlsTransport;
let media: MediaDescription;
if (["audio", "video"].includes(remoteM.kind)) {
const transceiver = this.getTransceiverByMid(remoteM.rtp.muxId!)!;
media = createMediaDescriptionForTransceiver(
transceiver,
this.cname,
andDirection(transceiver.direction, transceiver.offerDirection),
transceiver.mid!
);
if (!transceiver.dtlsTransport) throw new Error();
dtlsTransport = transceiver.dtlsTransport;
} else if (remoteM.kind === "application") {
if (!this.sctpTransport || !this.sctpTransport.mid) throw new Error();
media = createMediaDescriptionForSctp(
this.sctpTransport,
this.sctpTransport.mid
);
dtlsTransport = this.sctpTransport.dtlsTransport;
} else throw new Error();
// # determine DTLS role, or preserve the currently configured role
if (!media.dtlsParams) throw new Error();
if (dtlsTransport.role === "auto") {
media.dtlsParams.role = "client";
} else {
media.dtlsParams.role = dtlsTransport.role;
}
media.simulcastParameters = remoteM.simulcastParameters.map((v) => ({
...v,
direction: reverseSimulcastDirection(v.direction),
}));
description.media.push(media);
});
const bundle = new GroupDescription("BUNDLE", []);
description.media.forEach((media) => {
bundle.items.push(media.rtp.muxId!);
});
description.group.push(bundle);
return description.toJSON();
}
async close() {
if (this.isClosed) return;
this.isClosed = true;
this.setSignalingState("closed");
this.setConnectionState("closed");
this.transceivers.forEach((transceiver) => {
transceiver.receiver.stop();
transceiver.sender.stop();
});
if (this.sctpTransport) {
await this.sctpTransport.stop();
}
await this.dtlsTransport.stop();
await this.iceTransport.stop();
this.dispose();
log("peerConnection closed");
}
private assertNotClosed() {
if (this.isClosed) throw new Error("RTCPeerConnection is closed");