main.go 5.1 KB

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