forked from Monibuca/engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ring.go
98 lines (83 loc) · 1.73 KB
/
ring.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
package engine
import (
"bytes"
"sync"
"time"
"github.com/Monibuca/engine/v2/avformat"
)
type RingItem struct {
avformat.AVPacket
sync.WaitGroup
*bytes.Buffer
UpdateTime time.Time
}
// Ring 环形缓冲,使用数组实现
type Ring struct {
*RingItem
buffer []RingItem
Size int
Index int
}
// NewRing 创建Ring,传入大小指数
func NewRing(exp int) (r *Ring) {
r = new(Ring)
r.Size = 1 << exp
r.buffer = make([]RingItem, r.Size)
r.RingItem = &r.buffer[0]
r.Add(1)
return
}
func (r *Ring) offset(v int) int {
return (r.Index + v) & (r.Size - 1)
}
// GoTo 移动到指定索引处
func (r *Ring) GoTo(index int) {
r.Index = index
r.RingItem = &r.buffer[index]
}
// GetAt 获取指定索引处的引用
func (r *Ring) GetAt(index int) *RingItem {
return &r.buffer[index]
}
// GetNext 获取下一个位置的引用
func (r *Ring) GetNext() *RingItem {
return &r.buffer[r.offset(1)]
}
// GetLast 获取上一个位置的引用
func (r *Ring) GetLast() *RingItem {
return &r.buffer[r.offset(-1)]
}
// GoNext 移动到下一个位置
func (r *Ring) GoNext() {
r.Index = r.offset(1)
r.RingItem = &r.buffer[r.Index]
}
// GoBack 移动到上一个位置
func (r *Ring) GoBack() {
r.Index = r.offset(-1)
r.RingItem = &r.buffer[r.Index]
}
// NextW 写下一个
func (r *Ring) NextW() {
item := r.RingItem
item.UpdateTime = time.Now()
r.GoNext()
r.RingItem.Add(1)
item.Done()
}
func (r *Ring) GetBuffer() *bytes.Buffer {
if r.Buffer == nil {
r.Buffer = bytes.NewBuffer([]byte{})
} else {
r.Reset()
}
return r.Buffer
}
// Clone 克隆一个Ring
func (r Ring) Clone() *Ring {
return &r
}
// Timeout 发布者是否超时了
func (r *Ring) Timeout() bool {
return time.Since(r.UpdateTime) > config.PublishTimeout
}