Debian Codegraph @

transport_layer_cc.go

raw symbols SCIP
1 // SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
2 // SPDX-License-Identifier: MIT
3
4 package rtcp
5
6 // Author: adwpc
7
8 import (
9 "encoding/binary"
10 "errors"
11 "fmt"
12 "math"
13 "strings"
14 )
15
16 // https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#page-5
17 // 0 1 2 3
18 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
19 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
20 // |V=2|P| FMT=15 | PT=205 | length |
21 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
22 // | SSRC of packet sender |
23 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
24 // | SSRC of media source |
25 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
26 // | base sequence number | packet status count |
27 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
28 // | reference time | fb pkt. count |
29 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
30 // | packet chunk | packet chunk |
31 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
32 // . .
33 // . .
34 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
35 // | packet chunk | recv delta | recv delta |
36 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
37 // . .
38 // . .
39 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
40 // | recv delta | recv delta | zero padding |
41 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
42
43 // for packet status chunk.
44 const (
45 // type of packet status chunk.
46 TypeTCCRunLengthChunk = 0
47 TypeTCCStatusVectorChunk = 1
48
49 // len of packet status chunk.
50 packetStatusChunkLength = 2
51 )
52
53 // type of packet status symbol and recv delta.
54 const (
55 // https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#section-3.1.1
56 TypeTCCPacketNotReceived = uint16(iota)
57 TypeTCCPacketReceivedSmallDelta
58 TypeTCCPacketReceivedLargeDelta
59 // https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#page-7
60 // see Example 2: "packet received, w/o recv delta".
61 TypeTCCPacketReceivedWithoutDelta
62 )
63
64 // for status vector chunk.
65 const (
66 // https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#section-3.1.4
67 TypeTCCSymbolSizeOneBit = 0
68 TypeTCCSymbolSizeTwoBit = 1
69
70 // Notice: RFC is wrong: "packet received" (0) and "packet not received" (1)
71 // if S == TypeTCCSymbolSizeOneBit, symbol list will be: TypeTCCPacketNotReceived TypeTCCPacketReceivedSmallDelta
72 // if S == TypeTCCSymbolSizeTwoBit, symbol list will be same as above:
73 //.
74 )
75
76 func numOfBitsOfSymbolSize() map[uint16]uint16 {
77 return map[uint16]uint16{
78 TypeTCCSymbolSizeOneBit: 1,
79 TypeTCCSymbolSizeTwoBit: 2,
80 }
81 }
82
83 var (
84 errPacketStatusChunkLength = errors.New("packet status chunk must be 2 bytes")
85 errDeltaExceedLimit = errors.New("delta exceed limit")
86 )
87
88 // PacketStatusChunk has two kinds:
89 // RunLengthChunk and StatusVectorChunk.
90 type PacketStatusChunk interface {
91 Marshal() ([]byte, error)
92 Unmarshal(rawPacket []byte) error
93 }
94
95 // RunLengthChunk T=TypeTCCRunLengthChunk
96 // 0 1
97 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
98 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
99 // |T| S | Run Length |
100 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
101 // .
102 type RunLengthChunk struct {
103 PacketStatusChunk
104
105 // T = TypeTCCRunLengthChunk
106 Type uint16
107
108 // S: type of packet status
109 // kind: TypeTCCPacketNotReceived or...
110 PacketStatusSymbol uint16
111
112 // RunLength: count of S
113 RunLength uint16
114 }
115
116 // Marshal ..
117 func (r RunLengthChunk) Marshal() ([]byte, error) {
118 chunk := make([]byte, 2)
119
120 // append 1 bit '0'
121 dst, err := setNBitsOfUint16(0, 1, 0, 0)
122 if err != nil {
123 return nil, err
124 }
125
126 // append 2 bit PacketStatusSymbol
127 dst, err = setNBitsOfUint16(dst, 2, 1, r.PacketStatusSymbol)
128 if err != nil {
129 return nil, err
130 }
131
132 // append 13 bit RunLength
133 dst, err = setNBitsOfUint16(dst, 13, 3, r.RunLength)
134 if err != nil {
135 return nil, err
136 }
137
138 binary.BigEndian.PutUint16(chunk, dst)
139
140 return chunk, nil
141 }
142
143 // Unmarshal ..
144 func (r *RunLengthChunk) Unmarshal(rawPacket []byte) error {
145 if len(rawPacket) != packetStatusChunkLength {
146 return errPacketStatusChunkLength
147 }
148
149 // record type
150 r.Type = TypeTCCRunLengthChunk
151
152 // get PacketStatusSymbol
153 // r.PacketStatusSymbol = uint16(rawPacket[0] >> 5 & 0x03)
154 r.PacketStatusSymbol = getNBitsFromByte(rawPacket[0], 1, 2)
155
156 // get RunLength
157 // r.RunLength = uint16(rawPacket[0]&0x1F)*256 + uint16(rawPacket[1])
158 r.RunLength = getNBitsFromByte(rawPacket[0], 3, 5)<<8 + uint16(rawPacket[1])
159
160 return nil
161 }
162
163 // StatusVectorChunk T=typeStatusVecotrChunk
164 // 0 1
165 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
166 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
167 // |T|S| symbol list |
168 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
169 // .
170 type StatusVectorChunk struct {
171 PacketStatusChunk
172 // T = TypeTCCRunLengthChunk
173 Type uint16
174
175 // TypeTCCSymbolSizeOneBit or TypeTCCSymbolSizeTwoBit
176 SymbolSize uint16
177
178 // when SymbolSize = TypeTCCSymbolSizeOneBit, SymbolList is 14*1bit:
179 // TypeTCCSymbolListPacketReceived or TypeTCCSymbolListPacketNotReceived
180 // when SymbolSize = TypeTCCSymbolSizeTwoBit, SymbolList is 7*2bit:
181 // TypeTCCPacketNotReceived TypeTCCPacketReceivedSmallDelta TypeTCCPacketReceivedLargeDelta or typePacketReserved
182 SymbolList []uint16
183 }
184
185 // Marshal ..
186 func (r StatusVectorChunk) Marshal() ([]byte, error) {
187 chunk := make([]byte, 2)
188
189 // set first bit '1'
190 dst, err := setNBitsOfUint16(0, 1, 0, 1)
191 if err != nil {
192 return nil, err
193 }
194
195 // set second bit SymbolSize
196 dst, err = setNBitsOfUint16(dst, 1, 1, r.SymbolSize)
197 if err != nil {
198 return nil, err
199 }
200
201 numOfBits := numOfBitsOfSymbolSize()[r.SymbolSize]
202 // append 14 bit SymbolList
203 for i, s := range r.SymbolList {
204 index := numOfBits*uint16(i) + 2 //nolint:gosec // G115
205 dst, err = setNBitsOfUint16(dst, numOfBits, index, s)
206 if err != nil {
207 return nil, err
208 }
209 }
210
211 binary.BigEndian.PutUint16(chunk, dst)
212 // set SymbolList(bit8-15)
213 // chunk[1] = uint8(r.SymbolList) & 0x0f
214 return chunk, nil
215 }
216
217 // Unmarshal ..
218 func (r *StatusVectorChunk) Unmarshal(rawPacket []byte) error {
219 if len(rawPacket) != packetStatusChunkLength {
220 return errPacketStatusChunkLength
221 }
222
223 r.Type = TypeTCCStatusVectorChunk
224 r.SymbolSize = getNBitsFromByte(rawPacket[0], 1, 1)
225
226 if r.SymbolSize == TypeTCCSymbolSizeOneBit {
227 for i := range uint16(6) {
228 r.SymbolList = append(r.SymbolList, getNBitsFromByte(rawPacket[0], 2+i, 1))
229 }
230 for i := range uint16(8) {
231 r.SymbolList = append(r.SymbolList, getNBitsFromByte(rawPacket[1], i, 1))
232 }
233
234 return nil
235 }
236 if r.SymbolSize == TypeTCCSymbolSizeTwoBit {
237 for i := range uint16(3) {
238 r.SymbolList = append(r.SymbolList, getNBitsFromByte(rawPacket[0], 2+i*2, 2))
239 }
240 for i := range uint16(4) {
241 r.SymbolList = append(r.SymbolList, getNBitsFromByte(rawPacket[1], i*2, 2))
242 }
243
244 return nil
245 }
246
247 r.SymbolSize = getNBitsFromByte(rawPacket[0], 2, 6)<<8 + uint16(rawPacket[1])
248
249 return nil
250 }
251
252 const (
253 // TypeTCCDeltaScaleFactor https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#section-3.1.5
254 TypeTCCDeltaScaleFactor = 250
255 )
256
257 // RecvDelta are represented as multiples of 250us
258 // small delta is 1 byte: [0,63.75]ms = [0, 63750]us = [0, 255]*250us
259 // big delta is 2 bytes: [-8192.0, 8191.75]ms = [-8192000, 8191750]us = [-32768, 32767]*250us
260 // https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#section-3.1.5
261 type RecvDelta struct {
262 Type uint16
263 // us
264 Delta int64
265 }
266
267 // Marshal ..
268 func (r RecvDelta) Marshal() ([]byte, error) {
269 delta := r.Delta / TypeTCCDeltaScaleFactor
270
271 // small delta
272 if r.Type == TypeTCCPacketReceivedSmallDelta && delta >= 0 && delta <= math.MaxUint8 {
273 deltaChunk := make([]byte, 1)
274 deltaChunk[0] = byte(delta) //nolint:gosec // deltaChunk is created with length 1
275
276 return deltaChunk, nil
277 }
278
279 // big delta
280 if r.Type == TypeTCCPacketReceivedLargeDelta && delta >= math.MinInt16 && delta <= math.MaxInt16 {
281 deltaChunk := make([]byte, 2)
282 binary.BigEndian.PutUint16(deltaChunk, uint16(delta)) //nolint:gosec //delta is validated to fit in uint16
283
284 return deltaChunk, nil
285 }
286
287 // overflow
288 return nil, errDeltaExceedLimit
289 }
290
291 // Unmarshal ..
292 func (r *RecvDelta) Unmarshal(rawPacket []byte) error {
293 chunkLen := len(rawPacket)
294
295 // must be 1 or 2 bytes
296 if chunkLen != 1 && chunkLen != 2 {
297 return errDeltaExceedLimit
298 }
299
300 if chunkLen == 1 {
301 r.Type = TypeTCCPacketReceivedSmallDelta
302 r.Delta = TypeTCCDeltaScaleFactor * int64(rawPacket[0])
303
304 return nil
305 }
306
307 r.Type = TypeTCCPacketReceivedLargeDelta
308 r.Delta = TypeTCCDeltaScaleFactor * int64(int16(binary.BigEndian.Uint16(rawPacket))) //nolint:gosec // G115
309
310 return nil
311 }
312
313 const (
314 // the offset after header.
315 baseSequenceNumberOffset = 8
316 packetStatusCountOffset = 10
317 referenceTimeOffset = 12
318 fbPktCountOffset = 15
319 packetChunkOffset = 16
320 )
321
322 // TransportLayerCC for sender-BWE
323 // https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#page-5
324 type TransportLayerCC struct {
325 // header
326 Header Header
327
328 // SSRC of sender
329 SenderSSRC uint32
330
331 // SSRC of the media source
332 MediaSSRC uint32
333
334 // Transport wide sequence of rtp extension
335 BaseSequenceNumber uint16
336
337 // PacketStatusCount
338 PacketStatusCount uint16
339
340 // ReferenceTime
341 ReferenceTime uint32
342
343 // FbPktCount
344 FbPktCount uint8
345
346 // PacketChunks
347 PacketChunks []PacketStatusChunk
348
349 // RecvDeltas
350 RecvDeltas []*RecvDelta
351 }
352
353 // Header returns the Header associated with this packet.
354 // func (t *TransportLayerCC) Header() Header {
355 // return t.Header
356 // return Header{
357 // Padding: true,
358 // Count: FormatTCC,
359 // Type: TypeTCCTransportSpecificFeedback,
360 // // https://tools.ietf.org/html/rfc4585#page-33
361 // Length: uint16((t.len() / 4) - 1),
362 // }
363 // }
364
365 func (t *TransportLayerCC) packetLen() uint16 {
366 //nolint:gocognit,cyclop
367 n := uint16(headerLength + packetChunkOffset + len(t.PacketChunks)*2) //nolint:gosec // G115
368 for _, d := range t.RecvDeltas {
369 if d.Type == TypeTCCPacketReceivedSmallDelta {
370 n++
371 } else {
372 n += 2
373 }
374 }
375
376 return n
377 }
378
379 // Len return total bytes with padding.
380 func (t *TransportLayerCC) Len() uint16 {
381 return uint16(t.MarshalSize()) //nolint:gosec // G115
382 }
383
384 // MarshalSize returns the size of the packet once marshaled.
385 func (t *TransportLayerCC) MarshalSize() int {
386 n := t.packetLen()
387 // has padding
388 if n%4 != 0 {
389 n = (n/4 + 1) * 4
390 }
391
392 return int(n)
393 }
394
395 func (t TransportLayerCC) String() string {
396 var out strings.Builder
397 fmt.Fprintf(&out, "TransportLayerCC:\n\tHeader %v\n", t.Header)
398 fmt.Fprintf(&out, "TransportLayerCC:\n\tSender Ssrc %d\n", t.SenderSSRC)
399 fmt.Fprintf(&out, "\tMedia Ssrc %d\n", t.MediaSSRC)
400 fmt.Fprintf(&out, "\tBase Sequence Number %d\n", t.BaseSequenceNumber)
401 fmt.Fprintf(&out, "\tStatus Count %d\n", t.PacketStatusCount)
402 fmt.Fprintf(&out, "\tReference Time %d\n", t.ReferenceTime)
403 fmt.Fprintf(&out, "\tFeedback Packet Count %d\n", t.FbPktCount)
404 out.WriteString("\tPacketChunks ")
405 for _, chunk := range t.PacketChunks {
406 fmt.Fprintf(&out, "%+v ", chunk)
407 }
408 out.WriteString("\n\tRecvDeltas ")
409 for _, delta := range t.RecvDeltas {
410 fmt.Fprintf(&out, "%+v ", delta)
411 }
412 out.WriteString("\n")
413
414 return out.String()
415 }
416
417 // Marshal encodes the TransportLayerCC in binary.
418 func (t TransportLayerCC) Marshal() ([]byte, error) {
419 header, err := t.Header.Marshal()
420 if err != nil {
421 return nil, err
422 }
423
424 payload := make([]byte, t.MarshalSize()-headerLength)
425 binary.BigEndian.PutUint32(payload, t.SenderSSRC)
426 binary.BigEndian.PutUint32(payload[4:], t.MediaSSRC)
427 binary.BigEndian.PutUint16(payload[baseSequenceNumberOffset:], t.BaseSequenceNumber)
428 binary.BigEndian.PutUint16(payload[packetStatusCountOffset:], t.PacketStatusCount)
429 ReferenceTimeAndFbPktCount := appendNBitsToUint32(0, 24, t.ReferenceTime)
430 ReferenceTimeAndFbPktCount = appendNBitsToUint32(ReferenceTimeAndFbPktCount, 8, uint32(t.FbPktCount))
431 binary.BigEndian.PutUint32(payload[referenceTimeOffset:], ReferenceTimeAndFbPktCount)
432
433 for i, chunk := range t.PacketChunks {
434 b, err := chunk.Marshal()
435 if err != nil {
436 return nil, err
437 }
438 copy(payload[packetChunkOffset+i*2:], b)
439 }
440
441 recvDeltaOffset := packetChunkOffset + len(t.PacketChunks)*2
442 var i int
443 for _, delta := range t.RecvDeltas {
444 b, err := delta.Marshal()
445 if err == nil {
446 copy(payload[recvDeltaOffset+i:], b)
447 i++
448 if delta.Type == TypeTCCPacketReceivedLargeDelta {
449 i++
450 }
451 }
452 }
453
454 if t.Header.Padding {
455 payload[len(payload)-1] = uint8(t.MarshalSize() - int(t.packetLen())) //nolint:gosec // G115
456 }
457
458 return append(header, payload...), nil
459 }
460
461 // Unmarshal ..
462 //
463 //nolint:gocognit,cyclop
464 func (t *TransportLayerCC) Unmarshal(rawPacket []byte) error {
465 if len(rawPacket) < (headerLength + ssrcLength) {
466 return errPacketTooShort
467 }
468
469 if err := t.Header.Unmarshal(rawPacket); err != nil {
470 return err
471 }
472
473 // https://tools.ietf.org/html/rfc4585#page-33
474 // header's length + payload's length
475 totalLength := 4 * (int(t.Header.Length) + 1)
476
477 if totalLength < headerLength+packetChunkOffset {
478 return errPacketTooShort
479 }
480
481 if len(rawPacket) < totalLength {
482 return errPacketTooShort
483 }
484
485 if t.Header.Type != TypeTransportSpecificFeedback || t.Header.Count != FormatTCC {
486 return errWrongType
487 }
488
489 t.SenderSSRC = binary.BigEndian.Uint32(rawPacket[headerLength:])
490 t.MediaSSRC = binary.BigEndian.Uint32(rawPacket[headerLength+ssrcLength:])
491 t.BaseSequenceNumber = binary.BigEndian.Uint16(rawPacket[headerLength+baseSequenceNumberOffset:])
492 t.PacketStatusCount = binary.BigEndian.Uint16(rawPacket[headerLength+packetStatusCountOffset:])
493 t.ReferenceTime = get24BitsFromBytes(rawPacket[headerLength+referenceTimeOffset : headerLength+referenceTimeOffset+3])
494 t.FbPktCount = rawPacket[headerLength+fbPktCountOffset]
495
496 packetStatusPos := int(headerLength + packetChunkOffset)
497 var processedPacketNum uint16
498 for processedPacketNum < t.PacketStatusCount {
499 if packetStatusPos+packetStatusChunkLength >= totalLength {
500 return errPacketTooShort
501 }
502 typ := getNBitsFromByte(rawPacket[packetStatusPos : packetStatusPos+1][0], 0, 1)
503 var iPacketStatus PacketStatusChunk
504 switch typ {
505 case TypeTCCRunLengthChunk:
506 packetStatus := &RunLengthChunk{Type: typ}
507 iPacketStatus = packetStatus
508 err := packetStatus.Unmarshal(rawPacket[packetStatusPos : packetStatusPos+2])
509 if err != nil {
510 return err
511 }
512
513 packetNumberToProcess := localMin(t.PacketStatusCount-processedPacketNum, packetStatus.RunLength)
514 if packetStatus.PacketStatusSymbol == TypeTCCPacketReceivedSmallDelta ||
515 packetStatus.PacketStatusSymbol == TypeTCCPacketReceivedLargeDelta {
516 for range packetNumberToProcess {
517 t.RecvDeltas = append(t.RecvDeltas, &RecvDelta{Type: packetStatus.PacketStatusSymbol})
518 }
519 }
520 processedPacketNum += packetNumberToProcess
521 case TypeTCCStatusVectorChunk:
522 packetStatus := &StatusVectorChunk{Type: typ}
523 iPacketStatus = packetStatus
524 err := packetStatus.Unmarshal(rawPacket[packetStatusPos : packetStatusPos+2])
525 if err != nil {
526 return err
527 }
528 if packetStatus.SymbolSize == TypeTCCSymbolSizeOneBit {
529 for j := 0; j < len(packetStatus.SymbolList); j++ {
530 if packetStatus.SymbolList[j] == TypeTCCPacketReceivedSmallDelta {
531 t.RecvDeltas = append(t.RecvDeltas, &RecvDelta{Type: TypeTCCPacketReceivedSmallDelta})
532 }
533 }
534 }
535 if packetStatus.SymbolSize == TypeTCCSymbolSizeTwoBit {
536 for j := 0; j < len(packetStatus.SymbolList); j++ {
537 if packetStatus.SymbolList[j] == TypeTCCPacketReceivedSmallDelta ||
538 packetStatus.SymbolList[j] == TypeTCCPacketReceivedLargeDelta {
539 t.RecvDeltas = append(t.RecvDeltas, &RecvDelta{Type: packetStatus.SymbolList[j]})
540 }
541 }
542 }
543 processedPacketNum += uint16(len(packetStatus.SymbolList)) //nolint:gosec // G115
544 }
545 packetStatusPos += packetStatusChunkLength
546 t.PacketChunks = append(t.PacketChunks, iPacketStatus)
547 }
548
549 recvDeltasPos := packetStatusPos
550 for _, delta := range t.RecvDeltas {
551 if delta.Type == TypeTCCPacketReceivedSmallDelta {
552 if recvDeltasPos+1 > totalLength {
553 return errPacketTooShort
554 }
555 err := delta.Unmarshal(rawPacket[recvDeltasPos : recvDeltasPos+1])
556 if err != nil {
557 return err
558 }
559 recvDeltasPos++
560 }
561 if delta.Type == TypeTCCPacketReceivedLargeDelta {
562 if recvDeltasPos+2 > totalLength {
563 return errPacketTooShort
564 }
565 err := delta.Unmarshal(rawPacket[recvDeltasPos : recvDeltasPos+2])
566 if err != nil {
567 return err
568 }
569 recvDeltasPos += 2
570 }
571 }
572
573 return nil
574 }
575
576 // DestinationSSRC returns an array of SSRC values that this packet refers to.
577 func (t TransportLayerCC) DestinationSSRC() []uint32 {
578 return []uint32{t.MediaSSRC}
579 }
580
581 func localMin(x, y uint16) uint16 {
582 if x < y {
583 return x
584 }
585
586 return y
587 }