Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use loadSource() with strings instead of m3u8 playlists?

Tags:

hls.js

In the demo by galeksandrp: https://github.com/galeksandrp/hls.js/tree/hlstorrent he uses webtorrent and hls.js to create a P2P stream. The demo works perfectly for me but I will need to use the strings variable instead of loading an external playlist with hls.loadSource('193039199_mp4_h264_aac_ld_7.m3u8').

Has anyone ever done something similar? Simply trying to load the string gives: "Error trying to parse base URL" which is understandable since URLToolkit tries to build an absolute URL out of anything within the brackets of loadSource and thus it won't have a URL it can parse.

The strings variable has the same content as '193039199_mp4_h264_aac_ld_7.m3u8'

strings = ['#EXTM3U',
         '#EXT-X-VERSION:3',
         '#EXT-X-PLAYLIST-TYPE:VOD',
         '#EXT-X-TARGETDURATION:10',
         '#EXTINF:10.000,',
         'magnet:?xt=urn:btih:5493683624141c381fa19c9ed3bf00be2e0d96af',
         '#EXTINF:10.000,',
         'magnet:?xt=urn:btih:1ec3227aabe562cf2b244a41b93fa0a1aa423f4d',
         '#EXTINF:10.000,',
         'magnet:?xt=urn:btih:3cbd1622487f202f11aea838b0984a1478054456',
         '#EXTINF:10.000,',
         'magnet:?xt=urn:btih:9cf20cfe4fd1745ea4f72067192681b30b52a8c5',
         '#EXTINF:10.000,',
         'magnet:?xt=urn:btih:0c96911da7c860a9ae2a26ed8a96c10590508407',
         '#EXT-X-ENDLIST'];
like image 398
Marko Nikolov Avatar asked Dec 13 '17 10:12

Marko Nikolov


1 Answers

var enc = new TextEncoder("utf-8");
hls.loadSource(URL.createObjectURL(new Blob([enc.encode(strings.join('\n'))])));

Explaination: You only need to turn playlist text to URL, no need to write custom playlist loader.

  • Join array of strings to text (if needed), and turn text to Uint8Array with enc.encode().
  • Then turn result to Blob with new Blob([]).
  • Then turn result to blob: virtual URL with URL.createObjectURL().

Example:

  • https://rawgit.com/galeksandrp/hls.js/hlstorrent-blob-url/client.js
  • https://rawgit.com/galeksandrp/hls.js/hlstorrent-blob-url/server.js

var hls = new Hls({fLoader: customLoader, pLoader: customLoaderP});

Explaination: You can also write custom playlist loader because default is hardcoded to use XHR and therefore:

  • does not support playlist as text
  • does not support playlist as ArrayBuffer and derivatives (Blob, FileReader).
  • only support usual and blob: urls

Example of that custom playlist loader is customLoaderP function in which you discovered playlist in form of array of strings.

Please also note that my example is optimized for Live P2P, and therefore new torrent created for each 10seconds chunk, which may be not needed if you distributing VOD/DVR. With usual videos you can pass all chunks in single torrent.

like image 66
galeksandrp Avatar answered Oct 02 '22 11:10

galeksandrp