main.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. //go:build !js
  4. // +build !js
  5. // broadcast demonstrates how to broadcast a video to many peers, while only requiring the broadcaster to upload once.
  6. package main
  7. import (
  8. "errors"
  9. "fmt"
  10. "io"
  11. "github.com/pion/interceptor"
  12. "github.com/pion/interceptor/pkg/intervalpli"
  13. "github.com/pion/webrtc/v3"
  14. "github.com/pion/webrtc/v3/examples/internal/signal"
  15. )
  16. func main() { // nolint:gocognit
  17. sdpChan := signal.HTTPSDPServer()
  18. // Everything below is the Pion WebRTC API, thanks for using it ❤️.
  19. offer := webrtc.SessionDescription{}
  20. signal.Decode(<-sdpChan, &offer)
  21. fmt.Println("")
  22. peerConnectionConfig := webrtc.Configuration{
  23. ICEServers: []webrtc.ICEServer{
  24. {
  25. URLs: []string{"stun:stun.l.google.com:19302"},
  26. },
  27. },
  28. }
  29. m := &webrtc.MediaEngine{}
  30. if err := m.RegisterDefaultCodecs(); err != nil {
  31. panic(err)
  32. }
  33. // Create a InterceptorRegistry. This is the user configurable RTP/RTCP Pipeline.
  34. // This provides NACKs, RTCP Reports and other features. If you use `webrtc.NewPeerConnection`
  35. // this is enabled by default. If you are manually managing You MUST create a InterceptorRegistry
  36. // for each PeerConnection.
  37. i := &interceptor.Registry{}
  38. // Use the default set of Interceptors
  39. if err := webrtc.RegisterDefaultInterceptors(m, i); err != nil {
  40. panic(err)
  41. }
  42. // Register a intervalpli factory
  43. // This interceptor sends a PLI every 3 seconds. A PLI causes a video keyframe to be generated by the sender.
  44. // This makes our video seekable and more error resilent, but at a cost of lower picture quality and higher bitrates
  45. // A real world application should process incoming RTCP packets from viewers and forward them to senders
  46. intervalPliFactory, err := intervalpli.NewReceiverInterceptor()
  47. if err != nil {
  48. panic(err)
  49. }
  50. i.Add(intervalPliFactory)
  51. // Create a new RTCPeerConnection
  52. peerConnection, err := webrtc.NewAPI(webrtc.WithMediaEngine(m), webrtc.WithInterceptorRegistry(i)).NewPeerConnection(peerConnectionConfig)
  53. if err != nil {
  54. panic(err)
  55. }
  56. defer func() {
  57. if cErr := peerConnection.Close(); cErr != nil {
  58. fmt.Printf("cannot close peerConnection: %v\n", cErr)
  59. }
  60. }()
  61. // Allow us to receive 1 video track
  62. if _, err = peerConnection.AddTransceiverFromKind(webrtc.RTPCodecTypeVideo); err != nil {
  63. panic(err)
  64. }
  65. localTrackChan := make(chan *webrtc.TrackLocalStaticRTP)
  66. // Set a handler for when a new remote track starts, this just distributes all our packets
  67. // to connected peers
  68. peerConnection.OnTrack(func(remoteTrack *webrtc.TrackRemote, receiver *webrtc.RTPReceiver) {
  69. // Create a local track, all our SFU clients will be fed via this track
  70. localTrack, newTrackErr := webrtc.NewTrackLocalStaticRTP(remoteTrack.Codec().RTPCodecCapability, "video", "pion")
  71. if newTrackErr != nil {
  72. panic(newTrackErr)
  73. }
  74. localTrackChan <- localTrack
  75. rtpBuf := make([]byte, 1400)
  76. for {
  77. i, _, readErr := remoteTrack.Read(rtpBuf)
  78. if readErr != nil {
  79. panic(readErr)
  80. }
  81. // ErrClosedPipe means we don't have any subscribers, this is ok if no peers have connected yet
  82. if _, err = localTrack.Write(rtpBuf[:i]); err != nil && !errors.Is(err, io.ErrClosedPipe) {
  83. panic(err)
  84. }
  85. }
  86. })
  87. // Set the remote SessionDescription
  88. err = peerConnection.SetRemoteDescription(offer)
  89. if err != nil {
  90. panic(err)
  91. }
  92. // Create answer
  93. answer, err := peerConnection.CreateAnswer(nil)
  94. if err != nil {
  95. panic(err)
  96. }
  97. // Create channel that is blocked until ICE Gathering is complete
  98. gatherComplete := webrtc.GatheringCompletePromise(peerConnection)
  99. // Sets the LocalDescription, and starts our UDP listeners
  100. err = peerConnection.SetLocalDescription(answer)
  101. if err != nil {
  102. panic(err)
  103. }
  104. // Block until ICE Gathering is complete, disabling trickle ICE
  105. // we do this because we only can exchange one signaling message
  106. // in a production application you should exchange ICE Candidates via OnICECandidate
  107. <-gatherComplete
  108. // Get the LocalDescription and take it to base64 so we can paste in browser
  109. fmt.Println(signal.Encode(*peerConnection.LocalDescription()))
  110. localTrack := <-localTrackChan
  111. for {
  112. fmt.Println("")
  113. fmt.Println("Curl an base64 SDP to start sendonly peer connection")
  114. recvOnlyOffer := webrtc.SessionDescription{}
  115. signal.Decode(<-sdpChan, &recvOnlyOffer)
  116. // Create a new PeerConnection
  117. peerConnection, err := webrtc.NewPeerConnection(peerConnectionConfig)
  118. if err != nil {
  119. panic(err)
  120. }
  121. rtpSender, err := peerConnection.AddTrack(localTrack)
  122. if err != nil {
  123. panic(err)
  124. }
  125. // Read incoming RTCP packets
  126. // Before these packets are returned they are processed by interceptors. For things
  127. // like NACK this needs to be called.
  128. go func() {
  129. rtcpBuf := make([]byte, 1500)
  130. for {
  131. if _, _, rtcpErr := rtpSender.Read(rtcpBuf); rtcpErr != nil {
  132. return
  133. }
  134. }
  135. }()
  136. // Set the remote SessionDescription
  137. err = peerConnection.SetRemoteDescription(recvOnlyOffer)
  138. if err != nil {
  139. panic(err)
  140. }
  141. // Create answer
  142. answer, err := peerConnection.CreateAnswer(nil)
  143. if err != nil {
  144. panic(err)
  145. }
  146. // Create channel that is blocked until ICE Gathering is complete
  147. gatherComplete = webrtc.GatheringCompletePromise(peerConnection)
  148. // Sets the LocalDescription, and starts our UDP listeners
  149. err = peerConnection.SetLocalDescription(answer)
  150. if err != nil {
  151. panic(err)
  152. }
  153. // Block until ICE Gathering is complete, disabling trickle ICE
  154. // we do this because we only can exchange one signaling message
  155. // in a production application you should exchange ICE Candidates via OnICECandidate
  156. <-gatherComplete
  157. // Get the LocalDescription and take it to base64 so we can paste in browser
  158. fmt.Println(signal.Encode(*peerConnection.LocalDescription()))
  159. }
  160. }