// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT

// Package rtpbuffer provides a buffer for storing RTP packets
package rtpbuffer import ( ) const ( // Uint16SizeHalf is half of a math.Uint16. Uint16SizeHalf = 1 << 15 maxPayloadLen = 1460 ) // RTPBuffer stores RTP packets and allows custom logic // around the lifetime of them via the PacketFactory. type RTPBuffer struct { packets []*RetainablePacket size uint16 highestAdded uint16 started bool } // NewRTPBuffer constructs a new RTPBuffer. func ( uint16) (*RTPBuffer, error) { := make([]uint16, 0) := false for := 0; < 16; ++ { if == 1<< { = true break } = append(, 1<<) } if ! { return nil, fmt.Errorf("%w: %d is not a valid size, allowed sizes: %v", ErrInvalidSize, , ) } return &RTPBuffer{ packets: make([]*RetainablePacket, ), size: , }, nil } // Add places the RetainablePacket in the RTPBuffer. func ( *RTPBuffer) ( *RetainablePacket) { := .sequenceNumber if !.started { .packets[%.size] = .highestAdded = .started = true return } := - .highestAdded if == 0 { return } else if < Uint16SizeHalf { for := .highestAdded + 1; != ; ++ { := % .size := .packets[] if != nil { .Release() } .packets[] = nil } .highestAdded = } := % .size := .packets[] if != nil { .Release() } .packets[] = } // Get returns the RetainablePacket for the requested sequence number. func ( *RTPBuffer) ( uint16) *RetainablePacket { := .highestAdded - if >= Uint16SizeHalf { return nil } if >= .size { return nil } := .packets[%.size] if != nil { if .sequenceNumber != { return nil } // already released if := .Retain(); != nil { return nil } } return }