Search code examples
node.jssocketsvideostreaminghttp-live-streaming

Realtime HLS file playback with nodejs


I have built a php crud app that allows users to upload videos and queue them for conversion where I use FFMPEG to convert them to M3U8 Playlist format. I now need to build a streaming server that will allow me to playback those files in realtime so that when a user browses to the page they see the video playing at its current time. I know that nodejs has streaming capabilities and have done a great amount of research on video streaming and am coming up short. Can someone point me in the right direction with this. I have a concept in mind by using web sockets but I can't find an example that will help me solve my problem.


Solution

  • If you want to play the uploaded videos as video-on-demand (VOD) you just need to put the resulting segments and the m3u8 playlist in a web-accessible directory to be served via your web-server.

    You can easily emulate a live playlist based on your complete playlist using node.js by serving an on-the-fly generated m3u8.

    Eg:

    1. For each new client session get the initial connection time
    2. For each new GET request sent by the client calculate the current playing segment index using the difference between the initial time and the request time and the media segment durations in the complete m3u8 playlist. This will be the last element in the playlist.
    3. Find the previous i - n segments where n is your desired sliding-window size. Increase n if the current window size is less than three time the target duration. Use i - n as the #EXT-X-MEDIA-SEQUENCE value.
    4. Write the playlist containing the n resulting segments
    5. Repeat 2-4 for each request for each individual session.

    By managing the time offsets properly you can also time-shift etc. Keep the segments indexed by play time in something like memcached for performance's sake.