peerconnection.go 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399
  1. //go:build !js
  2. // +build !js
  3. package webrtc
  4. import (
  5. "crypto/ecdsa"
  6. "crypto/elliptic"
  7. "crypto/rand"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "strconv"
  12. "strings"
  13. "sync"
  14. "sync/atomic"
  15. "time"
  16. "github.com/pion/ice/v2"
  17. "github.com/pion/interceptor"
  18. "github.com/pion/logging"
  19. "github.com/pion/rtcp"
  20. "github.com/pion/sdp/v3"
  21. "github.com/pion/webrtc/v3/internal/util"
  22. "github.com/pion/webrtc/v3/pkg/rtcerr"
  23. )
  24. // PeerConnection represents a WebRTC connection that establishes a
  25. // peer-to-peer communications with another PeerConnection instance in a
  26. // browser, or to another endpoint implementing the required protocols.
  27. type PeerConnection struct {
  28. statsID string
  29. mu sync.RWMutex
  30. sdpOrigin sdp.Origin
  31. // ops is an operations queue which will ensure the enqueued actions are
  32. // executed in order. It is used for asynchronously, but serially processing
  33. // remote and local descriptions
  34. ops *operations
  35. configuration Configuration
  36. currentLocalDescription *SessionDescription
  37. pendingLocalDescription *SessionDescription
  38. currentRemoteDescription *SessionDescription
  39. pendingRemoteDescription *SessionDescription
  40. signalingState SignalingState
  41. iceConnectionState atomic.Value // ICEConnectionState
  42. connectionState atomic.Value // PeerConnectionState
  43. idpLoginURL *string
  44. isClosed *atomicBool
  45. isNegotiationNeeded *atomicBool
  46. negotiationNeededState negotiationNeededState
  47. lastOffer string
  48. lastAnswer string
  49. // a value containing the last known greater mid value
  50. // we internally generate mids as numbers. Needed since JSEP
  51. // requires that when reusing a media section a new unique mid
  52. // should be defined (see JSEP 3.4.1).
  53. greaterMid int
  54. rtpTransceivers []*RTPTransceiver
  55. onSignalingStateChangeHandler func(SignalingState)
  56. onICEConnectionStateChangeHandler atomic.Value // func(ICEConnectionState)
  57. onConnectionStateChangeHandler atomic.Value // func(PeerConnectionState)
  58. onTrackHandler func(*TrackRemote, *RTPReceiver)
  59. onDataChannelHandler func(*DataChannel)
  60. onNegotiationNeededHandler atomic.Value // func()
  61. iceGatherer *ICEGatherer
  62. iceTransport *ICETransport
  63. dtlsTransport *DTLSTransport
  64. sctpTransport *SCTPTransport
  65. // A reference to the associated API state used by this connection
  66. api *API
  67. log logging.LeveledLogger
  68. interceptorRTCPWriter interceptor.RTCPWriter
  69. }
  70. // NewPeerConnection creates a PeerConnection with the default codecs and
  71. // interceptors. See RegisterDefaultCodecs and RegisterDefaultInterceptors.
  72. //
  73. // If you wish to customize the set of available codecs or the set of
  74. // active interceptors, create a MediaEngine and call api.NewPeerConnection
  75. // instead of this function.
  76. func NewPeerConnection(configuration Configuration) (*PeerConnection, error) {
  77. m := &MediaEngine{}
  78. if err := m.RegisterDefaultCodecs(); err != nil {
  79. return nil, err
  80. }
  81. i := &interceptor.Registry{}
  82. if err := RegisterDefaultInterceptors(m, i); err != nil {
  83. return nil, err
  84. }
  85. api := NewAPI(WithMediaEngine(m), WithInterceptorRegistry(i))
  86. return api.NewPeerConnection(configuration)
  87. }
  88. // NewPeerConnection creates a new PeerConnection with the provided configuration against the received API object
  89. func (api *API) NewPeerConnection(configuration Configuration) (*PeerConnection, error) {
  90. // https://w3c.github.io/webrtc-pc/#constructor (Step #2)
  91. // Some variables defined explicitly despite their implicit zero values to
  92. // allow better readability to understand what is happening.
  93. pc := &PeerConnection{
  94. statsID: fmt.Sprintf("PeerConnection-%d", time.Now().UnixNano()),
  95. configuration: Configuration{
  96. ICEServers: []ICEServer{},
  97. ICETransportPolicy: ICETransportPolicyAll,
  98. BundlePolicy: BundlePolicyBalanced,
  99. RTCPMuxPolicy: RTCPMuxPolicyRequire,
  100. Certificates: []Certificate{},
  101. ICECandidatePoolSize: 0,
  102. },
  103. ops: newOperations(),
  104. isClosed: &atomicBool{},
  105. isNegotiationNeeded: &atomicBool{},
  106. negotiationNeededState: negotiationNeededStateEmpty,
  107. lastOffer: "",
  108. lastAnswer: "",
  109. greaterMid: -1,
  110. signalingState: SignalingStateStable,
  111. api: api,
  112. log: api.settingEngine.LoggerFactory.NewLogger("pc"),
  113. }
  114. pc.iceConnectionState.Store(ICEConnectionStateNew)
  115. pc.connectionState.Store(PeerConnectionStateNew)
  116. i, err := api.interceptorRegistry.Build("")
  117. if err != nil {
  118. return nil, err
  119. }
  120. pc.api = &API{
  121. settingEngine: api.settingEngine,
  122. interceptor: i,
  123. }
  124. if api.settingEngine.disableMediaEngineCopy {
  125. pc.api.mediaEngine = api.mediaEngine
  126. } else {
  127. pc.api.mediaEngine = api.mediaEngine.copy()
  128. }
  129. if err = pc.initConfiguration(configuration); err != nil {
  130. return nil, err
  131. }
  132. pc.iceGatherer, err = pc.createICEGatherer()
  133. if err != nil {
  134. return nil, err
  135. }
  136. // Create the ice transport
  137. iceTransport := pc.createICETransport()
  138. pc.iceTransport = iceTransport
  139. // Create the DTLS transport
  140. dtlsTransport, err := pc.api.NewDTLSTransport(pc.iceTransport, pc.configuration.Certificates)
  141. if err != nil {
  142. return nil, err
  143. }
  144. pc.dtlsTransport = dtlsTransport
  145. // Create the SCTP transport
  146. pc.sctpTransport = pc.api.NewSCTPTransport(pc.dtlsTransport)
  147. // Wire up the on datachannel handler
  148. pc.sctpTransport.OnDataChannel(func(d *DataChannel) {
  149. pc.mu.RLock()
  150. handler := pc.onDataChannelHandler
  151. pc.mu.RUnlock()
  152. if handler != nil {
  153. handler(d)
  154. }
  155. })
  156. pc.interceptorRTCPWriter = pc.api.interceptor.BindRTCPWriter(interceptor.RTCPWriterFunc(pc.writeRTCP))
  157. return pc, nil
  158. }
  159. // initConfiguration defines validation of the specified Configuration and
  160. // its assignment to the internal configuration variable. This function differs
  161. // from its SetConfiguration counterpart because most of the checks do not
  162. // include verification statements related to the existing state. Thus the
  163. // function describes only minor verification of some the struct variables.
  164. func (pc *PeerConnection) initConfiguration(configuration Configuration) error {
  165. if configuration.PeerIdentity != "" {
  166. pc.configuration.PeerIdentity = configuration.PeerIdentity
  167. }
  168. // https://www.w3.org/TR/webrtc/#constructor (step #3)
  169. if len(configuration.Certificates) > 0 {
  170. now := time.Now()
  171. for _, x509Cert := range configuration.Certificates {
  172. if !x509Cert.Expires().IsZero() && now.After(x509Cert.Expires()) {
  173. return &rtcerr.InvalidAccessError{Err: ErrCertificateExpired}
  174. }
  175. pc.configuration.Certificates = append(pc.configuration.Certificates, x509Cert)
  176. }
  177. } else {
  178. sk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  179. if err != nil {
  180. return &rtcerr.UnknownError{Err: err}
  181. }
  182. certificate, err := GenerateCertificate(sk)
  183. if err != nil {
  184. return err
  185. }
  186. pc.configuration.Certificates = []Certificate{*certificate}
  187. }
  188. if configuration.BundlePolicy != BundlePolicy(Unknown) {
  189. pc.configuration.BundlePolicy = configuration.BundlePolicy
  190. }
  191. if configuration.RTCPMuxPolicy != RTCPMuxPolicy(Unknown) {
  192. pc.configuration.RTCPMuxPolicy = configuration.RTCPMuxPolicy
  193. }
  194. if configuration.ICECandidatePoolSize != 0 {
  195. pc.configuration.ICECandidatePoolSize = configuration.ICECandidatePoolSize
  196. }
  197. if configuration.ICETransportPolicy != ICETransportPolicy(Unknown) {
  198. pc.configuration.ICETransportPolicy = configuration.ICETransportPolicy
  199. }
  200. if configuration.SDPSemantics != SDPSemantics(Unknown) {
  201. pc.configuration.SDPSemantics = configuration.SDPSemantics
  202. }
  203. sanitizedICEServers := configuration.getICEServers()
  204. if len(sanitizedICEServers) > 0 {
  205. for _, server := range sanitizedICEServers {
  206. if err := server.validate(); err != nil {
  207. return err
  208. }
  209. }
  210. pc.configuration.ICEServers = sanitizedICEServers
  211. }
  212. return nil
  213. }
  214. // OnSignalingStateChange sets an event handler which is invoked when the
  215. // peer connection's signaling state changes
  216. func (pc *PeerConnection) OnSignalingStateChange(f func(SignalingState)) {
  217. pc.mu.Lock()
  218. defer pc.mu.Unlock()
  219. pc.onSignalingStateChangeHandler = f
  220. }
  221. func (pc *PeerConnection) onSignalingStateChange(newState SignalingState) {
  222. pc.mu.RLock()
  223. handler := pc.onSignalingStateChangeHandler
  224. pc.mu.RUnlock()
  225. pc.log.Infof("signaling state changed to %s", newState)
  226. if handler != nil {
  227. go handler(newState)
  228. }
  229. }
  230. // OnDataChannel sets an event handler which is invoked when a data
  231. // channel message arrives from a remote peer.
  232. func (pc *PeerConnection) OnDataChannel(f func(*DataChannel)) {
  233. pc.mu.Lock()
  234. defer pc.mu.Unlock()
  235. pc.onDataChannelHandler = f
  236. }
  237. // OnNegotiationNeeded sets an event handler which is invoked when
  238. // a change has occurred which requires session negotiation
  239. func (pc *PeerConnection) OnNegotiationNeeded(f func()) {
  240. pc.onNegotiationNeededHandler.Store(f)
  241. }
  242. // onNegotiationNeeded enqueues negotiationNeededOp if necessary
  243. // caller of this method should hold `pc.mu` lock
  244. func (pc *PeerConnection) onNegotiationNeeded() {
  245. // https://w3c.github.io/webrtc-pc/#updating-the-negotiation-needed-flag
  246. // non-canon step 1
  247. if pc.negotiationNeededState == negotiationNeededStateRun {
  248. pc.negotiationNeededState = negotiationNeededStateQueue
  249. return
  250. } else if pc.negotiationNeededState == negotiationNeededStateQueue {
  251. return
  252. }
  253. pc.negotiationNeededState = negotiationNeededStateRun
  254. pc.ops.Enqueue(pc.negotiationNeededOp)
  255. }
  256. func (pc *PeerConnection) negotiationNeededOp() {
  257. // Don't run NegotiatedNeeded checks if OnNegotiationNeeded is not set
  258. if handler, ok := pc.onNegotiationNeededHandler.Load().(func()); !ok || handler == nil {
  259. return
  260. }
  261. // https://www.w3.org/TR/webrtc/#updating-the-negotiation-needed-flag
  262. // Step 2.1
  263. if pc.isClosed.get() {
  264. return
  265. }
  266. // non-canon step 2.2
  267. if !pc.ops.IsEmpty() {
  268. pc.ops.Enqueue(pc.negotiationNeededOp)
  269. return
  270. }
  271. // non-canon, run again if there was a request
  272. defer func() {
  273. pc.mu.Lock()
  274. defer pc.mu.Unlock()
  275. if pc.negotiationNeededState == negotiationNeededStateQueue {
  276. defer pc.onNegotiationNeeded()
  277. }
  278. pc.negotiationNeededState = negotiationNeededStateEmpty
  279. }()
  280. // Step 2.3
  281. if pc.SignalingState() != SignalingStateStable {
  282. return
  283. }
  284. // Step 2.4
  285. if !pc.checkNegotiationNeeded() {
  286. pc.isNegotiationNeeded.set(false)
  287. return
  288. }
  289. // Step 2.5
  290. if pc.isNegotiationNeeded.get() {
  291. return
  292. }
  293. // Step 2.6
  294. pc.isNegotiationNeeded.set(true)
  295. // Step 2.7
  296. if handler, ok := pc.onNegotiationNeededHandler.Load().(func()); ok && handler != nil {
  297. handler()
  298. }
  299. }
  300. func (pc *PeerConnection) checkNegotiationNeeded() bool { //nolint:gocognit
  301. // To check if negotiation is needed for connection, perform the following checks:
  302. // Skip 1, 2 steps
  303. // Step 3
  304. pc.mu.Lock()
  305. defer pc.mu.Unlock()
  306. localDesc := pc.currentLocalDescription
  307. remoteDesc := pc.currentRemoteDescription
  308. if localDesc == nil {
  309. return true
  310. }
  311. pc.sctpTransport.lock.Lock()
  312. lenDataChannel := len(pc.sctpTransport.dataChannels)
  313. pc.sctpTransport.lock.Unlock()
  314. if lenDataChannel != 0 && haveDataChannel(localDesc) == nil {
  315. return true
  316. }
  317. for _, t := range pc.rtpTransceivers {
  318. // https://www.w3.org/TR/webrtc/#dfn-update-the-negotiation-needed-flag
  319. // Step 5.1
  320. // if t.stopping && !t.stopped {
  321. // return true
  322. // }
  323. m := getByMid(t.Mid(), localDesc)
  324. // Step 5.2
  325. if !t.stopped && m == nil {
  326. return true
  327. }
  328. if !t.stopped && m != nil {
  329. // Step 5.3.1
  330. if t.Direction() == RTPTransceiverDirectionSendrecv || t.Direction() == RTPTransceiverDirectionSendonly {
  331. descMsid, okMsid := m.Attribute(sdp.AttrKeyMsid)
  332. track := t.Sender().Track()
  333. if !okMsid || descMsid != track.StreamID()+" "+track.ID() {
  334. return true
  335. }
  336. }
  337. switch localDesc.Type {
  338. case SDPTypeOffer:
  339. // Step 5.3.2
  340. rm := getByMid(t.Mid(), remoteDesc)
  341. if rm == nil {
  342. return true
  343. }
  344. if getPeerDirection(m) != t.Direction() && getPeerDirection(rm) != t.Direction().Revers() {
  345. return true
  346. }
  347. case SDPTypeAnswer:
  348. // Step 5.3.3
  349. if _, ok := m.Attribute(t.Direction().String()); !ok {
  350. return true
  351. }
  352. default:
  353. }
  354. }
  355. // Step 5.4
  356. if t.stopped && t.Mid() != "" {
  357. if getByMid(t.Mid(), localDesc) != nil || getByMid(t.Mid(), remoteDesc) != nil {
  358. return true
  359. }
  360. }
  361. }
  362. // Step 6
  363. return false
  364. }
  365. // OnICECandidate sets an event handler which is invoked when a new ICE
  366. // candidate is found.
  367. // ICE candidate gathering only begins when SetLocalDescription or
  368. // SetRemoteDescription is called.
  369. // Take note that the handler will be called with a nil pointer when
  370. // gathering is finished.
  371. func (pc *PeerConnection) OnICECandidate(f func(*ICECandidate)) {
  372. pc.iceGatherer.OnLocalCandidate(f)
  373. }
  374. // OnICEGatheringStateChange sets an event handler which is invoked when the
  375. // ICE candidate gathering state has changed.
  376. func (pc *PeerConnection) OnICEGatheringStateChange(f func(ICEGathererState)) {
  377. pc.iceGatherer.OnStateChange(f)
  378. }
  379. // OnTrack sets an event handler which is called when remote track
  380. // arrives from a remote peer.
  381. func (pc *PeerConnection) OnTrack(f func(*TrackRemote, *RTPReceiver)) {
  382. pc.mu.Lock()
  383. defer pc.mu.Unlock()
  384. pc.onTrackHandler = f
  385. }
  386. func (pc *PeerConnection) onTrack(t *TrackRemote, r *RTPReceiver) {
  387. pc.mu.RLock()
  388. handler := pc.onTrackHandler
  389. pc.mu.RUnlock()
  390. pc.log.Debugf("got new track: %+v", t)
  391. if t != nil {
  392. if handler != nil {
  393. go handler(t, r)
  394. } else {
  395. pc.log.Warnf("OnTrack unset, unable to handle incoming media streams")
  396. }
  397. }
  398. }
  399. // OnICEConnectionStateChange sets an event handler which is called
  400. // when an ICE connection state is changed.
  401. func (pc *PeerConnection) OnICEConnectionStateChange(f func(ICEConnectionState)) {
  402. pc.onICEConnectionStateChangeHandler.Store(f)
  403. }
  404. func (pc *PeerConnection) onICEConnectionStateChange(cs ICEConnectionState) {
  405. pc.iceConnectionState.Store(cs)
  406. pc.log.Infof("ICE connection state changed: %s", cs)
  407. if handler, ok := pc.onICEConnectionStateChangeHandler.Load().(func(ICEConnectionState)); ok && handler != nil {
  408. handler(cs)
  409. }
  410. }
  411. // OnConnectionStateChange sets an event handler which is called
  412. // when the PeerConnectionState has changed
  413. func (pc *PeerConnection) OnConnectionStateChange(f func(PeerConnectionState)) {
  414. pc.onConnectionStateChangeHandler.Store(f)
  415. }
  416. func (pc *PeerConnection) onConnectionStateChange(cs PeerConnectionState) {
  417. pc.connectionState.Store(cs)
  418. pc.log.Infof("peer connection state changed: %s", cs)
  419. if handler, ok := pc.onConnectionStateChangeHandler.Load().(func(PeerConnectionState)); ok && handler != nil {
  420. go handler(cs)
  421. }
  422. }
  423. // SetConfiguration updates the configuration of this PeerConnection object.
  424. func (pc *PeerConnection) SetConfiguration(configuration Configuration) error { //nolint:gocognit
  425. // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-setconfiguration (step #2)
  426. if pc.isClosed.get() {
  427. return &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
  428. }
  429. // https://www.w3.org/TR/webrtc/#set-the-configuration (step #3)
  430. if configuration.PeerIdentity != "" {
  431. if configuration.PeerIdentity != pc.configuration.PeerIdentity {
  432. return &rtcerr.InvalidModificationError{Err: ErrModifyingPeerIdentity}
  433. }
  434. pc.configuration.PeerIdentity = configuration.PeerIdentity
  435. }
  436. // https://www.w3.org/TR/webrtc/#set-the-configuration (step #4)
  437. if len(configuration.Certificates) > 0 {
  438. if len(configuration.Certificates) != len(pc.configuration.Certificates) {
  439. return &rtcerr.InvalidModificationError{Err: ErrModifyingCertificates}
  440. }
  441. for i, certificate := range configuration.Certificates {
  442. if !pc.configuration.Certificates[i].Equals(certificate) {
  443. return &rtcerr.InvalidModificationError{Err: ErrModifyingCertificates}
  444. }
  445. }
  446. pc.configuration.Certificates = configuration.Certificates
  447. }
  448. // https://www.w3.org/TR/webrtc/#set-the-configuration (step #5)
  449. if configuration.BundlePolicy != BundlePolicy(Unknown) {
  450. if configuration.BundlePolicy != pc.configuration.BundlePolicy {
  451. return &rtcerr.InvalidModificationError{Err: ErrModifyingBundlePolicy}
  452. }
  453. pc.configuration.BundlePolicy = configuration.BundlePolicy
  454. }
  455. // https://www.w3.org/TR/webrtc/#set-the-configuration (step #6)
  456. if configuration.RTCPMuxPolicy != RTCPMuxPolicy(Unknown) {
  457. if configuration.RTCPMuxPolicy != pc.configuration.RTCPMuxPolicy {
  458. return &rtcerr.InvalidModificationError{Err: ErrModifyingRTCPMuxPolicy}
  459. }
  460. pc.configuration.RTCPMuxPolicy = configuration.RTCPMuxPolicy
  461. }
  462. // https://www.w3.org/TR/webrtc/#set-the-configuration (step #7)
  463. if configuration.ICECandidatePoolSize != 0 {
  464. if pc.configuration.ICECandidatePoolSize != configuration.ICECandidatePoolSize &&
  465. pc.LocalDescription() != nil {
  466. return &rtcerr.InvalidModificationError{Err: ErrModifyingICECandidatePoolSize}
  467. }
  468. pc.configuration.ICECandidatePoolSize = configuration.ICECandidatePoolSize
  469. }
  470. // https://www.w3.org/TR/webrtc/#set-the-configuration (step #8)
  471. if configuration.ICETransportPolicy != ICETransportPolicy(Unknown) {
  472. pc.configuration.ICETransportPolicy = configuration.ICETransportPolicy
  473. }
  474. // https://www.w3.org/TR/webrtc/#set-the-configuration (step #11)
  475. if len(configuration.ICEServers) > 0 {
  476. // https://www.w3.org/TR/webrtc/#set-the-configuration (step #11.3)
  477. for _, server := range configuration.ICEServers {
  478. if err := server.validate(); err != nil {
  479. return err
  480. }
  481. }
  482. pc.configuration.ICEServers = configuration.ICEServers
  483. }
  484. return nil
  485. }
  486. // GetConfiguration returns a Configuration object representing the current
  487. // configuration of this PeerConnection object. The returned object is a
  488. // copy and direct mutation on it will not take affect until SetConfiguration
  489. // has been called with Configuration passed as its only argument.
  490. // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-getconfiguration
  491. func (pc *PeerConnection) GetConfiguration() Configuration {
  492. return pc.configuration
  493. }
  494. func (pc *PeerConnection) getStatsID() string {
  495. pc.mu.RLock()
  496. defer pc.mu.RUnlock()
  497. return pc.statsID
  498. }
  499. // hasLocalDescriptionChanged returns whether local media (rtpTransceivers) has changed
  500. // caller of this method should hold `pc.mu` lock
  501. func (pc *PeerConnection) hasLocalDescriptionChanged(desc *SessionDescription) bool {
  502. for _, t := range pc.rtpTransceivers {
  503. m := getByMid(t.Mid(), desc)
  504. if m == nil {
  505. return true
  506. }
  507. if getPeerDirection(m) != t.Direction() {
  508. return true
  509. }
  510. }
  511. return false
  512. }
  513. // CreateOffer starts the PeerConnection and generates the localDescription
  514. // https://w3c.github.io/webrtc-pc/#dom-rtcpeerconnection-createoffer
  515. func (pc *PeerConnection) CreateOffer(options *OfferOptions) (SessionDescription, error) { //nolint:gocognit
  516. useIdentity := pc.idpLoginURL != nil
  517. switch {
  518. case useIdentity:
  519. return SessionDescription{}, errIdentityProviderNotImplemented
  520. case pc.isClosed.get():
  521. return SessionDescription{}, &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
  522. }
  523. if options != nil && options.ICERestart {
  524. if err := pc.iceTransport.restart(); err != nil {
  525. return SessionDescription{}, err
  526. }
  527. }
  528. var (
  529. d *sdp.SessionDescription
  530. offer SessionDescription
  531. err error
  532. )
  533. // This may be necessary to recompute if, for example, createOffer was called when only an
  534. // audio RTCRtpTransceiver was added to connection, but while performing the in-parallel
  535. // steps to create an offer, a video RTCRtpTransceiver was added, requiring additional
  536. // inspection of video system resources.
  537. count := 0
  538. pc.mu.Lock()
  539. defer pc.mu.Unlock()
  540. for {
  541. // We cache current transceivers to ensure they aren't
  542. // mutated during offer generation. We later check if they have
  543. // been mutated and recompute the offer if necessary.
  544. currentTransceivers := pc.rtpTransceivers
  545. // in-parallel steps to create an offer
  546. // https://w3c.github.io/webrtc-pc/#dfn-in-parallel-steps-to-create-an-offer
  547. isPlanB := pc.configuration.SDPSemantics == SDPSemanticsPlanB
  548. if pc.currentRemoteDescription != nil && isPlanB {
  549. isPlanB = descriptionPossiblyPlanB(pc.currentRemoteDescription)
  550. }
  551. // include unmatched local transceivers
  552. if !isPlanB {
  553. // update the greater mid if the remote description provides a greater one
  554. if pc.currentRemoteDescription != nil {
  555. var numericMid int
  556. for _, media := range pc.currentRemoteDescription.parsed.MediaDescriptions {
  557. mid := getMidValue(media)
  558. if mid == "" {
  559. continue
  560. }
  561. numericMid, err = strconv.Atoi(mid)
  562. if err != nil {
  563. continue
  564. }
  565. if numericMid > pc.greaterMid {
  566. pc.greaterMid = numericMid
  567. }
  568. }
  569. }
  570. for _, t := range currentTransceivers {
  571. if t.Mid() != "" {
  572. continue
  573. }
  574. pc.greaterMid++
  575. err = t.SetMid(strconv.Itoa(pc.greaterMid))
  576. if err != nil {
  577. return SessionDescription{}, err
  578. }
  579. }
  580. }
  581. if pc.currentRemoteDescription == nil {
  582. d, err = pc.generateUnmatchedSDP(currentTransceivers, useIdentity)
  583. } else {
  584. d, err = pc.generateMatchedSDP(currentTransceivers, useIdentity, true /*includeUnmatched */, connectionRoleFromDtlsRole(defaultDtlsRoleOffer))
  585. }
  586. if err != nil {
  587. return SessionDescription{}, err
  588. }
  589. updateSDPOrigin(&pc.sdpOrigin, d)
  590. sdpBytes, err := d.Marshal()
  591. if err != nil {
  592. return SessionDescription{}, err
  593. }
  594. offer = SessionDescription{
  595. Type: SDPTypeOffer,
  596. SDP: string(sdpBytes),
  597. parsed: d,
  598. }
  599. // Verify local media hasn't changed during offer
  600. // generation. Recompute if necessary
  601. if isPlanB || !pc.hasLocalDescriptionChanged(&offer) {
  602. break
  603. }
  604. count++
  605. if count >= 128 {
  606. return SessionDescription{}, errExcessiveRetries
  607. }
  608. }
  609. pc.lastOffer = offer.SDP
  610. return offer, nil
  611. }
  612. func (pc *PeerConnection) createICEGatherer() (*ICEGatherer, error) {
  613. g, err := pc.api.NewICEGatherer(ICEGatherOptions{
  614. ICEServers: pc.configuration.getICEServers(),
  615. ICEGatherPolicy: pc.configuration.ICETransportPolicy,
  616. })
  617. if err != nil {
  618. return nil, err
  619. }
  620. return g, nil
  621. }
  622. // Update the PeerConnectionState given the state of relevant transports
  623. // https://www.w3.org/TR/webrtc/#rtcpeerconnectionstate-enum
  624. func (pc *PeerConnection) updateConnectionState(iceConnectionState ICEConnectionState, dtlsTransportState DTLSTransportState) {
  625. connectionState := PeerConnectionStateNew
  626. switch {
  627. // The RTCPeerConnection object's [[IsClosed]] slot is true.
  628. case pc.isClosed.get():
  629. connectionState = PeerConnectionStateClosed
  630. // Any of the RTCIceTransports or RTCDtlsTransports are in a "failed" state.
  631. case iceConnectionState == ICEConnectionStateFailed || dtlsTransportState == DTLSTransportStateFailed:
  632. connectionState = PeerConnectionStateFailed
  633. // Any of the RTCIceTransports or RTCDtlsTransports are in the "disconnected"
  634. // state and none of them are in the "failed" or "connecting" or "checking" state. */
  635. case iceConnectionState == ICEConnectionStateDisconnected:
  636. connectionState = PeerConnectionStateDisconnected
  637. // All RTCIceTransports and RTCDtlsTransports are in the "connected", "completed" or "closed"
  638. // state and at least one of them is in the "connected" or "completed" state.
  639. case iceConnectionState == ICEConnectionStateConnected && dtlsTransportState == DTLSTransportStateConnected:
  640. connectionState = PeerConnectionStateConnected
  641. // Any of the RTCIceTransports or RTCDtlsTransports are in the "connecting" or
  642. // "checking" state and none of them is in the "failed" state.
  643. case iceConnectionState == ICEConnectionStateChecking && dtlsTransportState == DTLSTransportStateConnecting:
  644. connectionState = PeerConnectionStateConnecting
  645. }
  646. if pc.connectionState.Load() == connectionState {
  647. return
  648. }
  649. pc.onConnectionStateChange(connectionState)
  650. }
  651. func (pc *PeerConnection) createICETransport() *ICETransport {
  652. t := pc.api.NewICETransport(pc.iceGatherer)
  653. t.internalOnConnectionStateChangeHandler.Store(func(state ICETransportState) {
  654. var cs ICEConnectionState
  655. switch state {
  656. case ICETransportStateNew:
  657. cs = ICEConnectionStateNew
  658. case ICETransportStateChecking:
  659. cs = ICEConnectionStateChecking
  660. case ICETransportStateConnected:
  661. cs = ICEConnectionStateConnected
  662. case ICETransportStateCompleted:
  663. cs = ICEConnectionStateCompleted
  664. case ICETransportStateFailed:
  665. cs = ICEConnectionStateFailed
  666. case ICETransportStateDisconnected:
  667. cs = ICEConnectionStateDisconnected
  668. case ICETransportStateClosed:
  669. cs = ICEConnectionStateClosed
  670. default:
  671. pc.log.Warnf("OnConnectionStateChange: unhandled ICE state: %s", state)
  672. return
  673. }
  674. pc.onICEConnectionStateChange(cs)
  675. pc.updateConnectionState(cs, pc.dtlsTransport.State())
  676. })
  677. return t
  678. }
  679. // CreateAnswer starts the PeerConnection and generates the localDescription
  680. func (pc *PeerConnection) CreateAnswer(options *AnswerOptions) (SessionDescription, error) {
  681. useIdentity := pc.idpLoginURL != nil
  682. remoteDesc := pc.RemoteDescription()
  683. switch {
  684. case remoteDesc == nil:
  685. return SessionDescription{}, &rtcerr.InvalidStateError{Err: ErrNoRemoteDescription}
  686. case useIdentity:
  687. return SessionDescription{}, errIdentityProviderNotImplemented
  688. case pc.isClosed.get():
  689. return SessionDescription{}, &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
  690. case pc.signalingState.Get() != SignalingStateHaveRemoteOffer && pc.signalingState.Get() != SignalingStateHaveLocalPranswer:
  691. return SessionDescription{}, &rtcerr.InvalidStateError{Err: ErrIncorrectSignalingState}
  692. }
  693. connectionRole := connectionRoleFromDtlsRole(pc.api.settingEngine.answeringDTLSRole)
  694. if connectionRole == sdp.ConnectionRole(0) {
  695. connectionRole = connectionRoleFromDtlsRole(defaultDtlsRoleAnswer)
  696. // If one of the agents is lite and the other one is not, the lite agent must be the controlling agent.
  697. // If both or neither agents are lite the offering agent is controlling.
  698. // RFC 8445 S6.1.1
  699. if isIceLiteSet(remoteDesc.parsed) && !pc.api.settingEngine.candidates.ICELite {
  700. connectionRole = connectionRoleFromDtlsRole(DTLSRoleServer)
  701. }
  702. }
  703. pc.mu.Lock()
  704. defer pc.mu.Unlock()
  705. d, err := pc.generateMatchedSDP(pc.rtpTransceivers, useIdentity, false /*includeUnmatched */, connectionRole)
  706. if err != nil {
  707. return SessionDescription{}, err
  708. }
  709. updateSDPOrigin(&pc.sdpOrigin, d)
  710. sdpBytes, err := d.Marshal()
  711. if err != nil {
  712. return SessionDescription{}, err
  713. }
  714. desc := SessionDescription{
  715. Type: SDPTypeAnswer,
  716. SDP: string(sdpBytes),
  717. parsed: d,
  718. }
  719. pc.lastAnswer = desc.SDP
  720. return desc, nil
  721. }
  722. // 4.4.1.6 Set the SessionDescription
  723. func (pc *PeerConnection) setDescription(sd *SessionDescription, op stateChangeOp) error { //nolint:gocognit
  724. switch {
  725. case pc.isClosed.get():
  726. return &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
  727. case NewSDPType(sd.Type.String()) == SDPType(Unknown):
  728. return &rtcerr.TypeError{Err: fmt.Errorf("%w: '%d' is not a valid enum value of type SDPType", errPeerConnSDPTypeInvalidValue, sd.Type)}
  729. }
  730. nextState, err := func() (SignalingState, error) {
  731. pc.mu.Lock()
  732. defer pc.mu.Unlock()
  733. cur := pc.SignalingState()
  734. setLocal := stateChangeOpSetLocal
  735. setRemote := stateChangeOpSetRemote
  736. newSDPDoesNotMatchOffer := &rtcerr.InvalidModificationError{Err: errSDPDoesNotMatchOffer}
  737. newSDPDoesNotMatchAnswer := &rtcerr.InvalidModificationError{Err: errSDPDoesNotMatchAnswer}
  738. var nextState SignalingState
  739. var err error
  740. switch op {
  741. case setLocal:
  742. switch sd.Type {
  743. // stable->SetLocal(offer)->have-local-offer
  744. case SDPTypeOffer:
  745. if sd.SDP != pc.lastOffer {
  746. return nextState, newSDPDoesNotMatchOffer
  747. }
  748. nextState, err = checkNextSignalingState(cur, SignalingStateHaveLocalOffer, setLocal, sd.Type)
  749. if err == nil {
  750. pc.pendingLocalDescription = sd
  751. }
  752. // have-remote-offer->SetLocal(answer)->stable
  753. // have-local-pranswer->SetLocal(answer)->stable
  754. case SDPTypeAnswer:
  755. if sd.SDP != pc.lastAnswer {
  756. return nextState, newSDPDoesNotMatchAnswer
  757. }
  758. nextState, err = checkNextSignalingState(cur, SignalingStateStable, setLocal, sd.Type)
  759. if err == nil {
  760. pc.currentLocalDescription = sd
  761. pc.currentRemoteDescription = pc.pendingRemoteDescription
  762. pc.pendingRemoteDescription = nil
  763. pc.pendingLocalDescription = nil
  764. }
  765. case SDPTypeRollback:
  766. nextState, err = checkNextSignalingState(cur, SignalingStateStable, setLocal, sd.Type)
  767. if err == nil {
  768. pc.pendingLocalDescription = nil
  769. }
  770. // have-remote-offer->SetLocal(pranswer)->have-local-pranswer
  771. case SDPTypePranswer:
  772. if sd.SDP != pc.lastAnswer {
  773. return nextState, newSDPDoesNotMatchAnswer
  774. }
  775. nextState, err = checkNextSignalingState(cur, SignalingStateHaveLocalPranswer, setLocal, sd.Type)
  776. if err == nil {
  777. pc.pendingLocalDescription = sd
  778. }
  779. default:
  780. return nextState, &rtcerr.OperationError{Err: fmt.Errorf("%w: %s(%s)", errPeerConnStateChangeInvalid, op, sd.Type)}
  781. }
  782. case setRemote:
  783. switch sd.Type {
  784. // stable->SetRemote(offer)->have-remote-offer
  785. case SDPTypeOffer:
  786. nextState, err = checkNextSignalingState(cur, SignalingStateHaveRemoteOffer, setRemote, sd.Type)
  787. if err == nil {
  788. pc.pendingRemoteDescription = sd
  789. }
  790. // have-local-offer->SetRemote(answer)->stable
  791. // have-remote-pranswer->SetRemote(answer)->stable
  792. case SDPTypeAnswer:
  793. nextState, err = checkNextSignalingState(cur, SignalingStateStable, setRemote, sd.Type)
  794. if err == nil {
  795. pc.currentRemoteDescription = sd
  796. pc.currentLocalDescription = pc.pendingLocalDescription
  797. pc.pendingRemoteDescription = nil
  798. pc.pendingLocalDescription = nil
  799. }
  800. case SDPTypeRollback:
  801. nextState, err = checkNextSignalingState(cur, SignalingStateStable, setRemote, sd.Type)
  802. if err == nil {
  803. pc.pendingRemoteDescription = nil
  804. }
  805. // have-local-offer->SetRemote(pranswer)->have-remote-pranswer
  806. case SDPTypePranswer:
  807. nextState, err = checkNextSignalingState(cur, SignalingStateHaveRemotePranswer, setRemote, sd.Type)
  808. if err == nil {
  809. pc.pendingRemoteDescription = sd
  810. }
  811. default:
  812. return nextState, &rtcerr.OperationError{Err: fmt.Errorf("%w: %s(%s)", errPeerConnStateChangeInvalid, op, sd.Type)}
  813. }
  814. default:
  815. return nextState, &rtcerr.OperationError{Err: fmt.Errorf("%w: %q", errPeerConnStateChangeUnhandled, op)}
  816. }
  817. return nextState, err
  818. }()
  819. if err == nil {
  820. pc.signalingState.Set(nextState)
  821. if pc.signalingState.Get() == SignalingStateStable {
  822. pc.isNegotiationNeeded.set(false)
  823. pc.mu.Lock()
  824. pc.onNegotiationNeeded()
  825. pc.mu.Unlock()
  826. }
  827. pc.onSignalingStateChange(nextState)
  828. }
  829. return err
  830. }
  831. // SetLocalDescription sets the SessionDescription of the local peer
  832. func (pc *PeerConnection) SetLocalDescription(desc SessionDescription) error {
  833. if pc.isClosed.get() {
  834. return &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
  835. }
  836. haveLocalDescription := pc.currentLocalDescription != nil
  837. // JSEP 5.4
  838. if desc.SDP == "" {
  839. switch desc.Type {
  840. case SDPTypeAnswer, SDPTypePranswer:
  841. desc.SDP = pc.lastAnswer
  842. case SDPTypeOffer:
  843. desc.SDP = pc.lastOffer
  844. default:
  845. return &rtcerr.InvalidModificationError{
  846. Err: fmt.Errorf("%w: %s", errPeerConnSDPTypeInvalidValueSetLocalDescription, desc.Type),
  847. }
  848. }
  849. }
  850. desc.parsed = &sdp.SessionDescription{}
  851. if err := desc.parsed.Unmarshal([]byte(desc.SDP)); err != nil {
  852. return err
  853. }
  854. if err := pc.setDescription(&desc, stateChangeOpSetLocal); err != nil {
  855. return err
  856. }
  857. currentTransceivers := append([]*RTPTransceiver{}, pc.GetTransceivers()...)
  858. weAnswer := desc.Type == SDPTypeAnswer
  859. remoteDesc := pc.RemoteDescription()
  860. if weAnswer && remoteDesc != nil {
  861. if err := pc.startRTPSenders(currentTransceivers); err != nil {
  862. return err
  863. }
  864. pc.configureRTPReceivers(haveLocalDescription, remoteDesc, currentTransceivers)
  865. pc.ops.Enqueue(func() {
  866. pc.startRTP(haveLocalDescription, remoteDesc, currentTransceivers)
  867. })
  868. }
  869. if pc.iceGatherer.State() == ICEGathererStateNew {
  870. return pc.iceGatherer.Gather()
  871. }
  872. return nil
  873. }
  874. // LocalDescription returns PendingLocalDescription if it is not null and
  875. // otherwise it returns CurrentLocalDescription. This property is used to
  876. // determine if SetLocalDescription has already been called.
  877. // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-localdescription
  878. func (pc *PeerConnection) LocalDescription() *SessionDescription {
  879. if pendingLocalDescription := pc.PendingLocalDescription(); pendingLocalDescription != nil {
  880. return pendingLocalDescription
  881. }
  882. return pc.CurrentLocalDescription()
  883. }
  884. // SetRemoteDescription sets the SessionDescription of the remote peer
  885. // nolint: gocyclo
  886. func (pc *PeerConnection) SetRemoteDescription(desc SessionDescription) error { //nolint:gocognit
  887. if pc.isClosed.get() {
  888. return &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
  889. }
  890. isRenegotation := pc.currentRemoteDescription != nil
  891. if _, err := desc.Unmarshal(); err != nil {
  892. return err
  893. }
  894. if err := pc.setDescription(&desc, stateChangeOpSetRemote); err != nil {
  895. return err
  896. }
  897. if err := pc.api.mediaEngine.updateFromRemoteDescription(*desc.parsed); err != nil {
  898. return err
  899. }
  900. var t *RTPTransceiver
  901. localTransceivers := append([]*RTPTransceiver{}, pc.GetTransceivers()...)
  902. detectedPlanB := descriptionIsPlanB(pc.RemoteDescription(), pc.log)
  903. if pc.configuration.SDPSemantics != SDPSemanticsUnifiedPlan {
  904. detectedPlanB = descriptionPossiblyPlanB(pc.RemoteDescription())
  905. }
  906. weOffer := desc.Type == SDPTypeAnswer
  907. if !weOffer && !detectedPlanB {
  908. for _, media := range pc.RemoteDescription().parsed.MediaDescriptions {
  909. midValue := getMidValue(media)
  910. if midValue == "" {
  911. return errPeerConnRemoteDescriptionWithoutMidValue
  912. }
  913. if media.MediaName.Media == mediaSectionApplication {
  914. continue
  915. }
  916. kind := NewRTPCodecType(media.MediaName.Media)
  917. direction := getPeerDirection(media)
  918. if kind == 0 || direction == RTPTransceiverDirection(Unknown) {
  919. continue
  920. }
  921. t, localTransceivers = findByMid(midValue, localTransceivers)
  922. if t == nil {
  923. t, localTransceivers = satisfyTypeAndDirection(kind, direction, localTransceivers)
  924. } else if direction == RTPTransceiverDirectionInactive {
  925. if err := t.Stop(); err != nil {
  926. return err
  927. }
  928. }
  929. switch {
  930. case t == nil:
  931. receiver, err := pc.api.NewRTPReceiver(kind, pc.dtlsTransport)
  932. if err != nil {
  933. return err
  934. }
  935. localDirection := RTPTransceiverDirectionRecvonly
  936. if direction == RTPTransceiverDirectionRecvonly {
  937. localDirection = RTPTransceiverDirectionSendonly
  938. } else if direction == RTPTransceiverDirectionInactive {
  939. localDirection = RTPTransceiverDirectionInactive
  940. }
  941. t = newRTPTransceiver(receiver, nil, localDirection, kind, pc.api)
  942. pc.mu.Lock()
  943. pc.addRTPTransceiver(t)
  944. pc.mu.Unlock()
  945. // if transceiver is create by remote sdp, set prefer codec same as remote peer
  946. if codecs, err := codecsFromMediaDescription(media); err == nil {
  947. filteredCodecs := []RTPCodecParameters{}
  948. for _, codec := range codecs {
  949. if c, matchType := codecParametersFuzzySearch(codec, pc.api.mediaEngine.getCodecsByKind(kind)); matchType == codecMatchExact {
  950. // if codec match exact, use payloadtype register to mediaengine
  951. codec.PayloadType = c.PayloadType
  952. filteredCodecs = append(filteredCodecs, codec)
  953. }
  954. }
  955. _ = t.SetCodecPreferences(filteredCodecs)
  956. }
  957. case direction == RTPTransceiverDirectionRecvonly:
  958. if t.Direction() == RTPTransceiverDirectionSendrecv {
  959. t.setDirection(RTPTransceiverDirectionSendonly)
  960. }
  961. case direction == RTPTransceiverDirectionSendrecv:
  962. if t.Direction() == RTPTransceiverDirectionSendonly {
  963. t.setDirection(RTPTransceiverDirectionSendrecv)
  964. }
  965. }
  966. if t.Mid() == "" {
  967. if err := t.SetMid(midValue); err != nil {
  968. return err
  969. }
  970. }
  971. }
  972. }
  973. remoteUfrag, remotePwd, candidates, err := extractICEDetails(desc.parsed, pc.log)
  974. if err != nil {
  975. return err
  976. }
  977. if isRenegotation && pc.iceTransport.haveRemoteCredentialsChange(remoteUfrag, remotePwd) {
  978. // An ICE Restart only happens implicitly for a SetRemoteDescription of type offer
  979. if !weOffer {
  980. if err = pc.iceTransport.restart(); err != nil {
  981. return err
  982. }
  983. }
  984. if err = pc.iceTransport.setRemoteCredentials(remoteUfrag, remotePwd); err != nil {
  985. return err
  986. }
  987. }
  988. for i := range candidates {
  989. if err = pc.iceTransport.AddRemoteCandidate(&candidates[i]); err != nil {
  990. return err
  991. }
  992. }
  993. currentTransceivers := append([]*RTPTransceiver{}, pc.GetTransceivers()...)
  994. if isRenegotation {
  995. if weOffer {
  996. if err = pc.startRTPSenders(currentTransceivers); err != nil {
  997. return err
  998. }
  999. pc.configureRTPReceivers(true, &desc, currentTransceivers)
  1000. pc.ops.Enqueue(func() {
  1001. pc.startRTP(true, &desc, currentTransceivers)
  1002. })
  1003. }
  1004. return nil
  1005. }
  1006. remoteIsLite := isIceLiteSet(desc.parsed)
  1007. fingerprint, fingerprintHash, err := extractFingerprint(desc.parsed)
  1008. if err != nil {
  1009. return err
  1010. }
  1011. iceRole := ICERoleControlled
  1012. // If one of the agents is lite and the other one is not, the lite agent must be the controlling agent.
  1013. // If both or neither agents are lite the offering agent is controlling.
  1014. // RFC 8445 S6.1.1
  1015. if (weOffer && remoteIsLite == pc.api.settingEngine.candidates.ICELite) || (remoteIsLite && !pc.api.settingEngine.candidates.ICELite) {
  1016. iceRole = ICERoleControlling
  1017. }
  1018. // Start the networking in a new routine since it will block until
  1019. // the connection is actually established.
  1020. if weOffer {
  1021. if err := pc.startRTPSenders(currentTransceivers); err != nil {
  1022. return err
  1023. }
  1024. pc.configureRTPReceivers(false, &desc, currentTransceivers)
  1025. }
  1026. pc.ops.Enqueue(func() {
  1027. pc.startTransports(iceRole, dtlsRoleFromRemoteSDP(desc.parsed), remoteUfrag, remotePwd, fingerprint, fingerprintHash)
  1028. if weOffer {
  1029. pc.startRTP(false, &desc, currentTransceivers)
  1030. }
  1031. })
  1032. return nil
  1033. }
  1034. func (pc *PeerConnection) configureReceiver(incoming trackDetails, receiver *RTPReceiver) {
  1035. receiver.configureReceive(trackDetailsToRTPReceiveParameters(&incoming))
  1036. // set track id and label early so they can be set as new track information
  1037. // is received from the SDP.
  1038. for i := range receiver.tracks {
  1039. receiver.tracks[i].track.mu.Lock()
  1040. receiver.tracks[i].track.id = incoming.id
  1041. receiver.tracks[i].track.streamID = incoming.streamID
  1042. receiver.tracks[i].track.mu.Unlock()
  1043. }
  1044. }
  1045. func (pc *PeerConnection) startReceiver(incoming trackDetails, receiver *RTPReceiver) {
  1046. if err := receiver.startReceive(trackDetailsToRTPReceiveParameters(&incoming)); err != nil {
  1047. pc.log.Warnf("RTPReceiver Receive failed %s", err)
  1048. return
  1049. }
  1050. for _, t := range receiver.Tracks() {
  1051. if t.SSRC() == 0 || t.RID() != "" {
  1052. return
  1053. }
  1054. go func(track *TrackRemote) {
  1055. b := make([]byte, pc.api.settingEngine.getReceiveMTU())
  1056. n, _, err := track.peek(b)
  1057. if err != nil {
  1058. pc.log.Warnf("Could not determine PayloadType for SSRC %d (%s)", track.SSRC(), err)
  1059. return
  1060. }
  1061. if err = track.checkAndUpdateTrack(b[:n]); err != nil {
  1062. pc.log.Warnf("Failed to set codec settings for track SSRC %d (%s)", track.SSRC(), err)
  1063. return
  1064. }
  1065. pc.onTrack(track, receiver)
  1066. }(t)
  1067. }
  1068. }
  1069. func runIfNewReceiver(
  1070. incomingTrack trackDetails,
  1071. transceivers []*RTPTransceiver,
  1072. f func(incomingTrack trackDetails, receiver *RTPReceiver),
  1073. ) bool {
  1074. for _, t := range transceivers {
  1075. if t.Mid() != incomingTrack.mid {
  1076. continue
  1077. }
  1078. receiver := t.Receiver()
  1079. if (incomingTrack.kind != t.Kind()) ||
  1080. (t.Direction() != RTPTransceiverDirectionRecvonly && t.Direction() != RTPTransceiverDirectionSendrecv) ||
  1081. receiver == nil ||
  1082. (receiver.haveReceived()) {
  1083. continue
  1084. }
  1085. f(incomingTrack, receiver)
  1086. return true
  1087. }
  1088. return false
  1089. }
  1090. // configurepRTPReceivers opens knows inbound SRTP streams from the RemoteDescription
  1091. func (pc *PeerConnection) configureRTPReceivers(isRenegotiation bool, remoteDesc *SessionDescription, currentTransceivers []*RTPTransceiver) { //nolint:gocognit
  1092. incomingTracks := trackDetailsFromSDP(pc.log, remoteDesc.parsed)
  1093. if isRenegotiation {
  1094. for _, t := range currentTransceivers {
  1095. receiver := t.Receiver()
  1096. if receiver == nil {
  1097. continue
  1098. }
  1099. tracks := t.Receiver().Tracks()
  1100. if len(tracks) == 0 {
  1101. continue
  1102. }
  1103. receiverNeedsStopped := false
  1104. func() {
  1105. for _, t := range tracks {
  1106. t.mu.Lock()
  1107. defer t.mu.Unlock()
  1108. if t.rid != "" {
  1109. if details := trackDetailsForRID(incomingTracks, t.rid); details != nil {
  1110. t.id = details.id
  1111. t.streamID = details.streamID
  1112. continue
  1113. }
  1114. } else if t.ssrc != 0 {
  1115. if details := trackDetailsForSSRC(incomingTracks, t.ssrc); details != nil {
  1116. t.id = details.id
  1117. t.streamID = details.streamID
  1118. continue
  1119. }
  1120. }
  1121. receiverNeedsStopped = true
  1122. }
  1123. }()
  1124. if !receiverNeedsStopped {
  1125. continue
  1126. }
  1127. if err := receiver.Stop(); err != nil {
  1128. pc.log.Warnf("Failed to stop RtpReceiver: %s", err)
  1129. continue
  1130. }
  1131. receiver, err := pc.api.NewRTPReceiver(receiver.kind, pc.dtlsTransport)
  1132. if err != nil {
  1133. pc.log.Warnf("Failed to create new RtpReceiver: %s", err)
  1134. continue
  1135. }
  1136. t.setReceiver(receiver)
  1137. }
  1138. }
  1139. localTransceivers := append([]*RTPTransceiver{}, currentTransceivers...)
  1140. // Ensure we haven't already started a transceiver for this ssrc
  1141. filteredTracks := append([]trackDetails{}, incomingTracks...)
  1142. for _, incomingTrack := range incomingTracks {
  1143. // If we already have a TrackRemote for a given SSRC don't handle it again
  1144. for _, t := range localTransceivers {
  1145. if receiver := t.Receiver(); receiver != nil {
  1146. for _, track := range receiver.Tracks() {
  1147. for _, ssrc := range incomingTrack.ssrcs {
  1148. if ssrc == track.SSRC() {
  1149. filteredTracks = filterTrackWithSSRC(filteredTracks, track.SSRC())
  1150. }
  1151. }
  1152. }
  1153. }
  1154. }
  1155. }
  1156. for _, incomingTrack := range filteredTracks {
  1157. _ = runIfNewReceiver(incomingTrack, localTransceivers, pc.configureReceiver)
  1158. }
  1159. }
  1160. // startRTPReceivers opens knows inbound SRTP streams from the RemoteDescription
  1161. func (pc *PeerConnection) startRTPReceivers(remoteDesc *SessionDescription, currentTransceivers []*RTPTransceiver) {
  1162. incomingTracks := trackDetailsFromSDP(pc.log, remoteDesc.parsed)
  1163. if len(incomingTracks) == 0 {
  1164. return
  1165. }
  1166. localTransceivers := append([]*RTPTransceiver{}, currentTransceivers...)
  1167. unhandledTracks := incomingTracks[:0]
  1168. for _, incomingTrack := range incomingTracks {
  1169. trackHandled := runIfNewReceiver(incomingTrack, localTransceivers, pc.startReceiver)
  1170. if !trackHandled {
  1171. unhandledTracks = append(unhandledTracks, incomingTrack)
  1172. }
  1173. }
  1174. remoteIsPlanB := false
  1175. switch pc.configuration.SDPSemantics {
  1176. case SDPSemanticsPlanB:
  1177. remoteIsPlanB = true
  1178. case SDPSemanticsUnifiedPlanWithFallback:
  1179. remoteIsPlanB = descriptionPossiblyPlanB(pc.RemoteDescription())
  1180. default:
  1181. // none
  1182. }
  1183. if remoteIsPlanB {
  1184. for _, incomingTrack := range unhandledTracks {
  1185. t, err := pc.AddTransceiverFromKind(incomingTrack.kind, RTPTransceiverInit{
  1186. Direction: RTPTransceiverDirectionSendrecv,
  1187. })
  1188. if err != nil {
  1189. pc.log.Warnf("Could not add transceiver for remote SSRC %d: %s", incomingTrack.ssrcs[0], err)
  1190. continue
  1191. }
  1192. pc.configureReceiver(incomingTrack, t.Receiver())
  1193. pc.startReceiver(incomingTrack, t.Receiver())
  1194. }
  1195. }
  1196. }
  1197. // startRTPSenders starts all outbound RTP streams
  1198. func (pc *PeerConnection) startRTPSenders(currentTransceivers []*RTPTransceiver) error {
  1199. for _, transceiver := range currentTransceivers {
  1200. if sender := transceiver.Sender(); sender != nil && sender.isNegotiated() && !sender.hasSent() {
  1201. err := sender.Send(sender.GetParameters())
  1202. if err != nil {
  1203. return err
  1204. }
  1205. }
  1206. }
  1207. return nil
  1208. }
  1209. // Start SCTP subsystem
  1210. func (pc *PeerConnection) startSCTP() {
  1211. // Start sctp
  1212. if err := pc.sctpTransport.Start(SCTPCapabilities{
  1213. MaxMessageSize: 0,
  1214. }); err != nil {
  1215. pc.log.Warnf("Failed to start SCTP: %s", err)
  1216. if err = pc.sctpTransport.Stop(); err != nil {
  1217. pc.log.Warnf("Failed to stop SCTPTransport: %s", err)
  1218. }
  1219. return
  1220. }
  1221. }
  1222. func (pc *PeerConnection) handleUndeclaredSSRC(ssrc SSRC, remoteDescription *SessionDescription) (handled bool, err error) {
  1223. if len(remoteDescription.parsed.MediaDescriptions) != 1 {
  1224. return false, nil
  1225. }
  1226. onlyMediaSection := remoteDescription.parsed.MediaDescriptions[0]
  1227. streamID := ""
  1228. id := ""
  1229. for _, a := range onlyMediaSection.Attributes {
  1230. switch a.Key {
  1231. case sdp.AttrKeyMsid:
  1232. if split := strings.Split(a.Value, " "); len(split) == 2 {
  1233. streamID = split[0]
  1234. id = split[1]
  1235. }
  1236. case sdp.AttrKeySSRC:
  1237. return false, errPeerConnSingleMediaSectionHasExplicitSSRC
  1238. case sdpAttributeRid:
  1239. return false, nil
  1240. }
  1241. }
  1242. incoming := trackDetails{
  1243. ssrcs: []SSRC{ssrc},
  1244. kind: RTPCodecTypeVideo,
  1245. streamID: streamID,
  1246. id: id,
  1247. }
  1248. if onlyMediaSection.MediaName.Media == RTPCodecTypeAudio.String() {
  1249. incoming.kind = RTPCodecTypeAudio
  1250. }
  1251. t, err := pc.AddTransceiverFromKind(incoming.kind, RTPTransceiverInit{
  1252. Direction: RTPTransceiverDirectionSendrecv,
  1253. })
  1254. if err != nil {
  1255. return false, fmt.Errorf("%w: %d: %s", errPeerConnRemoteSSRCAddTransceiver, ssrc, err)
  1256. }
  1257. pc.configureReceiver(incoming, t.Receiver())
  1258. pc.startReceiver(incoming, t.Receiver())
  1259. return true, nil
  1260. }
  1261. func (pc *PeerConnection) handleIncomingSSRC(rtpStream io.Reader, ssrc SSRC) error { //nolint:gocognit
  1262. remoteDescription := pc.RemoteDescription()
  1263. if remoteDescription == nil {
  1264. return errPeerConnRemoteDescriptionNil
  1265. }
  1266. // If a SSRC already exists in the RemoteDescription don't perform heuristics upon it
  1267. for _, track := range trackDetailsFromSDP(pc.log, remoteDescription.parsed) {
  1268. if track.repairSsrc != nil && ssrc == *track.repairSsrc {
  1269. return nil
  1270. }
  1271. for _, trackSsrc := range track.ssrcs {
  1272. if ssrc == trackSsrc {
  1273. return nil
  1274. }
  1275. }
  1276. }
  1277. // If the remote SDP was only one media section the ssrc doesn't have to be explicitly declared
  1278. if handled, err := pc.handleUndeclaredSSRC(ssrc, remoteDescription); handled || err != nil {
  1279. return err
  1280. }
  1281. midExtensionID, audioSupported, videoSupported := pc.api.mediaEngine.getHeaderExtensionID(RTPHeaderExtensionCapability{sdp.SDESMidURI})
  1282. if !audioSupported && !videoSupported {
  1283. return errPeerConnSimulcastMidRTPExtensionRequired
  1284. }
  1285. streamIDExtensionID, audioSupported, videoSupported := pc.api.mediaEngine.getHeaderExtensionID(RTPHeaderExtensionCapability{sdp.SDESRTPStreamIDURI})
  1286. if !audioSupported && !videoSupported {
  1287. return errPeerConnSimulcastStreamIDRTPExtensionRequired
  1288. }
  1289. repairStreamIDExtensionID, _, _ := pc.api.mediaEngine.getHeaderExtensionID(RTPHeaderExtensionCapability{sdesRepairRTPStreamIDURI})
  1290. b := make([]byte, pc.api.settingEngine.getReceiveMTU())
  1291. i, err := rtpStream.Read(b)
  1292. if err != nil {
  1293. return err
  1294. }
  1295. var mid, rid, rsid string
  1296. payloadType, err := handleUnknownRTPPacket(b[:i], uint8(midExtensionID), uint8(streamIDExtensionID), uint8(repairStreamIDExtensionID), &mid, &rid, &rsid)
  1297. if err != nil {
  1298. return err
  1299. }
  1300. params, err := pc.api.mediaEngine.getRTPParametersByPayloadType(payloadType)
  1301. if err != nil {
  1302. return err
  1303. }
  1304. streamInfo := createStreamInfo("", ssrc, params.Codecs[0].PayloadType, params.Codecs[0].RTPCodecCapability, params.HeaderExtensions)
  1305. readStream, interceptor, rtcpReadStream, rtcpInterceptor, err := pc.dtlsTransport.streamsForSSRC(ssrc, *streamInfo)
  1306. if err != nil {
  1307. return err
  1308. }
  1309. for readCount := 0; readCount <= simulcastProbeCount; readCount++ {
  1310. if mid == "" || (rid == "" && rsid == "") {
  1311. i, _, err := interceptor.Read(b, nil)
  1312. if err != nil {
  1313. return err
  1314. }
  1315. if _, err = handleUnknownRTPPacket(b[:i], uint8(midExtensionID), uint8(streamIDExtensionID), uint8(repairStreamIDExtensionID), &mid, &rid, &rsid); err != nil {
  1316. return err
  1317. }
  1318. continue
  1319. }
  1320. for _, t := range pc.GetTransceivers() {
  1321. receiver := t.Receiver()
  1322. if t.Mid() != mid || receiver == nil {
  1323. continue
  1324. }
  1325. if rsid != "" {
  1326. receiver.mu.Lock()
  1327. defer receiver.mu.Unlock()
  1328. return receiver.receiveForRtx(SSRC(0), rsid, streamInfo, readStream, interceptor, rtcpReadStream, rtcpInterceptor)
  1329. }
  1330. track, err := receiver.receiveForRid(rid, params, streamInfo, readStream, interceptor, rtcpReadStream, rtcpInterceptor)
  1331. if err != nil {
  1332. return err
  1333. }
  1334. pc.onTrack(track, receiver)
  1335. return nil
  1336. }
  1337. }
  1338. pc.api.interceptor.UnbindRemoteStream(streamInfo)
  1339. return errPeerConnSimulcastIncomingSSRCFailed
  1340. }
  1341. // undeclaredMediaProcessor handles RTP/RTCP packets that don't match any a:ssrc lines
  1342. func (pc *PeerConnection) undeclaredMediaProcessor() {
  1343. go func() {
  1344. var simulcastRoutineCount uint64
  1345. for {
  1346. srtpSession, err := pc.dtlsTransport.getSRTPSession()
  1347. if err != nil {
  1348. pc.log.Warnf("undeclaredMediaProcessor failed to open SrtpSession: %v", err)
  1349. return
  1350. }
  1351. stream, ssrc, err := srtpSession.AcceptStream()
  1352. if err != nil {
  1353. pc.log.Warnf("Failed to accept RTP %v", err)
  1354. return
  1355. }
  1356. if pc.isClosed.get() {
  1357. if err = stream.Close(); err != nil {
  1358. pc.log.Warnf("Failed to close RTP stream %v", err)
  1359. }
  1360. continue
  1361. }
  1362. if atomic.AddUint64(&simulcastRoutineCount, 1) >= simulcastMaxProbeRoutines {
  1363. atomic.AddUint64(&simulcastRoutineCount, ^uint64(0))
  1364. pc.log.Warn(ErrSimulcastProbeOverflow.Error())
  1365. continue
  1366. }
  1367. go func(rtpStream io.Reader, ssrc SSRC) {
  1368. pc.dtlsTransport.storeSimulcastStream(stream)
  1369. if err := pc.handleIncomingSSRC(rtpStream, ssrc); err != nil {
  1370. pc.log.Errorf(incomingUnhandledRTPSsrc, ssrc, err)
  1371. }
  1372. atomic.AddUint64(&simulcastRoutineCount, ^uint64(0))
  1373. }(stream, SSRC(ssrc))
  1374. }
  1375. }()
  1376. go func() {
  1377. for {
  1378. srtcpSession, err := pc.dtlsTransport.getSRTCPSession()
  1379. if err != nil {
  1380. pc.log.Warnf("undeclaredMediaProcessor failed to open SrtcpSession: %v", err)
  1381. return
  1382. }
  1383. _, ssrc, err := srtcpSession.AcceptStream()
  1384. if err != nil {
  1385. pc.log.Warnf("Failed to accept RTCP %v", err)
  1386. return
  1387. }
  1388. pc.log.Warnf("Incoming unhandled RTCP ssrc(%d), OnTrack will not be fired", ssrc)
  1389. }
  1390. }()
  1391. }
  1392. // RemoteDescription returns pendingRemoteDescription if it is not null and
  1393. // otherwise it returns currentRemoteDescription. This property is used to
  1394. // determine if setRemoteDescription has already been called.
  1395. // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-remotedescription
  1396. func (pc *PeerConnection) RemoteDescription() *SessionDescription {
  1397. pc.mu.RLock()
  1398. defer pc.mu.RUnlock()
  1399. if pc.pendingRemoteDescription != nil {
  1400. return pc.pendingRemoteDescription
  1401. }
  1402. return pc.currentRemoteDescription
  1403. }
  1404. // AddICECandidate accepts an ICE candidate string and adds it
  1405. // to the existing set of candidates.
  1406. func (pc *PeerConnection) AddICECandidate(candidate ICECandidateInit) error {
  1407. if pc.RemoteDescription() == nil {
  1408. return &rtcerr.InvalidStateError{Err: ErrNoRemoteDescription}
  1409. }
  1410. candidateValue := strings.TrimPrefix(candidate.Candidate, "candidate:")
  1411. var iceCandidate *ICECandidate
  1412. if candidateValue != "" {
  1413. candidate, err := ice.UnmarshalCandidate(candidateValue)
  1414. if err != nil {
  1415. if errors.Is(err, ice.ErrUnknownCandidateTyp) || errors.Is(err, ice.ErrDetermineNetworkType) {
  1416. pc.log.Warnf("Discarding remote candidate: %s", err)
  1417. return nil
  1418. }
  1419. return err
  1420. }
  1421. c, err := newICECandidateFromICE(candidate)
  1422. if err != nil {
  1423. return err
  1424. }
  1425. iceCandidate = &c
  1426. }
  1427. return pc.iceTransport.AddRemoteCandidate(iceCandidate)
  1428. }
  1429. // ICEConnectionState returns the ICE connection state of the
  1430. // PeerConnection instance.
  1431. func (pc *PeerConnection) ICEConnectionState() ICEConnectionState {
  1432. if state, ok := pc.iceConnectionState.Load().(ICEConnectionState); ok {
  1433. return state
  1434. }
  1435. return ICEConnectionState(0)
  1436. }
  1437. // GetSenders returns the RTPSender that are currently attached to this PeerConnection
  1438. func (pc *PeerConnection) GetSenders() (result []*RTPSender) {
  1439. pc.mu.Lock()
  1440. defer pc.mu.Unlock()
  1441. for _, transceiver := range pc.rtpTransceivers {
  1442. if sender := transceiver.Sender(); sender != nil {
  1443. result = append(result, sender)
  1444. }
  1445. }
  1446. return result
  1447. }
  1448. // GetReceivers returns the RTPReceivers that are currently attached to this PeerConnection
  1449. func (pc *PeerConnection) GetReceivers() (receivers []*RTPReceiver) {
  1450. pc.mu.Lock()
  1451. defer pc.mu.Unlock()
  1452. for _, transceiver := range pc.rtpTransceivers {
  1453. if receiver := transceiver.Receiver(); receiver != nil {
  1454. receivers = append(receivers, receiver)
  1455. }
  1456. }
  1457. return
  1458. }
  1459. // GetTransceivers returns the RtpTransceiver that are currently attached to this PeerConnection
  1460. func (pc *PeerConnection) GetTransceivers() []*RTPTransceiver {
  1461. pc.mu.Lock()
  1462. defer pc.mu.Unlock()
  1463. return pc.rtpTransceivers
  1464. }
  1465. // AddTrack adds a Track to the PeerConnection
  1466. func (pc *PeerConnection) AddTrack(track TrackLocal) (*RTPSender, error) {
  1467. if pc.isClosed.get() {
  1468. return nil, &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
  1469. }
  1470. pc.mu.Lock()
  1471. defer pc.mu.Unlock()
  1472. for _, t := range pc.rtpTransceivers {
  1473. if !t.stopped && t.kind == track.Kind() && t.Sender() == nil {
  1474. sender, err := pc.api.NewRTPSender(track, pc.dtlsTransport)
  1475. if err == nil {
  1476. err = t.SetSender(sender, track)
  1477. if err != nil {
  1478. _ = sender.Stop()
  1479. t.setSender(nil)
  1480. }
  1481. }
  1482. if err != nil {
  1483. return nil, err
  1484. }
  1485. pc.onNegotiationNeeded()
  1486. return sender, nil
  1487. }
  1488. }
  1489. transceiver, err := pc.newTransceiverFromTrack(RTPTransceiverDirectionSendrecv, track)
  1490. if err != nil {
  1491. return nil, err
  1492. }
  1493. pc.addRTPTransceiver(transceiver)
  1494. return transceiver.Sender(), nil
  1495. }
  1496. // RemoveTrack removes a Track from the PeerConnection
  1497. func (pc *PeerConnection) RemoveTrack(sender *RTPSender) (err error) {
  1498. if pc.isClosed.get() {
  1499. return &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
  1500. }
  1501. var transceiver *RTPTransceiver
  1502. pc.mu.Lock()
  1503. defer pc.mu.Unlock()
  1504. for _, t := range pc.rtpTransceivers {
  1505. if t.Sender() == sender {
  1506. transceiver = t
  1507. break
  1508. }
  1509. }
  1510. if transceiver == nil {
  1511. return &rtcerr.InvalidAccessError{Err: ErrSenderNotCreatedByConnection}
  1512. } else if err = sender.Stop(); err == nil {
  1513. err = transceiver.setSendingTrack(nil)
  1514. if err == nil {
  1515. pc.onNegotiationNeeded()
  1516. }
  1517. }
  1518. return
  1519. }
  1520. func (pc *PeerConnection) newTransceiverFromTrack(direction RTPTransceiverDirection, track TrackLocal) (t *RTPTransceiver, err error) {
  1521. var (
  1522. r *RTPReceiver
  1523. s *RTPSender
  1524. )
  1525. switch direction {
  1526. case RTPTransceiverDirectionSendrecv:
  1527. r, err = pc.api.NewRTPReceiver(track.Kind(), pc.dtlsTransport)
  1528. if err != nil {
  1529. return
  1530. }
  1531. s, err = pc.api.NewRTPSender(track, pc.dtlsTransport)
  1532. case RTPTransceiverDirectionSendonly:
  1533. s, err = pc.api.NewRTPSender(track, pc.dtlsTransport)
  1534. default:
  1535. err = errPeerConnAddTransceiverFromTrackSupport
  1536. }
  1537. if err != nil {
  1538. return
  1539. }
  1540. return newRTPTransceiver(r, s, direction, track.Kind(), pc.api), nil
  1541. }
  1542. // AddTransceiverFromKind Create a new RtpTransceiver and adds it to the set of transceivers.
  1543. func (pc *PeerConnection) AddTransceiverFromKind(kind RTPCodecType, init ...RTPTransceiverInit) (t *RTPTransceiver, err error) {
  1544. if pc.isClosed.get() {
  1545. return nil, &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
  1546. }
  1547. direction := RTPTransceiverDirectionSendrecv
  1548. if len(init) > 1 {
  1549. return nil, errPeerConnAddTransceiverFromKindOnlyAcceptsOne
  1550. } else if len(init) == 1 {
  1551. direction = init[0].Direction
  1552. }
  1553. switch direction {
  1554. case RTPTransceiverDirectionSendonly, RTPTransceiverDirectionSendrecv:
  1555. codecs := pc.api.mediaEngine.getCodecsByKind(kind)
  1556. if len(codecs) == 0 {
  1557. return nil, ErrNoCodecsAvailable
  1558. }
  1559. track, err := NewTrackLocalStaticSample(codecs[0].RTPCodecCapability, util.MathRandAlpha(16), util.MathRandAlpha(16))
  1560. if err != nil {
  1561. return nil, err
  1562. }
  1563. t, err = pc.newTransceiverFromTrack(direction, track)
  1564. if err != nil {
  1565. return nil, err
  1566. }
  1567. case RTPTransceiverDirectionRecvonly:
  1568. receiver, err := pc.api.NewRTPReceiver(kind, pc.dtlsTransport)
  1569. if err != nil {
  1570. return nil, err
  1571. }
  1572. t = newRTPTransceiver(receiver, nil, RTPTransceiverDirectionRecvonly, kind, pc.api)
  1573. default:
  1574. return nil, errPeerConnAddTransceiverFromKindSupport
  1575. }
  1576. pc.mu.Lock()
  1577. pc.addRTPTransceiver(t)
  1578. pc.mu.Unlock()
  1579. return t, nil
  1580. }
  1581. // AddTransceiverFromTrack Create a new RtpTransceiver(SendRecv or SendOnly) and add it to the set of transceivers.
  1582. func (pc *PeerConnection) AddTransceiverFromTrack(track TrackLocal, init ...RTPTransceiverInit) (t *RTPTransceiver, err error) {
  1583. if pc.isClosed.get() {
  1584. return nil, &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
  1585. }
  1586. direction := RTPTransceiverDirectionSendrecv
  1587. if len(init) > 1 {
  1588. return nil, errPeerConnAddTransceiverFromTrackOnlyAcceptsOne
  1589. } else if len(init) == 1 {
  1590. direction = init[0].Direction
  1591. }
  1592. t, err = pc.newTransceiverFromTrack(direction, track)
  1593. if err == nil {
  1594. pc.mu.Lock()
  1595. pc.addRTPTransceiver(t)
  1596. pc.mu.Unlock()
  1597. }
  1598. return
  1599. }
  1600. // CreateDataChannel creates a new DataChannel object with the given label
  1601. // and optional DataChannelInit used to configure properties of the
  1602. // underlying channel such as data reliability.
  1603. func (pc *PeerConnection) CreateDataChannel(label string, options *DataChannelInit) (*DataChannel, error) {
  1604. // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #2)
  1605. if pc.isClosed.get() {
  1606. return nil, &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
  1607. }
  1608. params := &DataChannelParameters{
  1609. Label: label,
  1610. Ordered: true,
  1611. }
  1612. // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #19)
  1613. if options != nil {
  1614. params.ID = options.ID
  1615. }
  1616. if options != nil {
  1617. // Ordered indicates if data is allowed to be delivered out of order. The
  1618. // default value of true, guarantees that data will be delivered in order.
  1619. // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #9)
  1620. if options.Ordered != nil {
  1621. params.Ordered = *options.Ordered
  1622. }
  1623. // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #7)
  1624. if options.MaxPacketLifeTime != nil {
  1625. params.MaxPacketLifeTime = options.MaxPacketLifeTime
  1626. }
  1627. // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #8)
  1628. if options.MaxRetransmits != nil {
  1629. params.MaxRetransmits = options.MaxRetransmits
  1630. }
  1631. // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #10)
  1632. if options.Protocol != nil {
  1633. params.Protocol = *options.Protocol
  1634. }
  1635. // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #11)
  1636. if len(params.Protocol) > 65535 {
  1637. return nil, &rtcerr.TypeError{Err: ErrProtocolTooLarge}
  1638. }
  1639. // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #12)
  1640. if options.Negotiated != nil {
  1641. params.Negotiated = *options.Negotiated
  1642. }
  1643. }
  1644. d, err := pc.api.newDataChannel(params, pc.log)
  1645. if err != nil {
  1646. return nil, err
  1647. }
  1648. // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #16)
  1649. if d.maxPacketLifeTime != nil && d.maxRetransmits != nil {
  1650. return nil, &rtcerr.TypeError{Err: ErrRetransmitsOrPacketLifeTime}
  1651. }
  1652. pc.sctpTransport.lock.Lock()
  1653. pc.sctpTransport.dataChannels = append(pc.sctpTransport.dataChannels, d)
  1654. pc.sctpTransport.dataChannelsRequested++
  1655. pc.sctpTransport.lock.Unlock()
  1656. // If SCTP already connected open all the channels
  1657. if pc.sctpTransport.State() == SCTPTransportStateConnected {
  1658. if err = d.open(pc.sctpTransport); err != nil {
  1659. return nil, err
  1660. }
  1661. }
  1662. pc.mu.Lock()
  1663. pc.onNegotiationNeeded()
  1664. pc.mu.Unlock()
  1665. return d, nil
  1666. }
  1667. // SetIdentityProvider is used to configure an identity provider to generate identity assertions
  1668. func (pc *PeerConnection) SetIdentityProvider(provider string) error {
  1669. return errPeerConnSetIdentityProviderNotImplemented
  1670. }
  1671. // WriteRTCP sends a user provided RTCP packet to the connected peer. If no peer is connected the
  1672. // packet is discarded. It also runs any configured interceptors.
  1673. func (pc *PeerConnection) WriteRTCP(pkts []rtcp.Packet) error {
  1674. _, err := pc.interceptorRTCPWriter.Write(pkts, make(interceptor.Attributes))
  1675. return err
  1676. }
  1677. func (pc *PeerConnection) writeRTCP(pkts []rtcp.Packet, _ interceptor.Attributes) (int, error) {
  1678. return pc.dtlsTransport.WriteRTCP(pkts)
  1679. }
  1680. // Close ends the PeerConnection
  1681. func (pc *PeerConnection) Close() error {
  1682. // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #1)
  1683. // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #2)
  1684. if pc.isClosed.swap(true) {
  1685. return nil
  1686. }
  1687. // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #3)
  1688. pc.signalingState.Set(SignalingStateClosed)
  1689. // Try closing everything and collect the errors
  1690. // Shutdown strategy:
  1691. // 1. All Conn close by closing their underlying Conn.
  1692. // 2. A Mux stops this chain. It won't close the underlying
  1693. // Conn if one of the endpoints is closed down. To
  1694. // continue the chain the Mux has to be closed.
  1695. closeErrs := make([]error, 4)
  1696. closeErrs = append(closeErrs, pc.api.interceptor.Close())
  1697. // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #4)
  1698. pc.mu.Lock()
  1699. for _, t := range pc.rtpTransceivers {
  1700. if !t.stopped {
  1701. closeErrs = append(closeErrs, t.Stop())
  1702. }
  1703. }
  1704. pc.mu.Unlock()
  1705. // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #5)
  1706. pc.sctpTransport.lock.Lock()
  1707. for _, d := range pc.sctpTransport.dataChannels {
  1708. d.setReadyState(DataChannelStateClosed)
  1709. }
  1710. pc.sctpTransport.lock.Unlock()
  1711. // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #6)
  1712. if pc.sctpTransport != nil {
  1713. closeErrs = append(closeErrs, pc.sctpTransport.Stop())
  1714. }
  1715. // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #7)
  1716. closeErrs = append(closeErrs, pc.dtlsTransport.Stop())
  1717. // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #8, #9, #10)
  1718. if pc.iceTransport != nil {
  1719. closeErrs = append(closeErrs, pc.iceTransport.Stop())
  1720. }
  1721. // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #11)
  1722. pc.updateConnectionState(pc.ICEConnectionState(), pc.dtlsTransport.State())
  1723. return util.FlattenErrs(closeErrs)
  1724. }
  1725. // addRTPTransceiver appends t into rtpTransceivers
  1726. // and fires onNegotiationNeeded;
  1727. // caller of this method should hold `pc.mu` lock
  1728. func (pc *PeerConnection) addRTPTransceiver(t *RTPTransceiver) {
  1729. pc.rtpTransceivers = append(pc.rtpTransceivers, t)
  1730. pc.onNegotiationNeeded()
  1731. }
  1732. // CurrentLocalDescription represents the local description that was
  1733. // successfully negotiated the last time the PeerConnection transitioned
  1734. // into the stable state plus any local candidates that have been generated
  1735. // by the ICEAgent since the offer or answer was created.
  1736. func (pc *PeerConnection) CurrentLocalDescription() *SessionDescription {
  1737. pc.mu.Lock()
  1738. localDescription := pc.currentLocalDescription
  1739. iceGather := pc.iceGatherer
  1740. iceGatheringState := pc.ICEGatheringState()
  1741. pc.mu.Unlock()
  1742. return populateLocalCandidates(localDescription, iceGather, iceGatheringState)
  1743. }
  1744. // PendingLocalDescription represents a local description that is in the
  1745. // process of being negotiated plus any local candidates that have been
  1746. // generated by the ICEAgent since the offer or answer was created. If the
  1747. // PeerConnection is in the stable state, the value is null.
  1748. func (pc *PeerConnection) PendingLocalDescription() *SessionDescription {
  1749. pc.mu.Lock()
  1750. localDescription := pc.pendingLocalDescription
  1751. iceGather := pc.iceGatherer
  1752. iceGatheringState := pc.ICEGatheringState()
  1753. pc.mu.Unlock()
  1754. return populateLocalCandidates(localDescription, iceGather, iceGatheringState)
  1755. }
  1756. // CurrentRemoteDescription represents the last remote description that was
  1757. // successfully negotiated the last time the PeerConnection transitioned
  1758. // into the stable state plus any remote candidates that have been supplied
  1759. // via AddICECandidate() since the offer or answer was created.
  1760. func (pc *PeerConnection) CurrentRemoteDescription() *SessionDescription {
  1761. pc.mu.RLock()
  1762. defer pc.mu.RUnlock()
  1763. return pc.currentRemoteDescription
  1764. }
  1765. // PendingRemoteDescription represents a remote description that is in the
  1766. // process of being negotiated, complete with any remote candidates that
  1767. // have been supplied via AddICECandidate() since the offer or answer was
  1768. // created. If the PeerConnection is in the stable state, the value is
  1769. // null.
  1770. func (pc *PeerConnection) PendingRemoteDescription() *SessionDescription {
  1771. pc.mu.RLock()
  1772. defer pc.mu.RUnlock()
  1773. return pc.pendingRemoteDescription
  1774. }
  1775. // SignalingState attribute returns the signaling state of the
  1776. // PeerConnection instance.
  1777. func (pc *PeerConnection) SignalingState() SignalingState {
  1778. return pc.signalingState.Get()
  1779. }
  1780. // ICEGatheringState attribute returns the ICE gathering state of the
  1781. // PeerConnection instance.
  1782. func (pc *PeerConnection) ICEGatheringState() ICEGatheringState {
  1783. if pc.iceGatherer == nil {
  1784. return ICEGatheringStateNew
  1785. }
  1786. switch pc.iceGatherer.State() {
  1787. case ICEGathererStateNew:
  1788. return ICEGatheringStateNew
  1789. case ICEGathererStateGathering:
  1790. return ICEGatheringStateGathering
  1791. default:
  1792. return ICEGatheringStateComplete
  1793. }
  1794. }
  1795. // ConnectionState attribute returns the connection state of the
  1796. // PeerConnection instance.
  1797. func (pc *PeerConnection) ConnectionState() PeerConnectionState {
  1798. if state, ok := pc.connectionState.Load().(PeerConnectionState); ok {
  1799. return state
  1800. }
  1801. return PeerConnectionState(0)
  1802. }
  1803. // GetStats return data providing statistics about the overall connection
  1804. func (pc *PeerConnection) GetStats() StatsReport {
  1805. var (
  1806. dataChannelsAccepted uint32
  1807. dataChannelsClosed uint32
  1808. dataChannelsOpened uint32
  1809. dataChannelsRequested uint32
  1810. )
  1811. statsCollector := newStatsReportCollector()
  1812. statsCollector.Collecting()
  1813. pc.mu.Lock()
  1814. if pc.iceGatherer != nil {
  1815. pc.iceGatherer.collectStats(statsCollector)
  1816. }
  1817. if pc.iceTransport != nil {
  1818. pc.iceTransport.collectStats(statsCollector)
  1819. }
  1820. pc.sctpTransport.lock.Lock()
  1821. dataChannels := append([]*DataChannel{}, pc.sctpTransport.dataChannels...)
  1822. dataChannelsAccepted = pc.sctpTransport.dataChannelsAccepted
  1823. dataChannelsOpened = pc.sctpTransport.dataChannelsOpened
  1824. dataChannelsRequested = pc.sctpTransport.dataChannelsRequested
  1825. pc.sctpTransport.lock.Unlock()
  1826. for _, d := range dataChannels {
  1827. state := d.ReadyState()
  1828. if state != DataChannelStateConnecting && state != DataChannelStateOpen {
  1829. dataChannelsClosed++
  1830. }
  1831. d.collectStats(statsCollector)
  1832. }
  1833. pc.sctpTransport.collectStats(statsCollector)
  1834. stats := PeerConnectionStats{
  1835. Timestamp: statsTimestampNow(),
  1836. Type: StatsTypePeerConnection,
  1837. ID: pc.statsID,
  1838. DataChannelsAccepted: dataChannelsAccepted,
  1839. DataChannelsClosed: dataChannelsClosed,
  1840. DataChannelsOpened: dataChannelsOpened,
  1841. DataChannelsRequested: dataChannelsRequested,
  1842. }
  1843. statsCollector.Collect(stats.ID, stats)
  1844. certificates := pc.configuration.Certificates
  1845. for _, certificate := range certificates {
  1846. if err := certificate.collectStats(statsCollector); err != nil {
  1847. continue
  1848. }
  1849. }
  1850. pc.mu.Unlock()
  1851. pc.api.mediaEngine.collectStats(statsCollector)
  1852. return statsCollector.Ready()
  1853. }
  1854. // Start all transports. PeerConnection now has enough state
  1855. func (pc *PeerConnection) startTransports(iceRole ICERole, dtlsRole DTLSRole, remoteUfrag, remotePwd, fingerprint, fingerprintHash string) {
  1856. // Start the ice transport
  1857. err := pc.iceTransport.Start(
  1858. pc.iceGatherer,
  1859. ICEParameters{
  1860. UsernameFragment: remoteUfrag,
  1861. Password: remotePwd,
  1862. ICELite: false,
  1863. },
  1864. &iceRole,
  1865. )
  1866. if err != nil {
  1867. pc.log.Warnf("Failed to start manager: %s", err)
  1868. return
  1869. }
  1870. // Start the dtls transport
  1871. err = pc.dtlsTransport.Start(DTLSParameters{
  1872. Role: dtlsRole,
  1873. Fingerprints: []DTLSFingerprint{{Algorithm: fingerprintHash, Value: fingerprint}},
  1874. })
  1875. pc.updateConnectionState(pc.ICEConnectionState(), pc.dtlsTransport.State())
  1876. if err != nil {
  1877. pc.log.Warnf("Failed to start manager: %s", err)
  1878. return
  1879. }
  1880. }
  1881. // nolint: gocognit
  1882. func (pc *PeerConnection) startRTP(isRenegotiation bool, remoteDesc *SessionDescription, currentTransceivers []*RTPTransceiver) {
  1883. if !isRenegotiation {
  1884. pc.undeclaredMediaProcessor()
  1885. }
  1886. pc.startRTPReceivers(remoteDesc, currentTransceivers)
  1887. if haveApplicationMediaSection(remoteDesc.parsed) {
  1888. pc.startSCTP()
  1889. }
  1890. }
  1891. // generateUnmatchedSDP generates an SDP that doesn't take remote state into account
  1892. // This is used for the initial call for CreateOffer
  1893. func (pc *PeerConnection) generateUnmatchedSDP(transceivers []*RTPTransceiver, useIdentity bool) (*sdp.SessionDescription, error) {
  1894. d, err := sdp.NewJSEPSessionDescription(useIdentity)
  1895. if err != nil {
  1896. return nil, err
  1897. }
  1898. iceParams, err := pc.iceGatherer.GetLocalParameters()
  1899. if err != nil {
  1900. return nil, err
  1901. }
  1902. candidates, err := pc.iceGatherer.GetLocalCandidates()
  1903. if err != nil {
  1904. return nil, err
  1905. }
  1906. isPlanB := pc.configuration.SDPSemantics == SDPSemanticsPlanB
  1907. mediaSections := []mediaSection{}
  1908. // Needed for pc.sctpTransport.dataChannelsRequested
  1909. pc.sctpTransport.lock.Lock()
  1910. defer pc.sctpTransport.lock.Unlock()
  1911. if isPlanB {
  1912. video := make([]*RTPTransceiver, 0)
  1913. audio := make([]*RTPTransceiver, 0)
  1914. for _, t := range transceivers {
  1915. if t.kind == RTPCodecTypeVideo {
  1916. video = append(video, t)
  1917. } else if t.kind == RTPCodecTypeAudio {
  1918. audio = append(audio, t)
  1919. }
  1920. if sender := t.Sender(); sender != nil {
  1921. sender.setNegotiated()
  1922. }
  1923. }
  1924. if len(video) > 0 {
  1925. mediaSections = append(mediaSections, mediaSection{id: "video", transceivers: video})
  1926. }
  1927. if len(audio) > 0 {
  1928. mediaSections = append(mediaSections, mediaSection{id: "audio", transceivers: audio})
  1929. }
  1930. if pc.sctpTransport.dataChannelsRequested != 0 {
  1931. mediaSections = append(mediaSections, mediaSection{id: "data", data: true})
  1932. }
  1933. } else {
  1934. for _, t := range transceivers {
  1935. if sender := t.Sender(); sender != nil {
  1936. sender.setNegotiated()
  1937. }
  1938. mediaSections = append(mediaSections, mediaSection{id: t.Mid(), transceivers: []*RTPTransceiver{t}})
  1939. }
  1940. if pc.sctpTransport.dataChannelsRequested != 0 {
  1941. mediaSections = append(mediaSections, mediaSection{id: strconv.Itoa(len(mediaSections)), data: true})
  1942. }
  1943. }
  1944. dtlsFingerprints, err := pc.configuration.Certificates[0].GetFingerprints()
  1945. if err != nil {
  1946. return nil, err
  1947. }
  1948. return populateSDP(d, isPlanB, dtlsFingerprints, pc.api.settingEngine.sdpMediaLevelFingerprints, pc.api.settingEngine.candidates.ICELite, true, pc.api.mediaEngine, connectionRoleFromDtlsRole(defaultDtlsRoleOffer), candidates, iceParams, mediaSections, pc.ICEGatheringState())
  1949. }
  1950. // generateMatchedSDP generates a SDP and takes the remote state into account
  1951. // this is used everytime we have a RemoteDescription
  1952. // nolint: gocyclo
  1953. func (pc *PeerConnection) generateMatchedSDP(transceivers []*RTPTransceiver, useIdentity bool, includeUnmatched bool, connectionRole sdp.ConnectionRole) (*sdp.SessionDescription, error) { //nolint:gocognit
  1954. d, err := sdp.NewJSEPSessionDescription(useIdentity)
  1955. if err != nil {
  1956. return nil, err
  1957. }
  1958. iceParams, err := pc.iceGatherer.GetLocalParameters()
  1959. if err != nil {
  1960. return nil, err
  1961. }
  1962. candidates, err := pc.iceGatherer.GetLocalCandidates()
  1963. if err != nil {
  1964. return nil, err
  1965. }
  1966. var t *RTPTransceiver
  1967. remoteDescription := pc.currentRemoteDescription
  1968. if pc.pendingRemoteDescription != nil {
  1969. remoteDescription = pc.pendingRemoteDescription
  1970. }
  1971. isExtmapAllowMixed := isExtMapAllowMixedSet(remoteDescription.parsed)
  1972. localTransceivers := append([]*RTPTransceiver{}, transceivers...)
  1973. detectedPlanB := descriptionIsPlanB(remoteDescription, pc.log)
  1974. if pc.configuration.SDPSemantics != SDPSemanticsUnifiedPlan {
  1975. detectedPlanB = descriptionPossiblyPlanB(remoteDescription)
  1976. }
  1977. mediaSections := []mediaSection{}
  1978. alreadyHaveApplicationMediaSection := false
  1979. for _, media := range remoteDescription.parsed.MediaDescriptions {
  1980. midValue := getMidValue(media)
  1981. if midValue == "" {
  1982. return nil, errPeerConnRemoteDescriptionWithoutMidValue
  1983. }
  1984. if media.MediaName.Media == mediaSectionApplication {
  1985. mediaSections = append(mediaSections, mediaSection{id: midValue, data: true})
  1986. alreadyHaveApplicationMediaSection = true
  1987. continue
  1988. }
  1989. kind := NewRTPCodecType(media.MediaName.Media)
  1990. direction := getPeerDirection(media)
  1991. if kind == 0 || direction == RTPTransceiverDirection(Unknown) {
  1992. continue
  1993. }
  1994. sdpSemantics := pc.configuration.SDPSemantics
  1995. switch {
  1996. case sdpSemantics == SDPSemanticsPlanB || sdpSemantics == SDPSemanticsUnifiedPlanWithFallback && detectedPlanB:
  1997. if !detectedPlanB {
  1998. return nil, &rtcerr.TypeError{Err: fmt.Errorf("%w: Expected PlanB, but RemoteDescription is UnifiedPlan", ErrIncorrectSDPSemantics)}
  1999. }
  2000. // If we're responding to a plan-b offer, then we should try to fill up this
  2001. // media entry with all matching local transceivers
  2002. mediaTransceivers := []*RTPTransceiver{}
  2003. for {
  2004. // keep going until we can't get any more
  2005. t, localTransceivers = satisfyTypeAndDirection(kind, direction, localTransceivers)
  2006. if t == nil {
  2007. if len(mediaTransceivers) == 0 {
  2008. t = &RTPTransceiver{kind: kind, api: pc.api, codecs: pc.api.mediaEngine.getCodecsByKind(kind)}
  2009. t.setDirection(RTPTransceiverDirectionInactive)
  2010. mediaTransceivers = append(mediaTransceivers, t)
  2011. }
  2012. break
  2013. }
  2014. if sender := t.Sender(); sender != nil {
  2015. sender.setNegotiated()
  2016. }
  2017. mediaTransceivers = append(mediaTransceivers, t)
  2018. }
  2019. mediaSections = append(mediaSections, mediaSection{id: midValue, transceivers: mediaTransceivers})
  2020. case sdpSemantics == SDPSemanticsUnifiedPlan || sdpSemantics == SDPSemanticsUnifiedPlanWithFallback:
  2021. if detectedPlanB {
  2022. return nil, &rtcerr.TypeError{Err: fmt.Errorf("%w: Expected UnifiedPlan, but RemoteDescription is PlanB", ErrIncorrectSDPSemantics)}
  2023. }
  2024. t, localTransceivers = findByMid(midValue, localTransceivers)
  2025. if t == nil {
  2026. return nil, fmt.Errorf("%w: %q", errPeerConnTranscieverMidNil, midValue)
  2027. }
  2028. if sender := t.Sender(); sender != nil {
  2029. sender.setNegotiated()
  2030. }
  2031. mediaTransceivers := []*RTPTransceiver{t}
  2032. mediaSections = append(mediaSections, mediaSection{id: midValue, transceivers: mediaTransceivers, ridMap: getRids(media)})
  2033. }
  2034. }
  2035. // If we are offering also include unmatched local transceivers
  2036. if includeUnmatched {
  2037. if !detectedPlanB {
  2038. for _, t := range localTransceivers {
  2039. if sender := t.Sender(); sender != nil {
  2040. sender.setNegotiated()
  2041. }
  2042. mediaSections = append(mediaSections, mediaSection{id: t.Mid(), transceivers: []*RTPTransceiver{t}})
  2043. }
  2044. }
  2045. if pc.sctpTransport.dataChannelsRequested != 0 && !alreadyHaveApplicationMediaSection {
  2046. if detectedPlanB {
  2047. mediaSections = append(mediaSections, mediaSection{id: "data", data: true})
  2048. } else {
  2049. mediaSections = append(mediaSections, mediaSection{id: strconv.Itoa(len(mediaSections)), data: true})
  2050. }
  2051. }
  2052. }
  2053. if pc.configuration.SDPSemantics == SDPSemanticsUnifiedPlanWithFallback && detectedPlanB {
  2054. pc.log.Info("Plan-B Offer detected; responding with Plan-B Answer")
  2055. }
  2056. dtlsFingerprints, err := pc.configuration.Certificates[0].GetFingerprints()
  2057. if err != nil {
  2058. return nil, err
  2059. }
  2060. return populateSDP(d, detectedPlanB, dtlsFingerprints, pc.api.settingEngine.sdpMediaLevelFingerprints, pc.api.settingEngine.candidates.ICELite, isExtmapAllowMixed, pc.api.mediaEngine, connectionRole, candidates, iceParams, mediaSections, pc.ICEGatheringState())
  2061. }
  2062. func (pc *PeerConnection) setGatherCompleteHandler(handler func()) {
  2063. pc.iceGatherer.onGatheringCompleteHandler.Store(handler)
  2064. }
  2065. // SCTP returns the SCTPTransport for this PeerConnection
  2066. //
  2067. // The SCTP transport over which SCTP data is sent and received. If SCTP has not been negotiated, the value is nil.
  2068. // https://www.w3.org/TR/webrtc/#attributes-15
  2069. func (pc *PeerConnection) SCTP() *SCTPTransport {
  2070. return pc.sctpTransport
  2071. }