forked from jiyeyuran/mediasoup-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata_consumer.go
383 lines (316 loc) · 8.75 KB
/
data_consumer.go
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
package mediasoup
import (
"encoding/json"
"sync/atomic"
)
type DataConsumerOptions struct {
/**
* The id of the DataProducer to consume.
*/
DataProducerId string `json:"dataProducerId,omitempty"`
/**
* Just if consuming over SCTP.
* Whether data messages must be received in order. If true the messages will
* be sent reliably. Defaults to the value in the DataProducer if it has type
* 'sctp' or to true if it has type 'direct'.
*/
Ordered *bool `json:"ordered,omitempty"`
/**
* Just if consuming over SCTP.
* When ordered is false indicates the time (in milliseconds) after which a
* SCTP packet will stop being retransmitted. Defaults to the value in the
* DataProducer if it has type 'sctp' or unset if it has type 'direct'.
*/
MaxPacketLifeTime uint16 `json:"maxPacketLifeTime,omitempty"`
/**
* Just if consuming over SCTP.
* When ordered is false indicates the maximum number of times a packet will
* be retransmitted. Defaults to the value in the DataProducer if it has type
* 'sctp' or unset if it has type 'direct'.
*/
MaxRetransmits uint16 `json:"maxRetransmits,omitempty"`
/**
* Custom application data.
*/
AppData interface{} `json:"appData,omitempty"`
}
type DataConsumerStat struct {
Type string `json:"type,omitempty"`
Timestamp int64 `json:"timestamp,omitempty"`
Label string `json:"label,omitempty"`
Protocol string `json:"protocol,omitempty"`
MessagesSent int64 `json:"messagesSent,omitempty"`
BytesSent int64 `json:"bytesSent,omitempty"`
BufferedAmount uint32 `json:"bufferedAmount,omitempty"`
}
/**
* DataConsumer type.
*/
type DataConsumerType string
const (
DataConsumerType_Sctp DataConsumerType = "sctp"
DataConsumerType_Direct DataConsumerType = "direct"
)
type dataConsumerParams struct {
internal internalData
data dataConsumerData
channel *Channel
payloadChannel *PayloadChannel
appData interface{}
}
type dataConsumerData struct {
Type DataConsumerType
SctpStreamParameters *SctpStreamParameters
Label string
Protocol string
}
/**
* DataConsumer
* @emits transportclose
* @emits dataproducerclose
* @emits message - (message: Buffer, ppid: number)
* @emits sctpsendbufferfull
* @emits bufferedamountlow - (bufferedAmount: number)
* @emits @close
* @emits @dataproducerclose
*/
type DataConsumer struct {
IEventEmitter
logger Logger
// {
// routerId: string;
// transportId: string;
// dataProducerId: string;
// dataConsumerId: string;
// };
internal internalData
data dataConsumerData
channel *Channel
payloadChannel *PayloadChannel
appData interface{}
closed uint32
observer IEventEmitter
}
func newDataConsumer(params dataConsumerParams) *DataConsumer {
logger := NewLogger("DataConsumer")
logger.Debug("constructor()")
if params.appData == nil {
params.appData = H{}
}
consumer := &DataConsumer{
IEventEmitter: NewEventEmitter(),
logger: logger,
internal: params.internal,
data: params.data,
channel: params.channel,
payloadChannel: params.payloadChannel,
appData: params.appData,
observer: NewEventEmitter(),
}
consumer.handleWorkerNotifications()
return consumer
}
// DataConsumer id
func (c *DataConsumer) Id() string {
return c.internal.DataConsumerId
}
// Associated DataProducer id.
func (c *DataConsumer) DataProducerId() string {
return c.internal.DataProducerId
}
// Whether the DataConsumer is closed.
func (c *DataConsumer) Closed() bool {
return atomic.LoadUint32(&c.closed) > 0
}
// DataConsumer type.
func (c *DataConsumer) Type() DataConsumerType {
return c.data.Type
}
/**
* SCTP stream parameters.
*/
func (c *DataConsumer) SctpStreamParameters() *SctpStreamParameters {
return c.data.SctpStreamParameters
}
/**
* DataChannel label.
*/
func (c *DataConsumer) Label() string {
return c.data.Label
}
/**
* DataChannel protocol.
*/
func (c *DataConsumer) Protocol() string {
return c.data.Protocol
}
/**
* App custom data.
*/
func (c *DataConsumer) AppData() interface{} {
return c.appData
}
/**
* Observer.
*
* @emits close
*/
func (c *DataConsumer) Observer() IEventEmitter {
return c.observer
}
// Close the DataConsumer.
func (c *DataConsumer) Close() (err error) {
if atomic.CompareAndSwapUint32(&c.closed, 0, 1) {
c.logger.Debug("close()")
// Remove notification subscriptions.
c.channel.RemoveAllListeners(c.Id())
c.payloadChannel.RemoveAllListeners(c.Id())
response := c.channel.Request("dataConsumer.close", c.internal)
if err = response.Err(); err != nil {
c.logger.Error("dataConsumer close error: %s", err)
}
c.Emit("@close")
c.RemoveAllListeners()
// Emit observer event.
c.observer.SafeEmit("close")
c.observer.RemoveAllListeners()
}
return
}
// Transport was closed.
func (c *DataConsumer) transportClosed() {
if atomic.CompareAndSwapUint32(&c.closed, 0, 1) {
c.logger.Debug("transportClosed()")
// Remove notification subscriptions.
c.channel.RemoveAllListeners(c.Id())
c.payloadChannel.RemoveAllListeners(c.Id())
c.SafeEmit("transportclose")
c.RemoveAllListeners()
// Emit observer event.
c.observer.SafeEmit("close")
c.observer.RemoveAllListeners()
}
}
// Dump DataConsumer.
func (c *DataConsumer) Dump() (data DataConsumerDump, err error) {
c.logger.Debug("dump()")
resp := c.channel.Request("dataConsumer.dump", c.internal)
err = resp.Unmarshal(&data)
return
}
// Get DataConsumer stats.
func (c *DataConsumer) GetStats() (stats []*DataConsumerStat, err error) {
c.logger.Debug("getStats()")
resp := c.channel.Request("dataConsumer.getStats", c.internal)
err = resp.Unmarshal(&stats)
return
}
/**
* Set buffered amount low threshold.
*/
func (c *DataConsumer) SetBufferedAmountLowThreshold(threshold int) error {
c.logger.Debug("setBufferedAmountLowThreshold() [threshold:%s]", threshold)
resp := c.channel.Request("dataConsumer.setBufferedAmountLowThreshold", c.internal, H{
"threshold": threshold,
})
return resp.Err()
}
/**
* Send data.
*/
func (c *DataConsumer) Send(data []byte, ppid ...int) (err error) {
/*
* +-------------------------------+----------+
* | Value | SCTP |
* | | PPID |
* +-------------------------------+----------+
* | WebRTC String | 51 |
* | WebRTC Binary Partial | 52 |
* | (Deprecated) | |
* | WebRTC Binary | 53 |
* | WebRTC String Partial | 54 |
* | (Deprecated) | |
* | WebRTC String Empty | 56 |
* | WebRTC Binary Empty | 57 |
* +-------------------------------+----------+
*/
ppidVal := 0
if len(ppid) == 0 {
if len(data) > 0 {
ppidVal = 53
} else {
ppidVal = 57
}
} else {
ppidVal = ppid[0]
}
if ppidVal == 56 || ppidVal == 57 {
data = make([]byte, 1)
}
resp := c.payloadChannel.Request("dataConsumer.send", c.internal, H{"ppid": ppid}, data)
return resp.Err()
}
/**
* Send text.
*/
func (c *DataConsumer) SendText(message string) error {
ppid := 51
if len(message) == 0 {
ppid = 56
}
return c.Send([]byte(message), ppid)
}
/**
* Get buffered amount size.
*/
func (c *DataConsumer) GetBufferedAmount() (bufferedAmount int64, err error) {
c.logger.Debug("getBufferedAmount()")
resp := c.channel.Request("dataConsumer.getBufferedAmount", c.internal)
var result struct {
BufferAmount int64
}
err = resp.Unmarshal(&result)
return result.BufferAmount, err
}
func (c *DataConsumer) handleWorkerNotifications() {
c.channel.On(c.Id(), func(event string, data []byte) {
switch event {
case "dataproducerclose":
if atomic.CompareAndSwapUint32(&c.closed, 0, 1) {
c.channel.RemoveAllListeners(c.internal.DataConsumerId)
c.payloadChannel.RemoveAllListeners(c.internal.DataConsumerId)
c.Emit("@dataproducerclose")
c.SafeEmit("dataproducerclose")
c.RemoveAllListeners()
// Emit observer event.
c.observer.SafeEmit("close")
c.observer.RemoveAllListeners()
}
case "sctpsendbufferfull":
c.SafeEmit("sctpsendbufferfull")
case "bufferedamountlow":
var result struct {
BufferAmount int64
}
json.Unmarshal(data, &result)
c.SafeEmit("bufferedamountlow", result.BufferAmount)
default:
c.logger.Error(`ignoring unknown event "%s" in channel listener`, event)
}
})
c.payloadChannel.On(c.Id(), func(event string, data, payload []byte) {
switch event {
case "message":
if c.Closed() {
return
}
var result struct {
Ppid int
}
json.Unmarshal(data, &result)
c.SafeEmit("message", payload, result.Ppid)
default:
c.logger.Error(`ignoring unknown event "%s" in payload channel listener`, event)
}
})
}