main.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. //go:build !js
  4. // +build !js
  5. // simulcast demonstrates of how to handle incoming track with multiple simulcast rtp streams and show all them back.
  6. package main
  7. import (
  8. "errors"
  9. "fmt"
  10. "io"
  11. "os"
  12. "time"
  13. "github.com/pion/interceptor"
  14. "github.com/pion/rtcp"
  15. "github.com/pion/webrtc/v3"
  16. "github.com/pion/webrtc/v3/examples/internal/signal"
  17. )
  18. // nolint:gocognit
  19. func main() {
  20. // Everything below is the Pion WebRTC API! Thanks for using it ❤️.
  21. // Prepare the configuration
  22. config := webrtc.Configuration{
  23. ICEServers: []webrtc.ICEServer{
  24. {
  25. URLs: []string{"stun:stun.l.google.com:19302"},
  26. },
  27. },
  28. }
  29. // Enable Extension Headers needed for Simulcast
  30. m := &webrtc.MediaEngine{}
  31. if err := m.RegisterDefaultCodecs(); err != nil {
  32. panic(err)
  33. }
  34. for _, extension := range []string{
  35. "urn:ietf:params:rtp-hdrext:sdes:mid",
  36. "urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id",
  37. "urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id",
  38. } {
  39. if err := m.RegisterHeaderExtension(webrtc.RTPHeaderExtensionCapability{URI: extension}, webrtc.RTPCodecTypeVideo); err != nil {
  40. panic(err)
  41. }
  42. }
  43. // Create a InterceptorRegistry. This is the user configurable RTP/RTCP Pipeline.
  44. // This provides NACKs, RTCP Reports and other features. If you use `webrtc.NewPeerConnection`
  45. // this is enabled by default. If you are manually managing You MUST create a InterceptorRegistry
  46. // for each PeerConnection.
  47. i := &interceptor.Registry{}
  48. // Use the default set of Interceptors
  49. if err := webrtc.RegisterDefaultInterceptors(m, i); err != nil {
  50. panic(err)
  51. }
  52. // Create a new RTCPeerConnection
  53. peerConnection, err := webrtc.NewAPI(webrtc.WithMediaEngine(m), webrtc.WithInterceptorRegistry(i)).NewPeerConnection(config)
  54. if err != nil {
  55. panic(err)
  56. }
  57. defer func() {
  58. if cErr := peerConnection.Close(); cErr != nil {
  59. fmt.Printf("cannot close peerConnection: %v\n", cErr)
  60. }
  61. }()
  62. outputTracks := map[string]*webrtc.TrackLocalStaticRTP{}
  63. // Create Track that we send video back to browser on
  64. outputTrack, err := webrtc.NewTrackLocalStaticRTP(webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeVP8}, "video_q", "pion_q")
  65. if err != nil {
  66. panic(err)
  67. }
  68. outputTracks["q"] = outputTrack
  69. outputTrack, err = webrtc.NewTrackLocalStaticRTP(webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeVP8}, "video_h", "pion_h")
  70. if err != nil {
  71. panic(err)
  72. }
  73. outputTracks["h"] = outputTrack
  74. outputTrack, err = webrtc.NewTrackLocalStaticRTP(webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeVP8}, "video_f", "pion_f")
  75. if err != nil {
  76. panic(err)
  77. }
  78. outputTracks["f"] = outputTrack
  79. // Add this newly created track to the PeerConnection
  80. if _, err = peerConnection.AddTrack(outputTracks["q"]); err != nil {
  81. panic(err)
  82. }
  83. if _, err = peerConnection.AddTrack(outputTracks["h"]); err != nil {
  84. panic(err)
  85. }
  86. if _, err = peerConnection.AddTrack(outputTracks["f"]); err != nil {
  87. panic(err)
  88. }
  89. // Read incoming RTCP packets
  90. // Before these packets are returned they are processed by interceptors. For things
  91. // like NACK this needs to be called.
  92. processRTCP := func(rtpSender *webrtc.RTPSender) {
  93. rtcpBuf := make([]byte, 1500)
  94. for {
  95. if _, _, rtcpErr := rtpSender.Read(rtcpBuf); rtcpErr != nil {
  96. return
  97. }
  98. }
  99. }
  100. for _, rtpSender := range peerConnection.GetSenders() {
  101. go processRTCP(rtpSender)
  102. }
  103. // Wait for the offer to be pasted
  104. offer := webrtc.SessionDescription{}
  105. signal.Decode(signal.MustReadStdin(), &offer)
  106. if err = peerConnection.SetRemoteDescription(offer); err != nil {
  107. panic(err)
  108. }
  109. // Set a handler for when a new remote track starts
  110. peerConnection.OnTrack(func(track *webrtc.TrackRemote, receiver *webrtc.RTPReceiver) {
  111. fmt.Println("Track has started")
  112. // Start reading from all the streams and sending them to the related output track
  113. rid := track.RID()
  114. go func() {
  115. ticker := time.NewTicker(3 * time.Second)
  116. for range ticker.C {
  117. fmt.Printf("Sending pli for stream with rid: %q, ssrc: %d\n", track.RID(), track.SSRC())
  118. if writeErr := peerConnection.WriteRTCP([]rtcp.Packet{&rtcp.PictureLossIndication{MediaSSRC: uint32(track.SSRC())}}); writeErr != nil {
  119. fmt.Println(writeErr)
  120. }
  121. }
  122. }()
  123. for {
  124. // Read RTP packets being sent to Pion
  125. packet, _, readErr := track.ReadRTP()
  126. if readErr != nil {
  127. panic(readErr)
  128. }
  129. if writeErr := outputTracks[rid].WriteRTP(packet); writeErr != nil && !errors.Is(writeErr, io.ErrClosedPipe) {
  130. panic(writeErr)
  131. }
  132. }
  133. })
  134. // Set the handler for Peer connection state
  135. // This will notify you when the peer has connected/disconnected
  136. peerConnection.OnConnectionStateChange(func(s webrtc.PeerConnectionState) {
  137. fmt.Printf("Peer Connection State has changed: %s\n", s.String())
  138. if s == webrtc.PeerConnectionStateFailed {
  139. // Wait until PeerConnection has had no network activity for 30 seconds or another failure. It may be reconnected using an ICE Restart.
  140. // Use webrtc.PeerConnectionStateDisconnected if you are interested in detecting faster timeout.
  141. // Note that the PeerConnection may come back from PeerConnectionStateDisconnected.
  142. fmt.Println("Peer Connection has gone to failed exiting")
  143. os.Exit(0)
  144. }
  145. })
  146. // Create an answer
  147. answer, err := peerConnection.CreateAnswer(nil)
  148. if err != nil {
  149. panic(err)
  150. }
  151. // Create channel that is blocked until ICE Gathering is complete
  152. gatherComplete := webrtc.GatheringCompletePromise(peerConnection)
  153. // Sets the LocalDescription, and starts our UDP listeners
  154. err = peerConnection.SetLocalDescription(answer)
  155. if err != nil {
  156. panic(err)
  157. }
  158. // Block until ICE Gathering is complete, disabling trickle ICE
  159. // we do this because we only can exchange one signaling message
  160. // in a production application you should exchange ICE Candidates via OnICECandidate
  161. <-gatherComplete
  162. // Output the answer in base64 so we can paste it in browser
  163. fmt.Println(signal.Encode(*peerConnection.LocalDescription()))
  164. // Block forever
  165. select {}
  166. }