main.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. //go:build !js
  4. // +build !js
  5. // reflect demonstrates how with one PeerConnection you can send video to Pion and have the packets sent back
  6. package main
  7. import (
  8. "fmt"
  9. "os"
  10. "github.com/pion/interceptor"
  11. "github.com/pion/interceptor/pkg/intervalpli"
  12. "github.com/pion/webrtc/v3"
  13. "github.com/pion/webrtc/v3/examples/internal/signal"
  14. )
  15. // nolint:gocognit
  16. func main() {
  17. // Everything below is the Pion WebRTC API! Thanks for using it ❤️.
  18. // Create a MediaEngine object to configure the supported codec
  19. m := &webrtc.MediaEngine{}
  20. // Setup the codecs you want to use.
  21. // We'll use a VP8 and Opus but you can also define your own
  22. if err := m.RegisterCodec(webrtc.RTPCodecParameters{
  23. RTPCodecCapability: webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeVP8, ClockRate: 90000, Channels: 0, SDPFmtpLine: "", RTCPFeedback: nil},
  24. PayloadType: 96,
  25. }, webrtc.RTPCodecTypeVideo); err != nil {
  26. panic(err)
  27. }
  28. // Create a InterceptorRegistry. This is the user configurable RTP/RTCP Pipeline.
  29. // This provides NACKs, RTCP Reports and other features. If you use `webrtc.NewPeerConnection`
  30. // this is enabled by default. If you are manually managing You MUST create a InterceptorRegistry
  31. // for each PeerConnection.
  32. i := &interceptor.Registry{}
  33. // Use the default set of Interceptors
  34. if err := webrtc.RegisterDefaultInterceptors(m, i); err != nil {
  35. panic(err)
  36. }
  37. // Register a intervalpli factory
  38. // This interceptor sends a PLI every 3 seconds. A PLI causes a video keyframe to be generated by the sender.
  39. // This makes our video seekable and more error resilent, but at a cost of lower picture quality and higher bitrates
  40. // A real world application should process incoming RTCP packets from viewers and forward them to senders
  41. intervalPliFactory, err := intervalpli.NewReceiverInterceptor()
  42. if err != nil {
  43. panic(err)
  44. }
  45. i.Add(intervalPliFactory)
  46. // Create the API object with the MediaEngine
  47. api := webrtc.NewAPI(webrtc.WithMediaEngine(m), webrtc.WithInterceptorRegistry(i))
  48. // Prepare the configuration
  49. config := webrtc.Configuration{
  50. ICEServers: []webrtc.ICEServer{
  51. {
  52. URLs: []string{"stun:stun.l.google.com:19302"},
  53. },
  54. },
  55. }
  56. // Create a new RTCPeerConnection
  57. peerConnection, err := api.NewPeerConnection(config)
  58. if err != nil {
  59. panic(err)
  60. }
  61. defer func() {
  62. if cErr := peerConnection.Close(); cErr != nil {
  63. fmt.Printf("cannot close peerConnection: %v\n", cErr)
  64. }
  65. }()
  66. // Create Track that we send video back to browser on
  67. outputTrack, err := webrtc.NewTrackLocalStaticRTP(webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeVP8}, "video", "pion")
  68. if err != nil {
  69. panic(err)
  70. }
  71. // Add this newly created track to the PeerConnection
  72. rtpSender, err := peerConnection.AddTrack(outputTrack)
  73. if err != nil {
  74. panic(err)
  75. }
  76. // Read incoming RTCP packets
  77. // Before these packets are returned they are processed by interceptors. For things
  78. // like NACK this needs to be called.
  79. go func() {
  80. rtcpBuf := make([]byte, 1500)
  81. for {
  82. if _, _, rtcpErr := rtpSender.Read(rtcpBuf); rtcpErr != nil {
  83. return
  84. }
  85. }
  86. }()
  87. // Wait for the offer to be pasted
  88. offer := webrtc.SessionDescription{}
  89. signal.Decode(signal.MustReadStdin(), &offer)
  90. // Set the remote SessionDescription
  91. err = peerConnection.SetRemoteDescription(offer)
  92. if err != nil {
  93. panic(err)
  94. }
  95. // Set a handler for when a new remote track starts, this handler copies inbound RTP packets,
  96. // replaces the SSRC and sends them back
  97. peerConnection.OnTrack(func(track *webrtc.TrackRemote, receiver *webrtc.RTPReceiver) {
  98. fmt.Printf("Track has started, of type %d: %s \n", track.PayloadType(), track.Codec().MimeType)
  99. for {
  100. // Read RTP packets being sent to Pion
  101. rtp, _, readErr := track.ReadRTP()
  102. if readErr != nil {
  103. panic(readErr)
  104. }
  105. if writeErr := outputTrack.WriteRTP(rtp); writeErr != nil {
  106. panic(writeErr)
  107. }
  108. }
  109. })
  110. // Set the handler for Peer connection state
  111. // This will notify you when the peer has connected/disconnected
  112. peerConnection.OnConnectionStateChange(func(s webrtc.PeerConnectionState) {
  113. fmt.Printf("Peer Connection State has changed: %s\n", s.String())
  114. if s == webrtc.PeerConnectionStateFailed {
  115. // Wait until PeerConnection has had no network activity for 30 seconds or another failure. It may be reconnected using an ICE Restart.
  116. // Use webrtc.PeerConnectionStateDisconnected if you are interested in detecting faster timeout.
  117. // Note that the PeerConnection may come back from PeerConnectionStateDisconnected.
  118. fmt.Println("Peer Connection has gone to failed exiting")
  119. os.Exit(0)
  120. }
  121. })
  122. // Create an answer
  123. answer, err := peerConnection.CreateAnswer(nil)
  124. if err != nil {
  125. panic(err)
  126. }
  127. // Create channel that is blocked until ICE Gathering is complete
  128. gatherComplete := webrtc.GatheringCompletePromise(peerConnection)
  129. // Sets the LocalDescription, and starts our UDP listeners
  130. if err = peerConnection.SetLocalDescription(answer); err != nil {
  131. panic(err)
  132. }
  133. // Block until ICE Gathering is complete, disabling trickle ICE
  134. // we do this because we only can exchange one signaling message
  135. // in a production application you should exchange ICE Candidates via OnICECandidate
  136. <-gatherComplete
  137. // Output the answer in base64 so we can paste it in browser
  138. fmt.Println(signal.Encode(*peerConnection.LocalDescription()))
  139. // Block forever
  140. select {}
  141. }