-
Notifications
You must be signed in to change notification settings - Fork 253
Expand file tree
/
Copy pathOutgoingDataStreamManager.ts
More file actions
321 lines (287 loc) · 9.07 KB
/
OutgoingDataStreamManager.ts
File metadata and controls
321 lines (287 loc) · 9.07 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
import { Mutex } from '@livekit/mutex';
import {
DataPacket,
DataPacket_Kind,
DataStream_ByteHeader,
DataStream_Chunk,
DataStream_Header,
DataStream_OperationType,
DataStream_TextHeader,
DataStream_Trailer,
Encryption_Type,
} from '@livekit/protocol';
import { type StructuredLogger } from '../../../logger';
import type RTCEngine from '../../RTCEngine';
import { EngineEvent } from '../../events';
import type {
ByteStreamInfo,
SendFileOptions,
SendTextOptions,
StreamBytesOptions,
StreamTextOptions,
TextStreamInfo,
} from '../../types';
import { numberToBigInt, splitUtf8 } from '../../utils';
import { ByteStreamWriter, TextStreamWriter } from './StreamWriter';
const STREAM_CHUNK_SIZE = 15_000;
/**
* Manages sending custom user data via data channels.
* @internal
*/
export default class OutgoingDataStreamManager {
protected engine: RTCEngine;
protected log: StructuredLogger;
constructor(engine: RTCEngine, log: StructuredLogger) {
this.engine = engine;
this.log = log;
}
setupEngine(engine: RTCEngine) {
this.engine = engine;
}
/** {@inheritDoc LocalParticipant.sendText} */
async sendText(text: string, options?: SendTextOptions): Promise<TextStreamInfo> {
const streamId = crypto.randomUUID();
const textInBytes = new TextEncoder().encode(text);
const totalTextLength = textInBytes.byteLength;
const fileIds = options?.attachments?.map(() => crypto.randomUUID());
const progresses = new Array<number>(fileIds ? fileIds.length + 1 : 1).fill(0);
const handleProgress = (progress: number, idx: number) => {
progresses[idx] = progress;
const totalProgress = progresses.reduce((acc, val) => acc + val, 0);
options?.onProgress?.(totalProgress);
};
const writer = await this.streamText({
streamId,
totalSize: totalTextLength,
destinationIdentities: options?.destinationIdentities,
topic: options?.topic,
attachedStreamIds: fileIds,
attributes: options?.attributes,
});
await writer.write(text);
// set text part of progress to 1
handleProgress(1, 0);
await writer.close();
if (options?.attachments && fileIds) {
await Promise.all(
options.attachments.map(async (file, idx) =>
this._sendFile(fileIds[idx], file, {
topic: options.topic,
mimeType: file.type,
onProgress: (progress) => {
handleProgress(progress, idx + 1);
},
}),
),
);
}
return writer.info;
}
/**
* @internal
*/
async streamText(options?: StreamTextOptions): Promise<TextStreamWriter> {
const streamId = options?.streamId ?? crypto.randomUUID();
const info: TextStreamInfo = {
id: streamId,
mimeType: 'text/plain',
timestamp: Date.now(),
topic: options?.topic ?? '',
size: options?.totalSize,
attributes: options?.attributes,
encryptionType: this.engine.e2eeManager?.isDataChannelEncryptionEnabled
? Encryption_Type.GCM
: Encryption_Type.NONE,
attachedStreamIds: options?.attachedStreamIds,
};
const header = new DataStream_Header({
streamId,
mimeType: info.mimeType,
topic: info.topic,
timestamp: numberToBigInt(info.timestamp),
totalLength: numberToBigInt(options?.totalSize),
attributes: info.attributes,
contentHeader: {
case: 'textHeader',
value: new DataStream_TextHeader({
version: options?.version,
attachedStreamIds: info.attachedStreamIds,
replyToStreamId: options?.replyToStreamId,
operationType:
options?.type === 'update'
? DataStream_OperationType.UPDATE
: DataStream_OperationType.CREATE,
}),
},
});
const destinationIdentities = options?.destinationIdentities;
const packet = new DataPacket({
destinationIdentities,
value: {
case: 'streamHeader',
value: header,
},
});
await this.engine.sendDataPacket(packet, DataPacket_Kind.RELIABLE);
let chunkId = 0;
const engine = this.engine;
const writableStream = new WritableStream<string>({
// Implement the sink
async write(text) {
for (const textByteChunk of splitUtf8(text, STREAM_CHUNK_SIZE)) {
const chunk = new DataStream_Chunk({
content: textByteChunk,
streamId,
chunkIndex: numberToBigInt(chunkId),
});
const chunkPacket = new DataPacket({
destinationIdentities,
value: {
case: 'streamChunk',
value: chunk,
},
});
await engine.sendDataPacket(chunkPacket, DataPacket_Kind.RELIABLE);
chunkId += 1;
}
},
async close() {
const trailer = new DataStream_Trailer({
streamId,
});
const trailerPacket = new DataPacket({
destinationIdentities,
value: {
case: 'streamTrailer',
value: trailer,
},
});
await engine.sendDataPacket(trailerPacket, DataPacket_Kind.RELIABLE);
},
abort(err) {
console.log('Sink error:', err);
// TODO handle aborts to signal something to receiver side
},
});
let onEngineClose = async () => {
await writer.close();
};
engine.once(EngineEvent.Closing, onEngineClose);
const writer = new TextStreamWriter(writableStream, info, () =>
this.engine.off(EngineEvent.Closing, onEngineClose),
);
return writer;
}
async sendFile(file: File, options?: SendFileOptions): Promise<{ id: string }> {
const streamId = crypto.randomUUID();
await this._sendFile(streamId, file, options);
return { id: streamId };
}
private async _sendFile(streamId: string, file: File, options?: SendFileOptions) {
const writer = await this.streamBytes({
streamId,
totalSize: file.size,
name: file.name,
mimeType: options?.mimeType ?? file.type,
topic: options?.topic,
destinationIdentities: options?.destinationIdentities,
});
const reader = file.stream().getReader();
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
await writer.write(value);
}
await writer.close();
return writer.info;
}
async streamBytes(options?: StreamBytesOptions) {
const streamId = options?.streamId ?? crypto.randomUUID();
const destinationIdentities = options?.destinationIdentities;
const info: ByteStreamInfo = {
id: streamId,
mimeType: options?.mimeType ?? 'application/octet-stream',
topic: options?.topic ?? '',
timestamp: Date.now(),
attributes: options?.attributes,
size: options?.totalSize,
name: options?.name ?? 'unknown',
encryptionType: this.engine.e2eeManager?.isDataChannelEncryptionEnabled
? Encryption_Type.GCM
: Encryption_Type.NONE,
};
const header = new DataStream_Header({
totalLength: numberToBigInt(info.size ?? 0),
mimeType: info.mimeType,
streamId,
topic: info.topic,
timestamp: numberToBigInt(Date.now()),
attributes: info.attributes,
contentHeader: {
case: 'byteHeader',
value: new DataStream_ByteHeader({
name: info.name,
}),
},
});
const packet = new DataPacket({
destinationIdentities,
value: {
case: 'streamHeader',
value: header,
},
});
await this.engine.sendDataPacket(packet, DataPacket_Kind.RELIABLE);
let chunkId = 0;
const writeMutex = new Mutex();
const engine = this.engine;
const logLocal = this.log;
const writableStream = new WritableStream<Uint8Array>({
async write(chunk) {
const unlock = await writeMutex.lock();
let byteOffset = 0;
try {
while (byteOffset < chunk.byteLength) {
const subChunk = chunk.slice(byteOffset, byteOffset + STREAM_CHUNK_SIZE);
const chunkPacket = new DataPacket({
destinationIdentities,
value: {
case: 'streamChunk',
value: new DataStream_Chunk({
content: subChunk,
streamId,
chunkIndex: numberToBigInt(chunkId),
}),
},
});
await engine.sendDataPacket(chunkPacket, DataPacket_Kind.RELIABLE);
chunkId += 1;
byteOffset += subChunk.byteLength;
}
} finally {
unlock();
}
},
async close() {
const trailer = new DataStream_Trailer({
streamId,
});
const trailerPacket = new DataPacket({
destinationIdentities,
value: {
case: 'streamTrailer',
value: trailer,
},
});
await engine.sendDataPacket(trailerPacket, DataPacket_Kind.RELIABLE);
},
abort(err) {
logLocal.error('Sink error:', err);
},
});
const byteWriter = new ByteStreamWriter(writableStream, info);
return byteWriter;
}
}