From a58fdc70bb67c0848c05598ff93a26c62a1bec6f Mon Sep 17 00:00:00 2001 From: Alex Snyatkov Date: Tue, 24 Feb 2026 23:37:31 +0000 Subject: [PATCH] feat: Export GetCodecMap for performance optimization Allows callers to build codec map once and reuse it instead of rebuilding on every GetCodecForPayloadType call. --- util.go | 9 +++++---- util_test.go | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/util.go b/util.go index b6f6a98..92c2797 100644 --- a/util.go +++ b/util.go @@ -226,7 +226,8 @@ func mergeCodecs(codec Codec, codecs map[uint8]Codec) { codecs[savedCodec.PayloadType] = savedCodec } -func (s *SessionDescription) buildCodecMap() map[uint8]Codec { //nolint:cyclop +// GetCodecMap builds the codec map from the session description. +func (s *SessionDescription) GetCodecMap() map[uint8]Codec { //nolint:cyclop codecs := map[uint8]Codec{ // static codecs that do not require a rtpmap 0: { @@ -326,7 +327,7 @@ func codecsMatch(wanted, got Codec) bool { // GetCodecForPayloadType scans the SessionDescription for the given payload type and returns the codec. func (s *SessionDescription) GetCodecForPayloadType(payloadType uint8) (Codec, error) { - codecs := s.buildCodecMap() + codecs := s.GetCodecMap() codec, ok := codecs[payloadType] if ok { @@ -337,7 +338,7 @@ func (s *SessionDescription) GetCodecForPayloadType(payloadType uint8) (Codec, e } func (s *SessionDescription) GetCodecsForPayloadTypes(payloadTypes []uint8) ([]Codec, error) { - codecs := s.buildCodecMap() + codecs := s.GetCodecMap() result := make([]Codec, 0, len(payloadTypes)) for _, payloadType := range payloadTypes { @@ -353,7 +354,7 @@ func (s *SessionDescription) GetCodecsForPayloadTypes(payloadTypes []uint8) ([]C // GetPayloadTypeForCodec scans the SessionDescription for a codec that matches the provided codec // as closely as possible and returns its payload type. func (s *SessionDescription) GetPayloadTypeForCodec(wanted Codec) (uint8, error) { - codecs := s.buildCodecMap() + codecs := s.GetCodecMap() for payloadType, codec := range codecs { if codecsMatch(wanted, codec) { diff --git a/util_test.go b/util_test.go index 1f1d82c..df8ae61 100644 --- a/util_test.go +++ b/util_test.go @@ -521,3 +521,25 @@ func TestLexer_HandleType_SyntaxErrorWhenFnReturnsNil(t *testing.T) { var se syntaxError assert.ErrorAs(t, err, &se) } + +func BenchmarkGetCodecForPayloadType(b *testing.B) { + sd := getTestSessionDescription() + payloadTypes := []uint8{120, 121, 126, 97, 98} + + b.Run("WithoutCaching", func(b *testing.B) { + for i := 0; i < b.N; i++ { + for _, pt := range payloadTypes { + _, _ = sd.GetCodecForPayloadType(pt) + } + } + }) + + b.Run("WithCaching", func(b *testing.B) { + for i := 0; i < b.N; i++ { + codecMap := sd.GetCodecMap() + for _, pt := range payloadTypes { + _ = codecMap[pt] + } + } + }) +}