player.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. // The MIT License (MIT)
  2. //
  3. // # Copyright (c) 2021 Winlin
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy of
  6. // this software and associated documentation files (the "Software"), to deal in
  7. // the Software without restriction, including without limitation the rights to
  8. // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  9. // the Software, and to permit persons to whom the Software is furnished to do so,
  10. // subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in all
  13. // copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  17. // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  18. // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  19. // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  20. // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. package janus
  22. import (
  23. "context"
  24. "fmt"
  25. "github.com/ossrs/go-oryx-lib/errors"
  26. "github.com/ossrs/go-oryx-lib/logger"
  27. "github.com/pion/interceptor"
  28. "github.com/pion/rtcp"
  29. "github.com/pion/sdp/v3"
  30. "github.com/pion/webrtc/v3"
  31. "net/url"
  32. "strconv"
  33. "strings"
  34. "time"
  35. )
  36. func startPlay(ctx context.Context, r string, enableAudioLevel, enableTWCC bool, pli int) error {
  37. ctx = logger.WithContext(ctx)
  38. u, err := url.Parse(r)
  39. if err != nil {
  40. return errors.Wrapf(err, "Parse url %v", r)
  41. }
  42. var room int
  43. var display string
  44. if us := strings.SplitN(u.Path, "/", 3); len(us) >= 3 {
  45. if iv, err := strconv.Atoi(us[1]); err != nil {
  46. return errors.Wrapf(err, "parse %v", us[1])
  47. } else {
  48. room = iv
  49. }
  50. display = strings.Join(us[2:], "-")
  51. }
  52. logger.Tf(ctx, "Run play url=%v, room=%v, diplay=%v, audio-level=%v, twcc=%v",
  53. r, room, display, enableAudioLevel, enableTWCC)
  54. // For audio-level.
  55. webrtcNewPeerConnection := func(configuration webrtc.Configuration) (*webrtc.PeerConnection, error) {
  56. m := &webrtc.MediaEngine{}
  57. if err := m.RegisterDefaultCodecs(); err != nil {
  58. return nil, err
  59. }
  60. for _, extension := range []string{sdp.SDESMidURI, sdp.SDESRTPStreamIDURI, sdp.TransportCCURI} {
  61. if extension == sdp.TransportCCURI && !enableTWCC {
  62. continue
  63. }
  64. if err := m.RegisterHeaderExtension(webrtc.RTPHeaderExtensionCapability{URI: extension}, webrtc.RTPCodecTypeVideo); err != nil {
  65. return nil, err
  66. }
  67. }
  68. // https://github.com/pion/ion/issues/130
  69. // https://github.com/pion/ion-sfu/pull/373/files#diff-6f42c5ac6f8192dd03e5a17e9d109e90cb76b1a4a7973be6ce44a89ffd1b5d18R73
  70. for _, extension := range []string{sdp.SDESMidURI, sdp.SDESRTPStreamIDURI, sdp.AudioLevelURI} {
  71. if extension == sdp.AudioLevelURI && !enableAudioLevel {
  72. continue
  73. }
  74. if err := m.RegisterHeaderExtension(webrtc.RTPHeaderExtensionCapability{URI: extension}, webrtc.RTPCodecTypeAudio); err != nil {
  75. return nil, err
  76. }
  77. }
  78. i := &interceptor.Registry{}
  79. if err := webrtc.RegisterDefaultInterceptors(m, i); err != nil {
  80. return nil, err
  81. }
  82. api := webrtc.NewAPI(webrtc.WithMediaEngine(m), webrtc.WithInterceptorRegistry(i))
  83. return api.NewPeerConnection(configuration)
  84. }
  85. pc, err := webrtcNewPeerConnection(webrtc.Configuration{
  86. SDPSemantics: webrtc.SDPSemanticsUnifiedPlanWithFallback,
  87. })
  88. if err != nil {
  89. return errors.Wrapf(err, "Create PC")
  90. }
  91. var receivers []*webrtc.RTPReceiver
  92. defer func() {
  93. pc.Close()
  94. for _, receiver := range receivers {
  95. receiver.Stop()
  96. }
  97. }()
  98. pc.AddTransceiverFromKind(webrtc.RTPCodecTypeAudio, webrtc.RTPTransceiverInit{
  99. Direction: webrtc.RTPTransceiverDirectionRecvonly,
  100. })
  101. pc.AddTransceiverFromKind(webrtc.RTPCodecTypeVideo, webrtc.RTPTransceiverInit{
  102. Direction: webrtc.RTPTransceiverDirectionRecvonly,
  103. })
  104. // Signaling API
  105. api := newJanusAPI(fmt.Sprintf("http://%v/janus", u.Host))
  106. if err := api.Create(ctx); err != nil {
  107. return errors.Wrapf(err, "create")
  108. }
  109. defer api.Close()
  110. // Discover the publisherInfo to subscribe.
  111. publisherInfo, err := api.DiscoverPublisher(ctx, room, display, 5*time.Second)
  112. if err != nil {
  113. return err
  114. }
  115. logger.Tf(ctx, "Publisher found, room=%v, display=%v, %v", room, display, publisherInfo)
  116. subscribeHandle, err := api.AttachPlugin(ctx)
  117. if err != nil {
  118. return errors.Wrap(err, "attach plugin")
  119. }
  120. offer, err := api.JoinAsSubscribe(ctx, subscribeHandle, room, publisherInfo)
  121. if err != nil {
  122. return errors.Wrapf(err, "subscribe")
  123. }
  124. // Exchange offer and generate answer.
  125. if err := pc.SetRemoteDescription(webrtc.SessionDescription{
  126. Type: webrtc.SDPTypeOffer, SDP: offer,
  127. }); err != nil {
  128. return errors.Wrapf(err, "Set offer %v", offer)
  129. }
  130. answer, err := pc.CreateAnswer(nil)
  131. if err != nil {
  132. return errors.Wrapf(err, "Create answer")
  133. }
  134. if err := pc.SetLocalDescription(answer); err != nil {
  135. return errors.Wrapf(err, "Set answer %v", answer)
  136. }
  137. // Send answer to Janus.
  138. if err := api.Subscribe(ctx, subscribeHandle, room, answer.SDP); err != nil {
  139. return errors.Wrapf(err, "Subscribe with answer %v", answer)
  140. }
  141. handleTrack := func(ctx context.Context, track *webrtc.TrackRemote, receiver *webrtc.RTPReceiver) error {
  142. // Send a PLI on an interval so that the publisher is pushing a keyframe
  143. go func() {
  144. if track.Kind() == webrtc.RTPCodecTypeAudio {
  145. return
  146. }
  147. if pli <= 0 {
  148. return
  149. }
  150. for {
  151. select {
  152. case <-ctx.Done():
  153. return
  154. case <-time.After(time.Duration(pli) * time.Second):
  155. _ = pc.WriteRTCP([]rtcp.Packet{&rtcp.PictureLossIndication{
  156. MediaSSRC: uint32(track.SSRC()),
  157. }})
  158. }
  159. }
  160. }()
  161. receivers = append(receivers, receiver)
  162. codec := track.Codec()
  163. trackDesc := fmt.Sprintf("channels=%v", codec.Channels)
  164. if track.Kind() == webrtc.RTPCodecTypeVideo {
  165. trackDesc = fmt.Sprintf("fmtp=%v", codec.SDPFmtpLine)
  166. }
  167. if headers := receiver.GetParameters().HeaderExtensions; len(headers) > 0 {
  168. trackDesc = fmt.Sprintf("%v, header=%v", trackDesc, headers)
  169. }
  170. logger.Tf(ctx, "Got track %v, pt=%v, tbn=%v, %v",
  171. codec.MimeType, codec.PayloadType, codec.ClockRate, trackDesc)
  172. return writeTrackToDisk(ctx, track)
  173. }
  174. ctx, cancel := context.WithCancel(ctx)
  175. pc.OnTrack(func(track *webrtc.TrackRemote, receiver *webrtc.RTPReceiver) {
  176. err = handleTrack(ctx, track, receiver)
  177. if err != nil {
  178. codec := track.Codec()
  179. err = errors.Wrapf(err, "Handle track %v, pt=%v", codec.MimeType, codec.PayloadType)
  180. cancel()
  181. }
  182. })
  183. pc.OnICEConnectionStateChange(func(state webrtc.ICEConnectionState) {
  184. logger.If(ctx, "ICE state %v", state)
  185. if state == webrtc.ICEConnectionStateFailed || state == webrtc.ICEConnectionStateClosed {
  186. if ctx.Err() != nil {
  187. return
  188. }
  189. logger.Wf(ctx, "Close for ICE state %v", state)
  190. cancel()
  191. }
  192. })
  193. <-ctx.Done()
  194. return nil
  195. }
  196. func writeTrackToDisk(ctx context.Context, track *webrtc.TrackRemote) error {
  197. for ctx.Err() == nil {
  198. pkt, _, err := track.ReadRTP()
  199. if err != nil {
  200. if ctx.Err() != nil {
  201. return nil
  202. }
  203. return errors.Wrapf(err, "Read RTP")
  204. }
  205. logger.If(ctx, "Got packet ssrc=%v, pt=%v, seq=%v %vB",
  206. pkt.SSRC, pkt.PayloadType, pkt.SequenceNumber, len(pkt.Payload))
  207. }
  208. return ctx.Err()
  209. }