util.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. package sdp
  4. import (
  5. "errors"
  6. "fmt"
  7. "io"
  8. "sort"
  9. "strconv"
  10. "strings"
  11. "github.com/pion/randutil"
  12. )
  13. const (
  14. attributeKey = "a="
  15. )
  16. var (
  17. errExtractCodecRtpmap = errors.New("could not extract codec from rtpmap")
  18. errExtractCodecFmtp = errors.New("could not extract codec from fmtp")
  19. errExtractCodecRtcpFb = errors.New("could not extract codec from rtcp-fb")
  20. errPayloadTypeNotFound = errors.New("payload type not found")
  21. errCodecNotFound = errors.New("codec not found")
  22. errSyntaxError = errors.New("SyntaxError")
  23. )
  24. // ConnectionRole indicates which of the end points should initiate the connection establishment
  25. type ConnectionRole int
  26. const (
  27. // ConnectionRoleActive indicates the endpoint will initiate an outgoing connection.
  28. ConnectionRoleActive ConnectionRole = iota + 1
  29. // ConnectionRolePassive indicates the endpoint will accept an incoming connection.
  30. ConnectionRolePassive
  31. // ConnectionRoleActpass indicates the endpoint is willing to accept an incoming connection or to initiate an outgoing connection.
  32. ConnectionRoleActpass
  33. // ConnectionRoleHoldconn indicates the endpoint does not want the connection to be established for the time being.
  34. ConnectionRoleHoldconn
  35. )
  36. func (t ConnectionRole) String() string {
  37. switch t {
  38. case ConnectionRoleActive:
  39. return "active"
  40. case ConnectionRolePassive:
  41. return "passive"
  42. case ConnectionRoleActpass:
  43. return "actpass"
  44. case ConnectionRoleHoldconn:
  45. return "holdconn"
  46. default:
  47. return "Unknown"
  48. }
  49. }
  50. func newSessionID() (uint64, error) {
  51. // https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-26#section-5.2.1
  52. // Session ID is recommended to be constructed by generating a 64-bit
  53. // quantity with the highest bit set to zero and the remaining 63-bits
  54. // being cryptographically random.
  55. id, err := randutil.CryptoUint64()
  56. return id & (^(uint64(1) << 63)), err
  57. }
  58. // Codec represents a codec
  59. type Codec struct {
  60. PayloadType uint8
  61. Name string
  62. ClockRate uint32
  63. EncodingParameters string
  64. Fmtp string
  65. RTCPFeedback []string
  66. }
  67. const (
  68. unknown = iota
  69. )
  70. func (c Codec) String() string {
  71. return fmt.Sprintf("%d %s/%d/%s (%s) [%s]", c.PayloadType, c.Name, c.ClockRate, c.EncodingParameters, c.Fmtp, strings.Join(c.RTCPFeedback, ", "))
  72. }
  73. func parseRtpmap(rtpmap string) (Codec, error) {
  74. var codec Codec
  75. parsingFailed := errExtractCodecRtpmap
  76. // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encoding parameters>]
  77. split := strings.Split(rtpmap, " ")
  78. if len(split) != 2 {
  79. return codec, parsingFailed
  80. }
  81. ptSplit := strings.Split(split[0], ":")
  82. if len(ptSplit) != 2 {
  83. return codec, parsingFailed
  84. }
  85. ptInt, err := strconv.ParseUint(ptSplit[1], 10, 8)
  86. if err != nil {
  87. return codec, parsingFailed
  88. }
  89. codec.PayloadType = uint8(ptInt)
  90. split = strings.Split(split[1], "/")
  91. codec.Name = split[0]
  92. parts := len(split)
  93. if parts > 1 {
  94. rate, err := strconv.ParseUint(split[1], 10, 32)
  95. if err != nil {
  96. return codec, parsingFailed
  97. }
  98. codec.ClockRate = uint32(rate)
  99. }
  100. if parts > 2 {
  101. codec.EncodingParameters = split[2]
  102. }
  103. return codec, nil
  104. }
  105. func parseFmtp(fmtp string) (Codec, error) {
  106. var codec Codec
  107. parsingFailed := errExtractCodecFmtp
  108. // a=fmtp:<format> <format specific parameters>
  109. split := strings.Split(fmtp, " ")
  110. if len(split) != 2 {
  111. return codec, parsingFailed
  112. }
  113. formatParams := split[1]
  114. split = strings.Split(split[0], ":")
  115. if len(split) != 2 {
  116. return codec, parsingFailed
  117. }
  118. ptInt, err := strconv.ParseUint(split[1], 10, 8)
  119. if err != nil {
  120. return codec, parsingFailed
  121. }
  122. codec.PayloadType = uint8(ptInt)
  123. codec.Fmtp = formatParams
  124. return codec, nil
  125. }
  126. func parseRtcpFb(rtcpFb string) (Codec, error) {
  127. var codec Codec
  128. parsingFailed := errExtractCodecRtcpFb
  129. // a=ftcp-fb:<payload type> <RTCP feedback type> [<RTCP feedback parameter>]
  130. split := strings.SplitN(rtcpFb, " ", 2)
  131. if len(split) != 2 {
  132. return codec, parsingFailed
  133. }
  134. ptSplit := strings.Split(split[0], ":")
  135. if len(ptSplit) != 2 {
  136. return codec, parsingFailed
  137. }
  138. ptInt, err := strconv.ParseUint(ptSplit[1], 10, 8)
  139. if err != nil {
  140. return codec, parsingFailed
  141. }
  142. codec.PayloadType = uint8(ptInt)
  143. codec.RTCPFeedback = append(codec.RTCPFeedback, split[1])
  144. return codec, nil
  145. }
  146. func mergeCodecs(codec Codec, codecs map[uint8]Codec) {
  147. savedCodec := codecs[codec.PayloadType]
  148. if savedCodec.PayloadType == 0 {
  149. savedCodec.PayloadType = codec.PayloadType
  150. }
  151. if savedCodec.Name == "" {
  152. savedCodec.Name = codec.Name
  153. }
  154. if savedCodec.ClockRate == 0 {
  155. savedCodec.ClockRate = codec.ClockRate
  156. }
  157. if savedCodec.EncodingParameters == "" {
  158. savedCodec.EncodingParameters = codec.EncodingParameters
  159. }
  160. if savedCodec.Fmtp == "" {
  161. savedCodec.Fmtp = codec.Fmtp
  162. }
  163. savedCodec.RTCPFeedback = append(savedCodec.RTCPFeedback, codec.RTCPFeedback...)
  164. codecs[savedCodec.PayloadType] = savedCodec
  165. }
  166. func (s *SessionDescription) buildCodecMap() map[uint8]Codec {
  167. codecs := map[uint8]Codec{
  168. // static codecs that do not require a rtpmap
  169. 0: {
  170. PayloadType: 0,
  171. Name: "PCMU",
  172. ClockRate: 8000,
  173. },
  174. 8: {
  175. PayloadType: 8,
  176. Name: "PCMA",
  177. ClockRate: 8000,
  178. },
  179. }
  180. for _, m := range s.MediaDescriptions {
  181. for _, a := range m.Attributes {
  182. attr := a.String()
  183. switch {
  184. case strings.HasPrefix(attr, "rtpmap:"):
  185. codec, err := parseRtpmap(attr)
  186. if err == nil {
  187. mergeCodecs(codec, codecs)
  188. }
  189. case strings.HasPrefix(attr, "fmtp:"):
  190. codec, err := parseFmtp(attr)
  191. if err == nil {
  192. mergeCodecs(codec, codecs)
  193. }
  194. case strings.HasPrefix(attr, "rtcp-fb:"):
  195. codec, err := parseRtcpFb(attr)
  196. if err == nil {
  197. mergeCodecs(codec, codecs)
  198. }
  199. }
  200. }
  201. }
  202. return codecs
  203. }
  204. func equivalentFmtp(want, got string) bool {
  205. wantSplit := strings.Split(want, ";")
  206. gotSplit := strings.Split(got, ";")
  207. if len(wantSplit) != len(gotSplit) {
  208. return false
  209. }
  210. sort.Strings(wantSplit)
  211. sort.Strings(gotSplit)
  212. for i, wantPart := range wantSplit {
  213. wantPart = strings.TrimSpace(wantPart)
  214. gotPart := strings.TrimSpace(gotSplit[i])
  215. if gotPart != wantPart {
  216. return false
  217. }
  218. }
  219. return true
  220. }
  221. func codecsMatch(wanted, got Codec) bool {
  222. if wanted.Name != "" && !strings.EqualFold(wanted.Name, got.Name) {
  223. return false
  224. }
  225. if wanted.ClockRate != 0 && wanted.ClockRate != got.ClockRate {
  226. return false
  227. }
  228. if wanted.EncodingParameters != "" && wanted.EncodingParameters != got.EncodingParameters {
  229. return false
  230. }
  231. if wanted.Fmtp != "" && !equivalentFmtp(wanted.Fmtp, got.Fmtp) {
  232. return false
  233. }
  234. return true
  235. }
  236. // GetCodecForPayloadType scans the SessionDescription for the given payload type and returns the codec
  237. func (s *SessionDescription) GetCodecForPayloadType(payloadType uint8) (Codec, error) {
  238. codecs := s.buildCodecMap()
  239. codec, ok := codecs[payloadType]
  240. if ok {
  241. return codec, nil
  242. }
  243. return codec, errPayloadTypeNotFound
  244. }
  245. // GetPayloadTypeForCodec scans the SessionDescription for a codec that matches the provided codec
  246. // as closely as possible and returns its payload type
  247. func (s *SessionDescription) GetPayloadTypeForCodec(wanted Codec) (uint8, error) {
  248. codecs := s.buildCodecMap()
  249. for payloadType, codec := range codecs {
  250. if codecsMatch(wanted, codec) {
  251. return payloadType, nil
  252. }
  253. }
  254. return 0, errCodecNotFound
  255. }
  256. type stateFn func(*lexer) (stateFn, error)
  257. type lexer struct {
  258. desc *SessionDescription
  259. cache *unmarshalCache
  260. baseLexer
  261. }
  262. type keyToState func(key byte) stateFn
  263. func (l *lexer) handleType(fn keyToState) (stateFn, error) {
  264. key, err := l.readType()
  265. if errors.Is(err, io.EOF) && key == 0 {
  266. return nil, nil //nolint:nilnil
  267. } else if err != nil {
  268. return nil, err
  269. }
  270. if res := fn(key); res != nil {
  271. return res, nil
  272. }
  273. return nil, l.syntaxError()
  274. }