All files / atom/videoPlayer/src/hooks/hls useInitHlsEffect.js

48.48% Statements 16/33
23.52% Branches 4/17
55.55% Functions 5/9
50% Lines 16/32

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84            1x 5x       5x       5x         5x 5x     5x 5x   5x                                             5x                               5x       5x 5x     5x 5x 5x              
import {useEffect} from 'react'
 
import Hls from 'hls.js'
 
import {HLS} from '../../settings/players.js'
 
const useInitHlsEffect = ({autoPlay, hlsConfig, onLoadVideo, playerRef, src, timeOffset}) => {
  useEffect(() => {
    let hls
 
    function _initPlayer() {
      Iif (hls !== undefined) {
        hls.destroy()
      }
 
      const newHls = new Hls({
        enableWorker: false,
        ...hlsConfig
      })
 
      Eif (playerRef.current !== null) {
        newHls.attachMedia(playerRef.current)
      }
 
      newHls.on(Hls.Events.MEDIA_ATTACHED, () => {
        newHls.loadSource(`${src}`)
 
        newHls.on(Hls.Events.MANIFEST_PARSED, () => {
          playerRef.current.onloadedmetadata = () => {
            const {duration, videoHeight, videoWidth} = playerRef.current
            onLoadVideo({
              src,
              type: HLS.VIDEO_TYPE,
              duration,
              videoHeight,
              videoWidth
            })
          }
 
          if (timeOffset) playerRef.current.currentTime = timeOffset
 
          if (autoPlay) {
            /* eslint-disable no-console */
            playerRef?.current
              ?.play()
              .catch(() => console.log('Unable to autoplay prior to user interaction with the dom.'))
          }
        })
      })
 
      newHls.on(Hls.Events.ERROR, function (event, data) {
        if (data.fatal) {
          switch (data.type) {
            case Hls.ErrorTypes.NETWORK_ERROR:
              newHls.startLoad()
              break
            case Hls.ErrorTypes.MEDIA_ERROR:
              newHls.recoverMediaError()
              break
            default:
              _initPlayer()
              break
          }
        }
      })
 
      hls = newHls
    }
 
    // Check for Media Source support
    Eif (Hls.isSupported()) {
      _initPlayer()
    }
 
    return () => {
      Eif (hls !== undefined) {
        hls.destroy()
      }
    }
  }, [autoPlay, hlsConfig, playerRef, src, timeOffset, onLoadVideo])
}
 
export default useInitHlsEffect