-
-
Notifications
You must be signed in to change notification settings - Fork 94
Expand file tree
/
Copy pathjanus_video_room_plugin.dart
More file actions
366 lines (339 loc) · 14.3 KB
/
Copy pathjanus_video_room_plugin.dart
File metadata and controls
366 lines (339 loc) · 14.3 KB
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
part of janus_client;
/// Quality tiers used when switching among simulcast layers.
enum ConfigureStreamQuality { LOW, MEDIUM, HIGH }
/// Represents a single remote simulcast layer configuration request.
class ConfigureStream {
String? mid;
bool? send;
int? fallback;
int? audio_level_average;
int? audio_active_packets;
int? min_delay;
int? max_delay;
ConfigureStreamQuality? substream;
ConfigureStreamQuality? temporal;
ConfigureStreamQuality? spatial_layer;
ConfigureStreamQuality? temporal_layer;
ConfigureStream({
this.mid,
this.substream,
this.temporal,
this.spatial_layer,
this.temporal_layer,
this.send,
this.fallback,
this.audio_level_average,
this.audio_active_packets,
this.min_delay,
this.max_delay,
});
/// Converts this configuration into the Janus wire-format map, omitting nulls.
Map<String, dynamic> toMap() {
return {
'mid': mid,
'send': send,
'substream': substream?.index,
'temporal': temporal?.index,
'spatial_layer': spatial_layer?.index,
'temporal_layer': temporal_layer?.index,
'fallback': fallback,
'audio_level_average': audio_level_average,
'audio_active_packets': audio_active_packets,
'min_delay': min_delay,
'max_delay': max_delay,
}..removeWhere((key, value) => value == null);
}
/// Builds a [ConfigureStream] from a Janus plugindata map.
factory ConfigureStream.fromMap(Map<String, dynamic> map) {
return ConfigureStream(
mid: map['mid'],
substream: map['substream'] != null ? ConfigureStreamQuality.values[map['substream']] : null,
temporal: map['temporal'] != null ? ConfigureStreamQuality.values[map['temporal']] : null,
spatial_layer: map['spatial_layer'] != null ? ConfigureStreamQuality.values[map['spatial_layer']] : null,
temporal_layer: map['temporal_layer'] != null ? ConfigureStreamQuality.values[map['temporal_layer']] : null,
send: map['send'],
fallback: map['fallback']?.toInt(),
audio_level_average: map['audio_level_average']?.toInt(),
audio_active_packets: map['audio_active_packets']?.toInt(),
min_delay: map['min_delay']?.toInt(),
max_delay: map['max_delay']?.toInt(),
);
}
/// Serialises this configuration to JSON for storage/debugging.
String toJson() => json.encode(toMap());
/// Parses a configuration instance from JSON.
factory ConfigureStream.fromJson(String source) => ConfigureStream.fromMap(json.decode(source));
@override
String toString() {
return '''ConfigureStream(mid: $mid,
substream: $substream,
temporal: $temporal,
spatial_layer: $spatial_layer,
temporal_layer: $temporal_layer,
send: $send, fallback: $fallback, audio_level_average: $audio_level_average, audio_active_packets: $audio_active_packets, min_delay: $min_delay, max_delay: $max_delay)''';
}
}
/// Wrapper around the Janus VideoRoom plugin with typed helpers.
class JanusVideoRoomPlugin extends JanusPlugin {
JanusVideoRoomPlugin({handleId, context, transport, session})
: super(context: context, handleId: handleId, plugin: JanusPlugins.VIDEO_ROOM, session: session, transport: transport);
/// Updates mutable room properties such as description, pin, or publisher caps.
///
/// Pass any field that needs to change; absent values remain untouched on Janus.
Future<dynamic> editRoom(dynamic roomId,
{String? secret,
String? newDescription,
String? newSecret,
String? newPin,
String? newIsPrivate,
String? newRequirePvtId,
String? newBitrate,
String? newFirFreq,
int? newPublisher,
bool? newLockRecord,
Map? extras,
bool? permanent}) async {
var payload = {
"request": "edit",
"room": roomId,
...?extras,
if (secret != null) "secret": secret,
if (newDescription != null) "new_description": newDescription,
if (newSecret != null) "new_secret": newSecret,
if (newPin != null) "new_pin": newPin,
if (newIsPrivate != null) "new_is_private": newIsPrivate,
if (newRequirePvtId != null) "new_require_pvtid": newRequirePvtId,
if (newBitrate != null) "new_bitrate": newBitrate,
if (newFirFreq != null) "new_fir_freq": newFirFreq,
if (newPublisher != null) "new_publishers": newPublisher,
if (newLockRecord != null) "new_lock_record": newLockRecord,
if (permanent != null) "permanent": permanent
};
_handleRoomIdTypeDifference(payload);
return (await this.send(data: payload));
}
/// Permanently removes an existing room, optionally using the admin [secret].
Future<dynamic> destroyRoom(dynamic roomId, {String? secret, bool? permanent}) async {
var payload = {"request": "destroy", "room": roomId, if (secret != null) "secret": secret, if (permanent != null) "permanent": permanent};
_handleRoomIdTypeDifference(payload);
return (await this.send(data: payload));
}
/// Creates a new room with the provided identifier and metadata.
///
/// Set [permanent] to `true` to persist the room across Janus restarts.
Future<dynamic> createRoom(dynamic roomId,
{bool permanent = false, String? pin, Map<String, dynamic>? extras, List<String>? allowed, String? isPrivate, String description = '', String? secret}) async {
var payload = {"request": "create", "room": roomId, "permanent": permanent, "description": description, ...?extras};
if (allowed != null) payload["allowed"] = allowed;
if (isPrivate != null) payload["is_private"] = isPrivate;
if (secret != null) payload['secret'] = secret;
if (pin != null) payload['pin'] = pin;
_handleRoomIdTypeDifference(payload);
return (await this.send(data: payload));
}
/// Fetches the active publishers currently joined to [roomId].
Future<VideoRoomListParticipantsResponse?> getRoomParticipants(dynamic roomId) async {
var payload = {"request": "listparticipants", "room": roomId};
Map data = await this.send(data: payload);
_handleRoomIdTypeDifference(payload);
return _getPluginDataFromPayload<VideoRoomListParticipantsResponse>(data, VideoRoomListParticipantsResponse.fromJson);
}
// prevent duplication
T? _getPluginDataFromPayload<T>(dynamic data, T Function(dynamic) fromJson) {
if (data.containsKey('janus') && data['janus'] == 'success' && data.containsKey('plugindata')) {
var dat = data['plugindata']['data'];
return fromJson(dat);
} else {
return null;
}
}
/// Lists rooms exposed by the Janus instance, including static ones.
Future<VideoRoomListResponse?> getRooms() async {
var payload = {"request": "list"};
Map data = await this.send(data: payload);
return _getPluginDataFromPayload<VideoRoomListResponse>(data, VideoRoomListResponse.fromJson);
}
/// Joins [roomId] as a publisher, advertising [displayName] to other participants.
///
/// Provide [pin] or [token] if the room requires authentication.
Future<void> joinPublisher(dynamic roomId, {String? pin, int? id, String? token, String? displayName}) async {
var payload = {
"request": "join",
"ptype": "publisher",
"room": roomId,
"pin": pin,
"id": id,
"display": displayName,
"token": token,
}..removeWhere((key, value) => value == null);
_handleRoomIdTypeDifference(payload);
await this.send(data: payload);
}
/// Subscribes to the listed publisher [streams], optionally sending a custom offer.
Future<void> subscribeToStreams(List<PublisherStream> streams, {RTCSessionDescription? offer}) async {
if (streams.length > 0) {
var payload = {'request': "subscribe", 'streams': streams.map((e) => e.toMap()..removeWhere((key, value) => value == null)).toList()};
await this.send(data: payload, jsep: offer);
}
}
/// Dynamically adds or removes simulcast streams on an existing subscription.
Future<void> update({List<SubscriberUpdateStream>? subscribe, List<SubscriberUpdateStream>? unsubscribe}) async {
if (subscribe?.isEmpty == true && unsubscribe?.isEmpty == true) {
return;
}
Map<String, dynamic> payload = {
'request': "update",
};
if (subscribe?.isNotEmpty == true) {
payload['subscribe'] = subscribe?.map((e) => e.toMap()..removeWhere((key, value) => value == null)).toList();
}
if (unsubscribe?.isNotEmpty == true) {
payload['unsubscribe'] = unsubscribe?.map((e) => e.toMap()..removeWhere((key, value) => value == null)).toList();
}
await this.send(data: payload);
}
/// Acknowledges the attach as a subscriber and starts receiving media.
Future<void> start(dynamic roomId, {RTCSessionDescription? answer}) async {
var payload = {"request": "start", 'room': roomId};
if (answer == null) {
answer = await this.createAnswer();
}
await this.send(data: payload, jsep: answer);
}
/// Joins [roomId] as a subscriber against [feedId] and requested [streams].
///
/// Use [privateId] returned from `joinPublisher` to correlate events in SFU cascading setups.
Future<dynamic> joinSubscriber(
dynamic roomId, {
List<PublisherStream>? streams,
int? privateId,
int? feedId,
String? pin,
String? token,
}) async {
var payload = {
"request": "join",
"room": roomId,
"ptype": "subscriber",
"pin": pin,
"token": token,
"feed": feedId,
"private_id": privateId,
"streams": streams?.map((e) => e.toMap()..removeWhere((key, value) => value == null)).toList(),
}..removeWhere((key, value) => value == null);
_handleRoomIdTypeDifference(payload);
await this.send(data: payload);
}
/// Publishes local media to existing subscribers, creating an offer when missing.
///
/// Adjust [bitrate], [record], or [descriptions] to tweak the upstream settings.
Future<void> publishMedia(
{String? audioCodec,
String? videCodec,
int? bitrate,
bool? record,
String? filename,
String? newDisplayName,
int? audioLevelAverage,
int? audioActivePackets,
List<Map<String, String?>>? descriptions,
RTCSessionDescription? offer}) async {
var payload = {
"request": "publish",
"audiocodec": audioCodec,
"videocodec": videCodec,
"bitrate": bitrate,
"record": record,
"filename": filename,
"display": newDisplayName,
"audio_level_average": audioLevelAverage,
"audio_active_packets": audioActivePackets,
"descriptions": descriptions
}..removeWhere((key, value) => value == null);
if (offer == null) {
offer = await this.createOffer(audioRecv: false, videoRecv: false);
}
await this.send(data: payload, jsep: offer);
}
/// Reconfigures an ongoing publisher session (bitrate, recording, layers, etc.).
Future<void> configure(
{int? bitrate,
bool? keyframe,
bool? record,
String? filename,
String? display,
dynamic audioActivePackets,
int? audioLevelAverage,
List<Map<String, String>>? descriptions,
List<ConfigureStream>? streams,
bool? restart,
RTCSessionDescription? sessionDescription}) async {
var payload = {
"request": "configure",
"bitrate": bitrate,
"keyframe": keyframe,
"record": record,
"filename": filename,
"display": display,
"audio_active_packets": audioActivePackets,
"audio_level_average": audioLevelAverage,
"streams": streams?.map((e) => e.toMap()).toList(),
"restart": restart,
"descriptions": descriptions
}..removeWhere((key, value) => value == null);
await this.send(data: payload, jsep: sessionDescription);
}
/// Stops receiving the specified [streams] while remaining attached.
Future<void> unsubscribe({List<UnsubscribeStreams>? streams}) async {
var payload = {"request": "unsubscribe", "streams": streams?.map((e) => e.toMap()..removeWhere((key, value) => value == null)).toList()}
..removeWhere((key, value) => value == null);
await this.send(data: payload);
}
/// Requests Janus to tear down the current publisher PeerConnection.
Future<void> unpublish() async {
await this.send(data: {"request": "unpublish"});
}
/// Tears down the subscriber connection and sends a `leave` request.
Future<void> hangup({bool disposeStream = true}) async {
await super.hangup(disposeStream: disposeStream);
await this.send(data: {"request": "leave"});
}
bool _onCreated = false;
/// Converts raw plugindata payloads into typed video-room events.
@override
void onCreate() {
if (_onCreated) {
return;
}
_onCreated = true;
messages?.listen((event) {
TypedEvent<JanusEvent> typedEvent = TypedEvent<JanusEvent>(event: JanusEvent.fromJson(event.event), jsep: event.jsep);
var data = typedEvent.event.plugindata?.data;
if (data == null) return;
if (data['videoroom'] == 'joined') {
typedEvent.event.plugindata?.data = VideoRoomJoinedEvent.fromJson(data);
_typedMessagesSink?.add(typedEvent);
} else if (data['videoroom'] == 'event' && data['unpublished'] != null && data['unpublished'] is int) {
typedEvent.event.plugindata?.data = VideoRoomUnPublishedEvent.fromJson(data);
_typedMessagesSink?.add(typedEvent);
} else if (data['videoroom'] == 'updated' && data['streams'] != null) {
typedEvent.event.plugindata?.data = VideoRoomUpdatedEvent.fromJson(data);
_typedMessagesSink?.add(typedEvent);
} else if (data['videoroom'] == 'event' && data['configured'] == "ok") {
typedEvent.event.plugindata?.data = VideoRoomConfigured.fromJson(data);
_typedMessagesSink?.add(typedEvent);
} else if (data['videoroom'] == 'event' && data['publishers'] != null) {
typedEvent.event.plugindata?.data = VideoRoomNewPublisherEvent.fromJson(data);
_typedMessagesSink?.add(typedEvent);
} else if (data['videoroom'] == 'event' && data['leaving'] != null && data['leaving'].runtimeType == int) {
typedEvent.event.plugindata?.data = VideoRoomLeavingEvent.fromJson(data);
_typedMessagesSink?.add(typedEvent);
} else if (data['videoroom'] == 'attached' || data['streams'] != null) {
typedEvent.event.plugindata?.data = VideoRoomAttachedEvent.fromJson(data);
_typedMessagesSink?.add(typedEvent);
} else if (data['videoroom'] == 'event' && (data['error_code'] != null || data['result']?['code'] != null)) {
_typedMessagesSink?.addError(JanusError.fromMap(data));
}
});
}
}