attributes.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. package interceptor
  4. import (
  5. "errors"
  6. "github.com/pion/rtcp"
  7. "github.com/pion/rtp"
  8. )
  9. type unmarshaledDataKeyType int
  10. const (
  11. rtpHeaderKey unmarshaledDataKeyType = iota
  12. rtcpPacketsKey
  13. )
  14. var errInvalidType = errors.New("found value of invalid type in attributes map")
  15. // Attributes are a generic key/value store used by interceptors
  16. type Attributes map[interface{}]interface{}
  17. // Get returns the attribute associated with key.
  18. func (a Attributes) Get(key interface{}) interface{} {
  19. return a[key]
  20. }
  21. // Set sets the attribute associated with key to the given value.
  22. func (a Attributes) Set(key interface{}, val interface{}) {
  23. a[key] = val
  24. }
  25. // GetRTPHeader gets the RTP header if present. If it is not present, it will be
  26. // unmarshalled from the raw byte slice and stored in the attribtues.
  27. func (a Attributes) GetRTPHeader(raw []byte) (*rtp.Header, error) {
  28. if val, ok := a[rtpHeaderKey]; ok {
  29. if header, ok := val.(*rtp.Header); ok {
  30. return header, nil
  31. }
  32. return nil, errInvalidType
  33. }
  34. header := &rtp.Header{}
  35. if _, err := header.Unmarshal(raw); err != nil {
  36. return nil, err
  37. }
  38. a[rtpHeaderKey] = header
  39. return header, nil
  40. }
  41. // GetRTCPPackets gets the RTCP packets if present. If the packet slice is not
  42. // present, it will be unmarshaled from the raw byte slice and stored in the
  43. // attributes.
  44. func (a Attributes) GetRTCPPackets(raw []byte) ([]rtcp.Packet, error) {
  45. if val, ok := a[rtcpPacketsKey]; ok {
  46. if packets, ok := val.([]rtcp.Packet); ok {
  47. return packets, nil
  48. }
  49. return nil, errInvalidType
  50. }
  51. pkts, err := rtcp.Unmarshal(raw)
  52. if err != nil {
  53. return nil, err
  54. }
  55. a[rtcpPacketsKey] = pkts
  56. return pkts, nil
  57. }