Debian Codegraph @

packetio/buffer.go

raw symbols SCIP
1 // Package packetio provides packet buffer
2 package packetio
3
4 import (
5 "errors"
6 "io"
7 "sync"
8 "time"
9
10 "github.com/pion/transport/v2/deadline"
11 )
12
13 var errPacketTooBig = errors.New("packet too big")
14
15 // BufferPacketType allow the Buffer to know which packet protocol is writing.
16 type BufferPacketType int
17
18 const (
19 // RTPBufferPacket indicates the Buffer that is handling RTP packets
20 RTPBufferPacket BufferPacketType = 1
21 // RTCPBufferPacket indicates the Buffer that is handling RTCP packets
22 RTCPBufferPacket BufferPacketType = 2
23 )
24
25 // Buffer allows writing packets to an intermediate buffer, which can then be read form.
26 // This is verify similar to bytes.Buffer but avoids combining multiple writes into a single read.
27 type Buffer struct {
28 mutex sync.Mutex
29
30 // this is a circular buffer. If head <= tail, then the useful
31 // data is in the interval [head, tail[. If tail < head, then
32 // the useful data is the union of [head, len[ and [0, tail[.
33 // In order to avoid ambiguity when head = tail, we always leave
34 // an unused byte in the buffer.
35 data []byte
36 head, tail int
37
38 notify chan struct{}
39 subs bool
40 closed bool
41
42 count int
43 limitCount, limitSize int
44
45 readDeadline *deadline.Deadline
46 }
47
48 const (
49 minSize = 2048
50 cutoffSize = 128 * 1024
51 maxSize = 4 * 1024 * 1024
52 )
53
54 // NewBuffer creates a new Buffer.
55 func NewBuffer() *Buffer {
56 return &Buffer{
57 notify: make(chan struct{}),
58 readDeadline: deadline.New(),
59 }
60 }
61
62 // available returns true if the buffer is large enough to fit a packet
63 // of the given size, taking overhead into account.
64 func (b *Buffer) available(size int) bool {
65 available := b.head - b.tail
66 if available <= 0 {
67 available += len(b.data)
68 }
69 // we interpret head=tail as empty, so always keep a byte free
70 if size+2+1 > available {
71 return false
72 }
73
74 return true
75 }
76
77 // grow increases the size of the buffer. If it returns nil, then the
78 // buffer has been grown. It returns ErrFull if hits a limit.
79 func (b *Buffer) grow() error {
80 var newSize int
81 if len(b.data) < cutoffSize {
82 newSize = 2 * len(b.data)
83 } else {
84 newSize = 5 * len(b.data) / 4
85 }
86 if newSize < minSize {
87 newSize = minSize
88 }
89 if (b.limitSize <= 0 || sizeHardLimit) && newSize > maxSize {
90 newSize = maxSize
91 }
92
93 // one byte slack
94 if b.limitSize > 0 && newSize > b.limitSize+1 {
95 newSize = b.limitSize + 1
96 }
97
98 if newSize <= len(b.data) {
99 return ErrFull
100 }
101
102 newData := make([]byte, newSize)
103
104 var n int
105 if b.head <= b.tail {
106 // data was contiguous
107 n = copy(newData, b.data[b.head:b.tail])
108 } else {
109 // data was discontinuous
110 n = copy(newData, b.data[b.head:])
111 n += copy(newData[n:], b.data[:b.tail])
112 }
113 b.head = 0
114 b.tail = n
115 b.data = newData
116
117 return nil
118 }
119
120 // Write appends a copy of the packet data to the buffer.
121 // Returns ErrFull if the packet doesn't fit.
122 //
123 // Note that the packet size is limited to 65536 bytes since v0.11.0 due to the internal data structure.
124 func (b *Buffer) Write(packet []byte) (int, error) {
125 if len(packet) >= 0x10000 {
126 return 0, errPacketTooBig
127 }
128
129 b.mutex.Lock()
130
131 if b.closed {
132 b.mutex.Unlock()
133 return 0, io.ErrClosedPipe
134 }
135
136 if (b.limitCount > 0 && b.count >= b.limitCount) ||
137 (b.limitSize > 0 && b.size()+2+len(packet) > b.limitSize) {
138 b.mutex.Unlock()
139 return 0, ErrFull
140 }
141
142 // grow the buffer until the packet fits
143 for !b.available(len(packet)) {
144 err := b.grow()
145 if err != nil {
146 b.mutex.Unlock()
147 return 0, err
148 }
149 }
150
151 var notify chan struct{}
152
153 if b.subs {
154 // readers are waiting. Prepare to notify, but only
155 // actually do it after we release the lock.
156 notify = b.notify
157 b.notify = make(chan struct{})
158 b.subs = false
159 }
160
161 // store the length of the packet
162 b.data[b.tail] = uint8(len(packet) >> 8)
163 b.tail++
164 if b.tail >= len(b.data) {
165 b.tail = 0
166 }
167 b.data[b.tail] = uint8(len(packet))
168 b.tail++
169 if b.tail >= len(b.data) {
170 b.tail = 0
171 }
172
173 // store the packet
174 n := copy(b.data[b.tail:], packet)
175 b.tail += n
176 if b.tail >= len(b.data) {
177 // we reached the end, wrap around
178 m := copy(b.data, packet[n:])
179 b.tail = m
180 }
181 b.count++
182 b.mutex.Unlock()
183
184 if notify != nil {
185 close(notify)
186 }
187
188 return len(packet), nil
189 }
190
191 // Read populates the given byte slice, returning the number of bytes read.
192 // Blocks until data is available or the buffer is closed.
193 // Returns io.ErrShortBuffer is the packet is too small to copy the Write.
194 // Returns io.EOF if the buffer is closed.
195 func (b *Buffer) Read(packet []byte) (n int, err error) {
196 // Return immediately if the deadline is already exceeded.
197 select {
198 case <-b.readDeadline.Done():
199 return 0, &netError{ErrTimeout, true, true}
200 default:
201 }
202
203 for {
204 b.mutex.Lock()
205
206 if b.head != b.tail {
207 // decode the packet size
208 n1 := b.data[b.head]
209 b.head++
210 if b.head >= len(b.data) {
211 b.head = 0
212 }
213 n2 := b.data[b.head]
214 b.head++
215 if b.head >= len(b.data) {
216 b.head = 0
217 }
218 count := int((uint16(n1) << 8) | uint16(n2))
219
220 // determine the number of bytes we'll actually copy
221 copied := count
222 if copied > len(packet) {
223 copied = len(packet)
224 }
225
226 // copy the data
227 if b.head+copied < len(b.data) {
228 copy(packet, b.data[b.head:b.head+copied])
229 } else {
230 k := copy(packet, b.data[b.head:])
231 copy(packet[k:], b.data[:copied-k])
232 }
233
234 // advance head, discarding any data that wasn't copied
235 b.head += count
236 if b.head >= len(b.data) {
237 b.head -= len(b.data)
238 }
239
240 if b.head == b.tail {
241 // the buffer is empty, reset to beginning
242 // in order to improve cache locality.
243 b.head = 0
244 b.tail = 0
245 }
246
247 b.count--
248
249 b.mutex.Unlock()
250
251 if copied < count {
252 return copied, io.ErrShortBuffer
253 }
254 return copied, nil
255 }
256
257 if b.closed {
258 b.mutex.Unlock()
259 return 0, io.EOF
260 }
261
262 notify := b.notify
263 b.subs = true
264 b.mutex.Unlock()
265
266 select {
267 case <-b.readDeadline.Done():
268 return 0, &netError{ErrTimeout, true, true}
269 case <-notify:
270 }
271 }
272 }
273
274 // Close the buffer, unblocking any pending reads.
275 // Data in the buffer can still be read, Read will return io.EOF only when empty.
276 func (b *Buffer) Close() (err error) {
277 b.mutex.Lock()
278
279 if b.closed {
280 b.mutex.Unlock()
281 return nil
282 }
283
284 notify := b.notify
285 b.closed = true
286
287 b.mutex.Unlock()
288
289 close(notify)
290
291 return nil
292 }
293
294 // Count returns the number of packets in the buffer.
295 func (b *Buffer) Count() int {
296 b.mutex.Lock()
297 defer b.mutex.Unlock()
298 return b.count
299 }
300
301 // SetLimitCount controls the maximum number of packets that can be buffered.
302 // Causes Write to return ErrFull when this limit is reached.
303 // A zero value will disable this limit.
304 func (b *Buffer) SetLimitCount(limit int) {
305 b.mutex.Lock()
306 defer b.mutex.Unlock()
307
308 b.limitCount = limit
309 }
310
311 // Size returns the total byte size of packets in the buffer, including
312 // a small amount of administrative overhead.
313 func (b *Buffer) Size() int {
314 b.mutex.Lock()
315 defer b.mutex.Unlock()
316
317 return b.size()
318 }
319
320 func (b *Buffer) size() int {
321 size := b.tail - b.head
322 if size < 0 {
323 size += len(b.data)
324 }
325 return size
326 }
327
328 // SetLimitSize controls the maximum number of bytes that can be buffered.
329 // Causes Write to return ErrFull when this limit is reached.
330 // A zero value means 4MB since v0.11.0.
331 //
332 // User can set packetioSizeHardLimit build tag to enable 4MB hard limit.
333 // When packetioSizeHardLimit build tag is set, SetLimitSize exceeding
334 // the hard limit will be silently discarded.
335 func (b *Buffer) SetLimitSize(limit int) {
336 b.mutex.Lock()
337 defer b.mutex.Unlock()
338
339 b.limitSize = limit
340 }
341
342 // SetReadDeadline sets the deadline for the Read operation.
343 // Setting to zero means no deadline.
344 func (b *Buffer) SetReadDeadline(t time.Time) error {
345 b.readDeadline.Set(t)
346 return nil
347 }