Search code examples
node.jsexpressvideo-streaming

NodeJS Express video streaming server with server controlled range


So I don't currently have any code but its just a general question. I've seen multiple articles and SO Questions that handle this issue except that in all of those the byte range header, that essentially specifies what time segment of the video is sent back to the client, is also specified by the client. I want the server to keep track of the current video position and stream the video back to the client.

The articles and SO Questions I've seen for reference:

https://blog.logrocket.com/build-video-streaming-server-node/

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?


Solution

  • Here's a solution that does not involve explicitly changing the header for the <video> tag src request or controlling the byte range piped from the server.

    The video element has a property called currentTime (in seconds) which allows the client to control its own range header. A separate request to the server for an initial value for 'currentTime' would allow the server to control the start time of the video.

    <video id="video"><source src="/srcendpoint" muted type="video/mp4" /></video>
    
    <script>
      const video = document.getElementById("videoPlayer")
      getCurrentSecAndPlay()
        
      async function getCurrentSecAndPlay() {
        let response = await fetch('/currentPosition').then(response => response.json())
        video.currentTime += response.currentSec
        video.play()
      }
    </script>
    

    This is sort of a work-around solution to mimic livestream behaviour. Maybe it's good enough for you. I do not have a lot of knowledge on HLS and RTMP but if you wanted to make a true livestream you should study those things.

    sources: