main.go 6.0 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. // save-to-disk is a simple application that shows how to record your webcam/microphone using Pion WebRTC and save VP8/Opus to disk.
  6. package main
  7. import (
  8. "fmt"
  9. "os"
  10. "strings"
  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. "github.com/pion/webrtc/v3/pkg/media"
  16. "github.com/pion/webrtc/v3/pkg/media/ivfwriter"
  17. "github.com/pion/webrtc/v3/pkg/media/oggwriter"
  18. )
  19. func saveToDisk(i media.Writer, track *webrtc.TrackRemote) {
  20. defer func() {
  21. if err := i.Close(); err != nil {
  22. panic(err)
  23. }
  24. }()
  25. for {
  26. rtpPacket, _, err := track.ReadRTP()
  27. if err != nil {
  28. panic(err)
  29. }
  30. if err := i.WriteRTP(rtpPacket); err != nil {
  31. panic(err)
  32. }
  33. }
  34. }
  35. // nolint:gocognit
  36. func main() {
  37. // Everything below is the Pion WebRTC API! Thanks for using it ❤️.
  38. // Create a MediaEngine object to configure the supported codec
  39. m := &webrtc.MediaEngine{}
  40. // Setup the codecs you want to use.
  41. // We'll use a VP8 and Opus but you can also define your own
  42. if err := m.RegisterCodec(webrtc.RTPCodecParameters{
  43. RTPCodecCapability: webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeVP8, ClockRate: 90000, Channels: 0, SDPFmtpLine: "", RTCPFeedback: nil},
  44. PayloadType: 96,
  45. }, webrtc.RTPCodecTypeVideo); err != nil {
  46. panic(err)
  47. }
  48. if err := m.RegisterCodec(webrtc.RTPCodecParameters{
  49. RTPCodecCapability: webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeOpus, ClockRate: 48000, Channels: 0, SDPFmtpLine: "", RTCPFeedback: nil},
  50. PayloadType: 111,
  51. }, webrtc.RTPCodecTypeAudio); err != nil {
  52. panic(err)
  53. }
  54. // Create a InterceptorRegistry. This is the user configurable RTP/RTCP Pipeline.
  55. // This provides NACKs, RTCP Reports and other features. If you use `webrtc.NewPeerConnection`
  56. // this is enabled by default. If you are manually managing You MUST create a InterceptorRegistry
  57. // for each PeerConnection.
  58. i := &interceptor.Registry{}
  59. // Register a intervalpli factory
  60. // This interceptor sends a PLI every 3 seconds. A PLI causes a video keyframe to be generated by the sender.
  61. // This makes our video seekable and more error resilent, but at a cost of lower picture quality and higher bitrates
  62. // A real world application should process incoming RTCP packets from viewers and forward them to senders
  63. intervalPliFactory, err := intervalpli.NewReceiverInterceptor()
  64. if err != nil {
  65. panic(err)
  66. }
  67. i.Add(intervalPliFactory)
  68. // Use the default set of Interceptors
  69. if err = webrtc.RegisterDefaultInterceptors(m, i); err != nil {
  70. panic(err)
  71. }
  72. // Create the API object with the MediaEngine
  73. api := webrtc.NewAPI(webrtc.WithMediaEngine(m), webrtc.WithInterceptorRegistry(i))
  74. // Prepare the configuration
  75. config := webrtc.Configuration{
  76. ICEServers: []webrtc.ICEServer{
  77. {
  78. URLs: []string{"stun:stun.l.google.com:19302"},
  79. },
  80. },
  81. }
  82. // Create a new RTCPeerConnection
  83. peerConnection, err := api.NewPeerConnection(config)
  84. if err != nil {
  85. panic(err)
  86. }
  87. // Allow us to receive 1 audio track, and 1 video track
  88. if _, err = peerConnection.AddTransceiverFromKind(webrtc.RTPCodecTypeAudio); err != nil {
  89. panic(err)
  90. } else if _, err = peerConnection.AddTransceiverFromKind(webrtc.RTPCodecTypeVideo); err != nil {
  91. panic(err)
  92. }
  93. oggFile, err := oggwriter.New("output.ogg", 48000, 2)
  94. if err != nil {
  95. panic(err)
  96. }
  97. ivfFile, err := ivfwriter.New("output.ivf")
  98. if err != nil {
  99. panic(err)
  100. }
  101. // Set a handler for when a new remote track starts, this handler saves buffers to disk as
  102. // an ivf file, since we could have multiple video tracks we provide a counter.
  103. // In your application this is where you would handle/process video
  104. peerConnection.OnTrack(func(track *webrtc.TrackRemote, receiver *webrtc.RTPReceiver) {
  105. codec := track.Codec()
  106. if strings.EqualFold(codec.MimeType, webrtc.MimeTypeOpus) {
  107. fmt.Println("Got Opus track, saving to disk as output.opus (48 kHz, 2 channels)")
  108. saveToDisk(oggFile, track)
  109. } else if strings.EqualFold(codec.MimeType, webrtc.MimeTypeVP8) {
  110. fmt.Println("Got VP8 track, saving to disk as output.ivf")
  111. saveToDisk(ivfFile, track)
  112. }
  113. })
  114. // Set the handler for ICE connection state
  115. // This will notify you when the peer has connected/disconnected
  116. peerConnection.OnICEConnectionStateChange(func(connectionState webrtc.ICEConnectionState) {
  117. fmt.Printf("Connection State has changed %s \n", connectionState.String())
  118. if connectionState == webrtc.ICEConnectionStateConnected {
  119. fmt.Println("Ctrl+C the remote client to stop the demo")
  120. } else if connectionState == webrtc.ICEConnectionStateFailed {
  121. if closeErr := oggFile.Close(); closeErr != nil {
  122. panic(closeErr)
  123. }
  124. if closeErr := ivfFile.Close(); closeErr != nil {
  125. panic(closeErr)
  126. }
  127. fmt.Println("Done writing media files")
  128. // Gracefully shutdown the peer connection
  129. if closeErr := peerConnection.Close(); closeErr != nil {
  130. panic(closeErr)
  131. }
  132. os.Exit(0)
  133. }
  134. })
  135. // Wait for the offer to be pasted
  136. offer := webrtc.SessionDescription{}
  137. signal.Decode(signal.MustReadStdin(), &offer)
  138. // Set the remote SessionDescription
  139. err = peerConnection.SetRemoteDescription(offer)
  140. if err != nil {
  141. panic(err)
  142. }
  143. // Create answer
  144. answer, err := peerConnection.CreateAnswer(nil)
  145. if err != nil {
  146. panic(err)
  147. }
  148. // Create channel that is blocked until ICE Gathering is complete
  149. gatherComplete := webrtc.GatheringCompletePromise(peerConnection)
  150. // Sets the LocalDescription, and starts our UDP listeners
  151. err = peerConnection.SetLocalDescription(answer)
  152. if err != nil {
  153. panic(err)
  154. }
  155. // Block until ICE Gathering is complete, disabling trickle ICE
  156. // we do this because we only can exchange one signaling message
  157. // in a production application you should exchange ICE Candidates via OnICECandidate
  158. <-gatherComplete
  159. // Output the answer in base64 so we can paste it in browser
  160. fmt.Println(signal.Encode(*peerConnection.LocalDescription()))
  161. // Block forever
  162. select {}
  163. }