/
mediatrack-stream.ts
160 lines (132 loc) · 4.51 KB
/
mediatrack-stream.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
/*
* SPDX-FileCopyrightText: 2022 Tim Perry <tim@httptoolkit.tech>
* SPDX-License-Identifier: Apache-2.0
*/
import * as stream from 'stream';
import type * as NodeDataChannel from 'node-datachannel';
/**
* Turns a node-datachannel media track into a real Node.js stream, complete with
* buffering, backpressure (up to a point - if the buffer fills up, messages are dropped),
* and support for piping data elsewhere.
*/
export class MediaTrackStream extends stream.Duplex {
constructor(
private rawTrack: NodeDataChannel.Track,
streamOptions: {
// These are the only Duplex options supported:
readableHighWaterMark?: number | undefined;
writableHighWaterMark?: number | undefined;
allowHalfOpen?: boolean;
} = {}
) {
super({
allowHalfOpen: false, // Default to autoclose on end().
...streamOptions,
});
rawTrack.onMessage((msg) => {
this._totalBytesReceived += msg.byteLength;
if (!this._readActive) return; // If the buffer is full, drop messages.
// If the push is rejected, we pause reading until the next call to _read().
this._readActive = this.push(msg);
});
// When the DataChannel closes, the readable & writable ends close
rawTrack.onClosed(() => this.close());
rawTrack.onError((errMsg) => {
this.destroy(new Error(`Media track error: ${errMsg}`));
});
// Buffer all writes until the DataChannel opens
if (!rawTrack.isOpen()) {
this.cork();
rawTrack.onOpen(() => {
this.uncork();
this._isOpen = true;
this.emit('track-open');
});
} else {
setImmediate(() => {
this._isOpen = true;
this.emit('track-open');
});
}
}
private _isOpen = false;
get isOpen() {
return this._isOpen;
}
private _totalBytesSent = 0;
get totalBytesSent() {
return this._totalBytesSent;
}
private _totalBytesReceived = 0;
get totalBytesReceived() {
return this._totalBytesReceived;
}
private close() {
this.push(null);
this.destroy();
}
private _readActive = true;
_read() {
// Stop dropping messages, if the buffer filling up meant we were doing so before.
this._readActive = true;
}
_write(chunk: Buffer, _encoding: string, callback: (error: Error | null) => void) {
let sentOk: boolean;
if (this.rawTrack.isClosed()) {
// isClosed becomes true and writes start failing just before onClosed() fires, so here we
// drop pending writes as soon as we notice.
this.close();
return;
}
try {
sentOk = this.rawTrack.sendMessageBinary(chunk);
this._totalBytesSent += chunk.byteLength;
} catch (err: any) {
return callback(err);
}
if (sentOk) {
callback(null);
} else {
callback(new Error("Failed to write to media track"));
}
}
_writev(chunks: Array<{ chunk: any; encoding: BufferEncoding; }>, callback: (error?: Error | null) => void) {
let sentOk: boolean;
if (this.rawTrack.isClosed()) {
// isClosed becomes true and writes start failing just before onClosed() fires, so here we
// drop pending writes as soon as we notice.
this.close();
return;
}
try {
const combinedChunks = Buffer.concat(chunks.map(c => c.chunk));
sentOk = this.rawTrack.sendMessageBinary(combinedChunks);
this._totalBytesSent += combinedChunks.byteLength;
} catch (err: any) {
return callback(err);
}
if (sentOk) {
callback(null);
} else {
callback(new Error("Failed to write to media track"));
}
}
_final(callback: (error: Error | null) => void) {
if (!this.allowHalfOpen) this.destroy();
callback(null);
}
_destroy(maybeErr: Error | null, callback: (error: Error | null) => void) {
// When the stream is destroyed, we close the DataChannel.
this.rawTrack.close();
callback(maybeErr);
}
get direction() {
return this.rawTrack.direction();
}
get mid() {
return this.rawTrack.mid();
}
get type() {
return this.rawTrack.type();
}
}