/
queue.go
102 lines (84 loc) · 1.71 KB
/
queue.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
package sfu
import (
"context"
"errors"
"sync"
"sync/atomic"
"github.com/golang/glog"
"github.com/pion/webrtc/v3"
)
var (
ErrQueueIsClosed = errors.New("queue is closed")
)
type queue struct {
mutex sync.Mutex
opChan chan interface{}
IsOpen *atomic.Bool
}
type negotiationQueue struct {
Client *Client
SDP webrtc.SessionDescription
AnswerChan chan webrtc.SessionDescription
ErrorChan chan error
}
type renegotiateQueue struct {
Client *Client
}
type allowRemoteRenegotiationQueue struct {
Client *Client
}
func NewQueue(ctx context.Context) *queue {
var isOpen atomic.Bool
isOpen.Store(true)
q := &queue{
mutex: sync.Mutex{},
IsOpen: &isOpen,
opChan: make(chan interface{}, 10),
}
go q.run(ctx)
return q
}
func (q *queue) Push(item interface{}) {
go func() {
q.mutex.Lock()
defer q.mutex.Unlock()
if !q.IsOpen.Load() {
glog.Warning("sfu: queue is closed when push renegotiation")
if opItem, ok := item.(negotiationQueue); ok {
opItem.ErrorChan <- ErrQueueIsClosed
}
return
}
q.opChan <- item
}()
}
func (q *queue) run(ctx context.Context) {
ctxx, cancel := context.WithCancel(ctx)
defer func() {
q.mutex.Lock()
defer q.mutex.Unlock()
q.IsOpen.Store(false)
close(q.opChan)
cancel()
}()
for {
select {
case <-ctxx.Done():
return
case item := <-q.opChan:
switch opItem := item.(type) {
case negotiationQueue:
answer, err := opItem.Client.negotiateQueuOp(opItem.SDP)
if err != nil {
opItem.ErrorChan <- err
continue
}
opItem.AnswerChan <- *answer
case renegotiateQueue:
opItem.Client.renegotiateQueuOp()
case allowRemoteRenegotiationQueue:
opItem.Client.allowRemoteRenegotiationQueuOp()
}
}
}
}