attributes.go 1.6 KB

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