forked from x186k/deadsfu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pubsub.go
55 lines (42 loc) · 844 Bytes
/
pubsub.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
package main
import (
"sync"
"github.com/pion/rtp"
)
type Pubsub struct {
mu sync.RWMutex
subs []chan rtp.Packet
}
func (ps *Pubsub) Subscribe(ch chan rtp.Packet) *chan rtp.Packet {
ps.mu.Lock()
defer ps.mu.Unlock()
ps.subs = append(ps.subs, ch)
return &ps.subs[len(ps.subs)-1]
}
func (ps *Pubsub) Unubscribe(removed *chan rtp.Packet) {
ps.mu.Lock()
defer ps.mu.Unlock()
//close(*removed)
// delete slice trick
*removed = ps.subs[len(ps.subs)-1]
ps.subs[len(ps.subs)-1] = nil
ps.subs = ps.subs[:len(ps.subs)-1]
}
func (ps *Pubsub) Publish(p rtp.Packet) {
// faster lock period
ps.mu.RLock()
a := make([]chan rtp.Packet, len(ps.subs))
copy(a, ps.subs)
ps.mu.RUnlock()
discardOnBusy := true
for _, v := range a {
if discardOnBusy {
select {
case v <- p:
default:
}
} else {
v <- p
}
}
}