-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathclient_segment_queue.go
83 lines (63 loc) · 1.26 KB
/
client_segment_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
package gohlslib
import (
"context"
"sync"
"time"
)
type segmentData struct {
dateTime *time.Time
payload []byte
}
type clientSegmentQueue struct {
mutex sync.Mutex
queue []*segmentData
didPush chan struct{}
didPull chan struct{}
}
func (q *clientSegmentQueue) initialize() {
q.didPush = make(chan struct{})
q.didPull = make(chan struct{})
}
func (q *clientSegmentQueue) push(seg *segmentData) {
q.mutex.Lock()
queueWasEmpty := (len(q.queue) == 0)
q.queue = append(q.queue, seg)
if queueWasEmpty {
close(q.didPush)
q.didPush = make(chan struct{})
}
q.mutex.Unlock()
}
func (q *clientSegmentQueue) waitUntilSizeIsBelow(ctx context.Context, n int) bool {
q.mutex.Lock()
for len(q.queue) > n {
q.mutex.Unlock()
select {
case <-q.didPull:
case <-ctx.Done():
return false
}
q.mutex.Lock()
}
q.mutex.Unlock()
return true
}
func (q *clientSegmentQueue) pull(ctx context.Context) (*segmentData, bool) {
q.mutex.Lock()
for len(q.queue) == 0 {
didPush := q.didPush
q.mutex.Unlock()
select {
case <-didPush:
case <-ctx.Done():
return nil, false
}
q.mutex.Lock()
}
var seg *segmentData
seg, q.queue = q.queue[0], q.queue[1:]
close(q.didPull)
q.didPull = make(chan struct{})
q.mutex.Unlock()
return seg, true
}