Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reducing memory allocations in read RTCP methods #185

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions application_defined.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,9 @@
}
return 12 + dataLength + paddingSize
}

// Release returns the packet to its pool and resets it
func (p *ApplicationDefined) Release() {

Check failure on line 125 in application_defined.go

View workflow job for this annotation

GitHub Actions / lint / Go

receiver-naming: receiver name p should be consistent with previous receiver name a for ApplicationDefined (revive)
*p = ApplicationDefined{} // Reset the packet
applicationDefinedPool.Put(p)
}
8 changes: 8 additions & 0 deletions compound_packet.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,3 +159,11 @@
out = strings.TrimSuffix(strings.ReplaceAll(out, "\n", "\n\t"), "\t")
return out
}

// Release returns the packet to its pool and resets it
func (p *CompoundPacket) Release() {

Check failure on line 164 in compound_packet.go

View workflow job for this annotation

GitHub Actions / lint / Go

receiver-naming: receiver name p should be consistent with previous receiver name c for CompoundPacket (revive)

Check warning on line 164 in compound_packet.go

View check run for this annotation

Codecov / codecov/patch

compound_packet.go#L164

Added line #L164 was not covered by tests
// CompoundPacket is a slice of pointers, so we need to release each one
for _, packet := range *p {
packet.Release()

Check warning on line 167 in compound_packet.go

View check run for this annotation

Codecov / codecov/patch

compound_packet.go#L166-L167

Added lines #L166 - L167 were not covered by tests
}
}
6 changes: 6 additions & 0 deletions extended_report.go
Original file line number Diff line number Diff line change
Expand Up @@ -657,3 +657,9 @@
func (x *ExtendedReport) String() string {
return stringify(x)
}

// Release returns the packet to its pool and resets it
func (p *ExtendedReport) Release() {

Check failure on line 662 in extended_report.go

View workflow job for this annotation

GitHub Actions / lint / Go

receiver-naming: receiver name p should be consistent with previous receiver name x for ExtendedReport (revive)
*p = ExtendedReport{} // Reset the packet
extendedReportPool.Put(p)
}
6 changes: 6 additions & 0 deletions full_intra_request.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,3 +114,9 @@ func (p *FullIntraRequest) DestinationSSRC() []uint32 {
}
return ssrcs
}

// Release returns the packet to its pool and resets it
func (p *FullIntraRequest) Release() {
*p = FullIntraRequest{} // Reset the packet
fullIntraRequestPool.Put(p)
}
6 changes: 6 additions & 0 deletions goodbye.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,3 +161,9 @@

return out
}

// Release returns the packet to its pool and resets it
func (p *Goodbye) Release() {

Check failure on line 166 in goodbye.go

View workflow job for this annotation

GitHub Actions / lint / Go

receiver-naming: receiver name p should be consistent with previous receiver name g for Goodbye (revive)
*p = Goodbye{} // Reset the packet
goodbyePool.Put(p)
}
77 changes: 56 additions & 21 deletions packet.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@

package rtcp

import (
"bytes"
"sync"
)

// Packet represents an RTCP packet, a protocol used for out-of-band statistics and control information for an RTP session
type Packet interface {
// DestinationSSRC returns an array of SSRC values that this packet refers to.
Expand All @@ -11,19 +16,48 @@
Marshal() ([]byte, error)
Unmarshal(rawPacket []byte) error
MarshalSize() int

// Release returns the packet to its pool
Release()
}

//nolint:gochecknoglobals
var (
senderReportPool = sync.Pool{New: func() interface{} { return new(SenderReport) }}
receiverReportPool = sync.Pool{New: func() interface{} { return new(ReceiverReport) }}
sourceDescriptionPool = sync.Pool{New: func() interface{} { return new(SourceDescription) }}
goodbyePool = sync.Pool{New: func() interface{} { return new(Goodbye) }}
transportLayerNackPool = sync.Pool{New: func() interface{} { return new(TransportLayerNack) }}
rapidResynchronizationRequestPool = sync.Pool{New: func() interface{} { return new(RapidResynchronizationRequest) }}
transportLayerCCPool = sync.Pool{New: func() interface{} { return new(TransportLayerCC) }}
ccFeedbackReportPool = sync.Pool{New: func() interface{} { return new(CCFeedbackReport) }}
pictureLossIndicationPool = sync.Pool{New: func() interface{} { return new(PictureLossIndication) }}
sliceLossIndicationPool = sync.Pool{New: func() interface{} { return new(SliceLossIndication) }}
receiverEstimatedMaximumBitratePool = sync.Pool{New: func() interface{} { return new(ReceiverEstimatedMaximumBitrate) }}
fullIntraRequestPool = sync.Pool{New: func() interface{} { return new(FullIntraRequest) }}
extendedReportPool = sync.Pool{New: func() interface{} { return new(ExtendedReport) }}
applicationDefinedPool = sync.Pool{New: func() interface{} { return new(ApplicationDefined) }}
rawPacketPool = sync.Pool{New: func() interface{} { return new(RawPacket) }}
)

// Unmarshal takes an entire udp datagram (which may consist of multiple RTCP packets) and
// returns the unmarshaled packets it contains.
//
// If this is a reduced-size RTCP packet a feedback packet (Goodbye, SliceLossIndication, etc)
// will be returned. Otherwise, the underlying type of the returned packet will be
// CompoundPacket.
func Unmarshal(rawData []byte) ([]Packet, error) {
var packets []Packet
// Preallocate a slice with a reasonable initial capacity
estimatedPackets := len(rawData) / 100 // Estimate based on average packet size
packets := make([]Packet, 0, estimatedPackets)

for len(rawData) != 0 {
p, processed, err := unmarshal(rawData)
if err != nil {
// Release already allocated packets in case of error
for _, packet := range packets {
packet.Release()
}
return nil, err
}

Expand All @@ -43,15 +77,16 @@

// Marshal takes an array of Packets and serializes them to a single buffer
func Marshal(packets []Packet) ([]byte, error) {
out := make([]byte, 0)
var buf bytes.Buffer
for _, p := range packets {
data, err := p.Marshal()
if err != nil {
return nil, err
}
out = append(out, data...)
buf.Write(data)
p.Release()
}
return out, nil
return buf.Bytes(), nil
}

// unmarshal is a factory which pulls the first RTCP packet from a bytestream,
Expand All @@ -72,53 +107,53 @@

switch h.Type {
case TypeSenderReport:
packet = new(SenderReport)
packet = senderReportPool.Get().(*SenderReport)

Check warning on line 110 in packet.go

View check run for this annotation

Codecov / codecov/patch

packet.go#L110

Added line #L110 was not covered by tests

case TypeReceiverReport:
packet = new(ReceiverReport)
packet = receiverReportPool.Get().(*ReceiverReport)

case TypeSourceDescription:
packet = new(SourceDescription)
packet = sourceDescriptionPool.Get().(*SourceDescription)

case TypeGoodbye:
packet = new(Goodbye)
packet = goodbyePool.Get().(*Goodbye)

case TypeTransportSpecificFeedback:
switch h.Count {
case FormatTLN:
packet = new(TransportLayerNack)
packet = transportLayerNackPool.Get().(*TransportLayerNack)
case FormatRRR:
packet = new(RapidResynchronizationRequest)
packet = rapidResynchronizationRequestPool.Get().(*RapidResynchronizationRequest)
case FormatTCC:
packet = new(TransportLayerCC)
packet = transportLayerCCPool.Get().(*TransportLayerCC)
case FormatCCFB:
packet = new(CCFeedbackReport)
packet = ccFeedbackReportPool.Get().(*CCFeedbackReport)
default:
packet = new(RawPacket)
packet = rawPacketPool.Get().(*RawPacket)

Check warning on line 132 in packet.go

View check run for this annotation

Codecov / codecov/patch

packet.go#L132

Added line #L132 was not covered by tests
}

case TypePayloadSpecificFeedback:
switch h.Count {
case FormatPLI:
packet = new(PictureLossIndication)
packet = pictureLossIndicationPool.Get().(*PictureLossIndication)
case FormatSLI:
packet = new(SliceLossIndication)
packet = sliceLossIndicationPool.Get().(*SliceLossIndication)

Check warning on line 140 in packet.go

View check run for this annotation

Codecov / codecov/patch

packet.go#L140

Added line #L140 was not covered by tests
case FormatREMB:
packet = new(ReceiverEstimatedMaximumBitrate)
packet = receiverEstimatedMaximumBitratePool.Get().(*ReceiverEstimatedMaximumBitrate)

Check warning on line 142 in packet.go

View check run for this annotation

Codecov / codecov/patch

packet.go#L142

Added line #L142 was not covered by tests
case FormatFIR:
packet = new(FullIntraRequest)
packet = fullIntraRequestPool.Get().(*FullIntraRequest)
default:
packet = new(RawPacket)
packet = rawPacketPool.Get().(*RawPacket)

Check warning on line 146 in packet.go

View check run for this annotation

Codecov / codecov/patch

packet.go#L146

Added line #L146 was not covered by tests
}

case TypeExtendedReport:
packet = new(ExtendedReport)
packet = extendedReportPool.Get().(*ExtendedReport)

Check warning on line 150 in packet.go

View check run for this annotation

Codecov / codecov/patch

packet.go#L150

Added line #L150 was not covered by tests

case TypeApplicationDefined:
packet = new(ApplicationDefined)
packet = applicationDefinedPool.Get().(*ApplicationDefined)

default:
packet = new(RawPacket)
packet = rawPacketPool.Get().(*RawPacket)

Check warning on line 156 in packet.go

View check run for this annotation

Codecov / codecov/patch

packet.go#L156

Added line #L156 was not covered by tests
}

err = packet.Unmarshal(inPacket)
Expand Down
123 changes: 123 additions & 0 deletions packet_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,21 @@ func realPacket() []byte {
}
}

func BenchmarkUnmarshal(b *testing.B) {
packetData := realPacket()
for i := 0; i < b.N; i++ {
pkts, err := Unmarshal(packetData)
if err != nil {
b.Fatalf("Error unmarshalling packets: %s", err)
}

for _, pkt := range pkts {
pkt.Release()
}

}
}

func TestUnmarshal(t *testing.T) {
packet, err := Unmarshal(realPacket())
if err != nil {
Expand Down Expand Up @@ -144,3 +159,111 @@ func TestInvalidHeaderLength(t *testing.T) {
t.Fatalf("Unmarshal(nil) err = %v, want %v", got, want)
}
}

func TestPacketPool(t *testing.T) {
t.Run("SenderReport", func(t *testing.T) {
sr := senderReportPool.Get()
p, ok := sr.(*SenderReport)
assert.True(t, ok)

p.Release()
})

t.Run("ReceiverReport", func(t *testing.T) {
rr := receiverReportPool.Get()
p, ok := rr.(*ReceiverReport)
assert.True(t, ok)
p.Release()
})

t.Run("SourceDescription", func(t *testing.T) {
sd := sourceDescriptionPool.Get()
p, ok := sd.(*SourceDescription)
assert.True(t, ok)
p.Release()
})

t.Run("Goodbye", func(t *testing.T) {
gb := goodbyePool.Get()
p, ok := gb.(*Goodbye)
assert.True(t, ok)
p.Release()
})

t.Run("TransportLayerNack", func(t *testing.T) {
tln := transportLayerNackPool.Get()
p, ok := tln.(*TransportLayerNack)
assert.True(t, ok)
p.Release()
})

t.Run("RapidResynchronizationRequest", func(t *testing.T) {
rrr := rapidResynchronizationRequestPool.Get()
p, ok := rrr.(*RapidResynchronizationRequest)
assert.True(t, ok)
p.Release()
})

t.Run("TransportLayerCC", func(t *testing.T) {
tcc := transportLayerCCPool.Get()
p, ok := tcc.(*TransportLayerCC)
assert.True(t, ok)
p.Release()
})

t.Run("CCFeedbackReport", func(t *testing.T) {
ccfb := ccFeedbackReportPool.Get()
p, ok := ccfb.(*CCFeedbackReport)
assert.True(t, ok)
p.Release()
})

t.Run("PictureLossIndication", func(t *testing.T) {
pli := pictureLossIndicationPool.Get()
p, ok := pli.(*PictureLossIndication)
assert.True(t, ok)
p.Release()
})

t.Run("SliceLossIndication", func(t *testing.T) {
sli := sliceLossIndicationPool.Get()
p, ok := sli.(*SliceLossIndication)
assert.True(t, ok)
p.Release()
})

t.Run("ReceiverEstimatedMaximumBitrate", func(t *testing.T) {
remb := receiverEstimatedMaximumBitratePool.Get()
p, ok := remb.(*ReceiverEstimatedMaximumBitrate)
assert.True(t, ok)
p.Release()
})

t.Run("FullIntraRequest", func(t *testing.T) {
fir := fullIntraRequestPool.Get()
p, ok := fir.(*FullIntraRequest)
assert.True(t, ok)
p.Release()
})

t.Run("ExtendedReport", func(t *testing.T) {
er := extendedReportPool.Get()
p, ok := er.(*ExtendedReport)
assert.True(t, ok)
p.Release()
})

t.Run("ApplicationDefined", func(t *testing.T) {
ad := applicationDefinedPool.Get()
p, ok := ad.(*ApplicationDefined)
assert.True(t, ok)
p.Release()
})

t.Run("RawPacket", func(t *testing.T) {
rp := rawPacketPool.Get()
p, ok := rp.(*RawPacket)
assert.True(t, ok)
p.Release()
})
}
6 changes: 6 additions & 0 deletions picture_loss_indication.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,9 @@ func (p *PictureLossIndication) String() string {
func (p *PictureLossIndication) DestinationSSRC() []uint32 {
return []uint32{p.MediaSSRC}
}

// Release returns the packet to its pool and resets it
func (p *PictureLossIndication) Release() {
*p = PictureLossIndication{} // Reset the packet
pictureLossIndicationPool.Put(p)
}
6 changes: 6 additions & 0 deletions rapid_resynchronization_request.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,9 @@ func (p *RapidResynchronizationRequest) DestinationSSRC() []uint32 {
func (p *RapidResynchronizationRequest) String() string {
return fmt.Sprintf("RapidResynchronizationRequest %x %x", p.SenderSSRC, p.MediaSSRC)
}

// Release returns the packet to its pool and resets it
func (p *RapidResynchronizationRequest) Release() {
*p = RapidResynchronizationRequest{} // Reset the packet
rapidResynchronizationRequestPool.Put(p)
}
6 changes: 6 additions & 0 deletions raw_packet.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,9 @@
func (r RawPacket) MarshalSize() int {
return len(r)
}

// Release returns the packet to its pool and resets it
func (p *RawPacket) Release() {

Check failure on line 53 in raw_packet.go

View workflow job for this annotation

GitHub Actions / lint / Go

receiver-naming: receiver name p should be consistent with previous receiver name r for RawPacket (revive)
*p = RawPacket{} // Reset the packet
rawPacketPool.Put(p)
}
6 changes: 6 additions & 0 deletions receiver_estimated_maximum_bitrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -283,3 +283,9 @@ func (p *ReceiverEstimatedMaximumBitrate) String() string {
func (p *ReceiverEstimatedMaximumBitrate) DestinationSSRC() []uint32 {
return p.SSRCs
}

// Release returns the packet to its pool and resets it
func (p *ReceiverEstimatedMaximumBitrate) Release() {
*p = ReceiverEstimatedMaximumBitrate{} // Reset the packet
receiverEstimatedMaximumBitratePool.Put(p)
}
6 changes: 6 additions & 0 deletions receiver_report.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,3 +193,9 @@
out += fmt.Sprintf("\tProfile Extension Data: %v\n", r.ProfileExtensions)
return out
}

// Release returns the packet to its pool and resets it
func (p *ReceiverReport) Release() {

Check failure on line 198 in receiver_report.go

View workflow job for this annotation

GitHub Actions / lint / Go

receiver-naming: receiver name p should be consistent with previous receiver name r for ReceiverReport (revive)
*p = ReceiverReport{} // Reset the packet
receiverReportPool.Put(p)
}
Loading
Loading