-
Notifications
You must be signed in to change notification settings - Fork 78
/
Peer.js
109 lines (91 loc) · 2.54 KB
/
Peer.js
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
module.exports = class Peer {
constructor(socket_id, name) {
this.id = socket_id
this.name = name
this.transports = new Map()
this.consumers = new Map()
this.producers = new Map()
}
addTransport(transport) {
this.transports.set(transport.id, transport)
}
async connectTransport(transport_id, dtlsParameters) {
if (!this.transports.has(transport_id)) return
await this.transports.get(transport_id).connect({
dtlsParameters: dtlsParameters
})
}
async createProducer(producerTransportId, rtpParameters, kind) {
//TODO handle null errors
let producer = await this.transports.get(producerTransportId).produce({
kind,
rtpParameters
})
this.producers.set(producer.id, producer)
producer.on(
'transportclose',
function () {
console.log('Producer transport close', { name: `${this.name}`, consumer_id: `${producer.id}` })
producer.close()
this.producers.delete(producer.id)
}.bind(this)
)
return producer
}
async createConsumer(consumer_transport_id, producer_id, rtpCapabilities) {
let consumerTransport = this.transports.get(consumer_transport_id)
let consumer = null
try {
consumer = await consumerTransport.consume({
producerId: producer_id,
rtpCapabilities,
paused: false //producer.kind === 'video',
})
} catch (error) {
console.error('Consume failed', error)
return
}
if (consumer.type === 'simulcast') {
await consumer.setPreferredLayers({
spatialLayer: 2,
temporalLayer: 2
})
}
this.consumers.set(consumer.id, consumer)
consumer.on(
'transportclose',
function () {
console.log('Consumer transport close', { name: `${this.name}`, consumer_id: `${consumer.id}` })
this.consumers.delete(consumer.id)
}.bind(this)
)
return {
consumer,
params: {
producerId: producer_id,
id: consumer.id,
kind: consumer.kind,
rtpParameters: consumer.rtpParameters,
type: consumer.type,
producerPaused: consumer.producerPaused
}
}
}
closeProducer(producer_id) {
try {
this.producers.get(producer_id).close()
} catch (e) {
console.warn(e)
}
this.producers.delete(producer_id)
}
getProducer(producer_id) {
return this.producers.get(producer_id)
}
close() {
this.transports.forEach((transport) => transport.close())
}
removeConsumer(consumer_id) {
this.consumers.delete(consumer_id)
}
}