-
Notifications
You must be signed in to change notification settings - Fork 2
/
peer.dart
217 lines (178 loc) · 7.32 KB
/
peer.dart
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
/// A Peer on the client side. This is a remote client. The local peer is not represented as a Peer object!
///
/// Only Peer2Peer connections will be wrapped by the Peer class
part of webrtc_utils.client;
/// Peer interface class
abstract class Peer /*<C extends P2PClient>*/ {
/// An integer representing the global id of this peer according to the
/// [SignalingServer]. This id must be unique for each SignalingServer connection
/// but might be re-used for multiple rooms.
int get id;
/// The room this Peer belongs to.
PeerRoom get room;
/*
/// A reference to the [P2PClient]
C get client;
*/
/// Map of [RtcDataChannel.label] to the channel
Map<String, RtcDataChannel> get channels;
/// Can be listened to, to get notified when a stream gets added
Stream<MediaStreamEvent> get onAddStream;
/// Can be listened to, to get notified when a stream gets removed
Stream<MediaStreamEvent> get onRemoveStream;
/// Can be listened to, to get informed when a new [RtcDataChannel] was created.
///
/// Note: You have to wait for the [RtcDataChannel.onOpen] event to be able
/// to send messages.
Stream<RtcDataChannel> get onChannel;
/// Signals to create a new [RtcDataChannel] with this peer.
void createChannel(String label, [Map options = null]);
/// Adds a stream to this peer
///
/// The [ms] can be loaded using [window.navigator.getUserMedia].
///
/// The [mediaConstraints] map specifies mandatory/optional constraints for
/// the stream.
///
/// TODO(rh): Example configuration
void addStream(MediaStream ms, [Map<String, String> mediaConstraints]);
/// Removes a stream from this peer
void removeStream(MediaStream ms);
}
/// An interface for a protocol peer that extends the regular peer
abstract class ProtocolPeer /*<C extends P2PClient>*/ extends Peer /*<C>*/ {
/// Map of [RtcDataChannel.label] to a [DataChannelProtocol]
Map<String, DataChannelProtocol> get protocols;
/// Stream that can be listened to, to get notified when a new protocol is ready
/// to be used. This means that this stream will fire events after the
/// [RtcDataChannel.onOpen] event was fired and the underlying [RtcDataChanenl]
/// is ready to use
Stream<DataChannelProtocol> get onProtocol;
}
/// A peer represents a machine/browser in the system. This is the internal
/// implementation of the [Peer] interface.
class _Peer<C extends _P2PClient> implements Peer {
final int id;
final _PeerRoom room;
final RtcPeerConnection _pc;
final C client;
Stream<MediaStreamEvent> get onAddStream => _pc.onAddStream;
Stream<MediaStreamEvent> get onRemoveStream => _pc.onRemoveStream;
Stream<RtcDataChannel> get onChannel => _onChannelController.stream;
StreamController<RtcDataChannel> _onChannelController =
new StreamController.broadcast();
final Map<String, RtcDataChannel> channels = {};
/// Internal constructor that is called from the [P2PClient]
_Peer(this.room, this.id, C client, [Map mediaConstraints = const {
'optional': const [const {'DtlsSrtpKeyAgreement': true}]
}])
: this.client = client,
_pc = new RtcPeerConnection(client.rtcConfiguration, mediaConstraints) {
_pc.onNegotiationNeeded.listen((Event ev) {
print('[$this] Connection.negotiationNeeded');
// Send offer to the other peer
_pc.createOffer({}).then((RtcSessionDescription desc) {
_pc.setLocalDescription(desc).then((_) {
client._signalingChannel
.send(new SessionDescriptionMessage(room.name, id, desc));
});
}).catchError((err) {
print('[$this] Error at offer: $err');
});
});
_pc.onIceCandidate.listen((RtcIceCandidateEvent ev) {
if (ev.candidate != null) {
client._signalingChannel
.send(new IceCandidateMessage(room.name, id, ev.candidate));
}
});
_pc.onDataChannel.listen((RtcDataChannelEvent ev) {
_notifyChannelCreated(ev.channel);
});
// // DEBUG
// _pc.onSignalingStateChange.listen((Event ev) {
// print('[Event] SignalingStateChange: ${_pc.signalingState}');
// });
//
// _pc.onIceConnectionStateChange.listen((Event ev) {
// print('[Event] IceConnectionStateChange: ${_pc.iceConnectionState} (${_pc.iceGatheringState})');
// });
}
/// Internal helper function to add a [RtcDataChannel] to the stream. This will
/// be called directly when creating a channel or when the remote peer opens
/// a connection.
void _notifyChannelCreated(RtcDataChannel channel) {
channels[channel.label] = channel;
channel.onClose.listen((Event ev) {
channels.remove(channel.label);
});
_onChannelController.add(channel);
}
/// See [Peer.createChannel]
void createChannel(String label, [Map options = null]) {
_notifyChannelCreated(_pc.createDataChannel(label, options));
}
/// See [Peer.addStream]
void addStream(MediaStream ms, [Map<String, String> mediaConstraints]) {
_pc.addStream(ms);
}
/// See [Peer.removeStream]
void removeStream(MediaStream ms) {
// TODO(rh): Should we use _pc.getLocalStreams() and see if [ms] is in there?
_pc.removeStream(ms);
}
/// Called internally by [_PeerRoom.onSignalingMessage] to handle the message
/// locally.
void _handleSignalingMessage(SignalingMessage sm) {
if (sm is SessionDescriptionMessage) {
RtcSessionDescription desc = sm.description;
if (desc.type == 'offer') {
_pc.setRemoteDescription(desc).then((_) {
_pc.createAnswer().then((RtcSessionDescription answer) {
_pc.setLocalDescription(answer).then((_) {
client._signalingChannel
.send(new SessionDescriptionMessage(room.name, id, answer));
});
});
});
} else {
_pc.setRemoteDescription(desc);
}
} else if (sm is IceCandidateMessage) {
_pc.addIceCandidate(sm.candidate, () {/* ... */}, (error) {
print('[ERROR] Unable to add IceCandidateMessage: $error');
});
}
}
String toString() => 'Peer#$id';
}
/// The [_ProtocolPeer] extends [_Peer] that by adding a [DataChannelProtocol] on top to the [RtcDataChannel].
/// It uses the [RtcDataChannel.protocol] property and a [ProtocolProvider] to provide application
/// specific protocols.
class _ProtocolPeer extends _Peer<_ProtocolP2PClient>
implements ProtocolPeer /*<_ProtocolP2PClient>*/ {
Stream<DataChannelProtocol> get onProtocol => _onProtocolController.stream;
StreamController<DataChannelProtocol> _onProtocolController =
new StreamController.broadcast();
final Map<String, DataChannelProtocol> protocols = {};
/// Library-internal constructor
_ProtocolPeer(room, id, client) : super(room, id, client);
@override
void _notifyChannelCreated(RtcDataChannel channel) {
super._notifyChannelCreated(channel);
DataChannelProtocol protocol =
client._protocolProvider.provide(this, channel);
print('[$this] Protocol: $protocol');
if (protocol != null) {
channel.onOpen.listen((Event ev) {
print('Channel is open: ${channel.label}');
_onProtocolController.add(protocol);
});
protocols[protocol.channel.label] = protocol;
} else {
throw "Protocol returned by ProtocolProvider ${client._protocolProvider} should not be null";
}
}
/// Returns a string representation for this ProtocolPeer
String toString() => 'ProtocolPeer#$id';
}