wait-tracks.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package engine
  2. import (
  3. "m7s.live/engine/v4/common"
  4. . "m7s.live/engine/v4/common"
  5. "m7s.live/engine/v4/track"
  6. "m7s.live/engine/v4/util"
  7. )
  8. type waitTrackNames []string
  9. // Waiting是否正在等待
  10. func (w waitTrackNames) Waiting() bool {
  11. return w != nil
  12. }
  13. // Waitany 是否等待任意的
  14. func (w waitTrackNames) Waitany() bool {
  15. return len(w) == 0
  16. }
  17. // Wait 设置需要等待的名称,空数组为等待任意的
  18. func (w *waitTrackNames) Wait(names ...string) {
  19. if names == nil {
  20. *w = make([]string, 0)
  21. } else {
  22. *w = names
  23. }
  24. }
  25. // StopWait 不再需要等待了
  26. func (w *waitTrackNames) StopWait() {
  27. *w = nil
  28. }
  29. func (w waitTrackNames) InviteTrack(suber ISubscriber) {
  30. if len(w) > 0 {
  31. InviteTrack(w[0], suber)
  32. }
  33. }
  34. // Accept 检查名称是否在等待候选项中
  35. func (w *waitTrackNames) Accept(name string) bool {
  36. if !w.Waiting() {
  37. return false
  38. }
  39. if w.Waitany() {
  40. w.StopWait()
  41. return true
  42. } else {
  43. for _, n := range *w {
  44. if n == name {
  45. w.StopWait()
  46. return true
  47. }
  48. }
  49. }
  50. return false
  51. }
  52. type waitTracks struct {
  53. *util.Promise[ISubscriber] // 等待中的Promise
  54. audio waitTrackNames
  55. video waitTrackNames
  56. data waitTrackNames
  57. }
  58. // NeedWait 是否需要等待Track
  59. func (w *waitTracks) NeedWait() bool {
  60. return w.audio.Waiting() || w.video.Waiting() || w.data.Waiting()
  61. }
  62. // Accept 有新的Track来到,检查是否可以不再需要等待了
  63. func (w *waitTracks) Accept(t Track) bool {
  64. suber := w.Promise.Value
  65. switch t.(type) {
  66. case *track.Audio:
  67. if w.audio.Accept(t.GetName()) {
  68. suber.OnEvent(t)
  69. }
  70. case *track.Video:
  71. if w.video.Accept(t.GetName()) {
  72. suber.OnEvent(t)
  73. }
  74. case common.Track:
  75. w.data.Accept(t.GetName())
  76. suber.OnEvent(t)
  77. }
  78. if w.NeedWait() {
  79. return false
  80. } else {
  81. w.Resolve()
  82. return true
  83. }
  84. }