2
0

hls.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. package download
  2. import (
  3. "context"
  4. "errors"
  5. "github.com/grafov/m3u8"
  6. "github.com/hashicorp/golang-lru/v2/expirable"
  7. "github.com/rs/zerolog/log"
  8. "io"
  9. "net/http"
  10. "net/url"
  11. "strings"
  12. "sync/atomic"
  13. "time"
  14. )
  15. type HLSOptions struct {
  16. Timeout time.Duration
  17. MaxAttempts int
  18. }
  19. type HLS struct {
  20. ctx context.Context
  21. ctxClose context.CancelFunc
  22. exit chan any
  23. options HLSOptions
  24. client *http.Client
  25. request *http.Request
  26. retryAttempts atomic.Uint32
  27. }
  28. func NewHLS(r func() (*http.Request, error), opts HLSOptions) (*HLS, error) {
  29. if r == nil {
  30. return nil, errors.New("illegal state: empty requester")
  31. }
  32. var (
  33. d = HLS{
  34. options: opts,
  35. client: &http.Client{
  36. Transport: func() *http.Transport {
  37. transport := http.DefaultTransport.(*http.Transport)
  38. transport.Proxy = http.ProxyFromEnvironment
  39. return transport
  40. }(),
  41. Timeout: opts.Timeout,
  42. },
  43. }
  44. err error
  45. )
  46. if d.request, err = r(); err != nil {
  47. return nil, err
  48. }
  49. d.ctx, d.ctxClose = context.WithCancel(context.Background())
  50. return &d, nil
  51. }
  52. func (d *HLS) Close() error {
  53. log.Info().Msg("request to close HLS recorder")
  54. if d.ctxClose != nil {
  55. d.ctxClose()
  56. }
  57. d.exit <- 0
  58. return nil
  59. }
  60. func (d *HLS) Start() chan []byte {
  61. d.exit = make(chan any)
  62. var (
  63. c = make(chan []byte)
  64. medialist *m3u8.MediaPlaylist
  65. segments = expirable.NewLRU[uint64, *m3u8.MediaSegment](64, nil, time.Minute)
  66. err error
  67. )
  68. go func() {
  69. defer close(c)
  70. for {
  71. select {
  72. case <-d.exit:
  73. c <- nil
  74. return
  75. default:
  76. if medialist, err = d.getMediaList(); err != nil {
  77. log.Debug().
  78. Err(err).
  79. Msg("could not retrieve m3u8 playlist")
  80. c <- nil
  81. return
  82. }
  83. if medialist.Closed {
  84. c <- nil
  85. return
  86. }
  87. duration := time.NewTicker(time.Duration(medialist.TargetDuration) * time.Second)
  88. for _, seq := range medialist.Segments {
  89. if seq == nil {
  90. continue
  91. }
  92. if _, ok := segments.Get(seq.SeqId); ok {
  93. continue
  94. }
  95. segments.Add(seq.SeqId, seq)
  96. var (
  97. uri = seq.URI
  98. request *http.Request
  99. response *http.Response
  100. buff []byte
  101. )
  102. // pre-handle relative segment URIs
  103. if !strings.HasPrefix(uri, "http") {
  104. if s, err := d.request.URL.Parse(uri); err != nil {
  105. log.Debug().Err(err).Msg("could not build segment abs segment URI")
  106. c <- nil
  107. return
  108. } else {
  109. if uri, err = url.QueryUnescape(s.String()); err != nil {
  110. log.Debug().Err(err).Msg("could not build segment abs segment URI")
  111. c <- nil
  112. return
  113. }
  114. }
  115. }
  116. request = d.request.Clone(d.ctx)
  117. request.Method = http.MethodGet
  118. if request.URL, err = request.URL.Parse(uri); err != nil {
  119. log.Debug().Err(err).Msg("could not parse segment URI")
  120. c <- nil
  121. return
  122. }
  123. if response, err = d.client.Do(request); err != nil {
  124. log.Debug().Err(err).Msg("could not retrieve segment data")
  125. c <- nil
  126. return
  127. }
  128. if buff, err = io.ReadAll(response.Body); err != nil {
  129. log.Debug().Err(err).Msg("could not read segment data")
  130. c <- nil
  131. return
  132. }
  133. _ = response.Body.Close()
  134. c <- buff
  135. }
  136. <-duration.C
  137. }
  138. }
  139. }()
  140. return c
  141. }
  142. func (d *HLS) requestMediaList(request *http.Request) (*http.Response, error) {
  143. var (
  144. response *http.Response
  145. err error
  146. )
  147. response, err = d.client.Do(request)
  148. if err != nil && errors.Is(err, http.ErrHandlerTimeout) {
  149. if d.retryAttempts.Load() == uint32(d.options.MaxAttempts) {
  150. return nil, err
  151. }
  152. select {
  153. case <-time.After(time.Second):
  154. }
  155. if d.options.MaxAttempts != -1 {
  156. d.retryAttempts.Add(1)
  157. }
  158. return d.requestMediaList(request)
  159. }
  160. if err != nil {
  161. return nil, err
  162. }
  163. d.retryAttempts.Store(0)
  164. return response, nil
  165. }
  166. func (d *HLS) getMediaList() (*m3u8.MediaPlaylist, error) {
  167. var (
  168. request *http.Request
  169. response *http.Response
  170. playlist m3u8.Playlist
  171. t m3u8.ListType
  172. err error
  173. )
  174. request = d.request.Clone(d.ctx)
  175. if response, err = d.requestMediaList(request); err != nil {
  176. return nil, err
  177. }
  178. if playlist, t, err = m3u8.DecodeFrom(response.Body, false); err != nil {
  179. return nil, err
  180. }
  181. if m3u8.MEDIA != t {
  182. return nil, errors.New("invalid media type")
  183. }
  184. return playlist.(*m3u8.MediaPlaylist), nil
  185. }