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

package rtpbuffer

import (
	

	
)

// RetainablePacket is a referenced counted RTP packet.
type RetainablePacket struct {
	onRelease func(*rtp.Header, *[]byte)

	countMu sync.Mutex
	count   int

	header  *rtp.Header
	buffer  *[]byte
	payload []byte

	sequenceNumber uint16
}

// Header returns the RTP Header of the RetainablePacket.
func ( *RetainablePacket) () *rtp.Header {
	return .header
}

// Payload returns the RTP Payload of the RetainablePacket.
func ( *RetainablePacket) () []byte {
	return .payload
}

// Retain increases the reference count of the RetainablePacket.
func ( *RetainablePacket) () error {
	.countMu.Lock()
	defer .countMu.Unlock()
	if .count == 0 {
		// already released
		return errPacketReleased
	}
	.count++

	return nil
}

// Release decreases the reference count of the RetainablePacket and frees if needed.
func ( *RetainablePacket) () {
	.countMu.Lock()
	defer .countMu.Unlock()
	.count--

	if .count == 0 {
		// release back to pool
		.onRelease(.header, .buffer)
		.header = nil
		.buffer = nil
		.payload = nil
	}
}