hls.js icon indicating copy to clipboard operation
hls.js copied to clipboard

Creating an IPFS custom loader: failure in v1.x?

Open codi0 opened this issue 4 years ago • 7 comments

What do you want to do with Hls.js?

I'm attempting to write a custom loader for ipfs. Everything works perfectly in v0.14.17, but any version from 1.0.0 up to 1.1.5 (latest) fails. I'm not sure whether there's a bug in the hls.js code or whether my custom loader needs tweaking.

What have you tried so far?

Tested on Windows 10, in Chrome 100.0.4896.75 and Firefox 99.0. In both browsers, it works in 3 of 4 scenarios:

1.) v0.14.17 - https version of video file - PASS 2.) v0.14.17 - ipfs version of video file - PASS 3.) v1.1.5 - https version of video file - PASS 4.) v1.1.5 - ipfs version of video file - FAIL

Console doesn't throw any errors, but stops downloading any chunks after the first one:

[log] > attachMedia   ([email protected]:1)
[log] > [buffer-controller]: Media source opened   ([email protected]:1)
[log] > [subtitle-stream-controller]: STOPPED->IDLE   ([email protected]:1)
[log] > stopLoad   ([email protected]:1)
[log] > [subtitle-stream-controller]: IDLE->STOPPED   ([email protected]:1)
[log] > loadSource:ipfs://QmdpAidwAsBGptFB3b6A9Pyi5coEbgjHrL3K2Qrsutmj9K   ([email protected]:1)
[log] > [stream-controller]: Trigger BUFFER_RESET   ([email protected]:1)
Fetching cid: QmdpAidwAsBGptFB3b6A9Pyi5coEbgjHrL3K2Qrsutmj9K/master.m3u8   (stream.html:25)
Received cid: QmdpAidwAsBGptFB3b6A9Pyi5coEbgjHrL3K2Qrsutmj9K/master.m3u8 {size: 3407, chunks: 1}   (stream.html:25)
[log] > [level-controller]: manifest loaded, 1 level(s) found, first bitrate: 0   ([email protected]:1)
[log] > 1 bufferCodec event(s) expected   ([email protected]:1)
[log] > startLoad(-1)   ([email protected]:1)
[log] > [level-controller]: switching to level 0 from -1   ([email protected]:1)
[log] > [stream-controller]: STOPPED->IDLE   ([email protected]:1)
[log] > [subtitle-stream-controller]: STOPPED->IDLE   ([email protected]:1)
[log] > [stream-controller]: Level 0 loaded [0,109], cc [0, 0] duration:596.41667   ([email protected]:1)
[log] > [buffer-controller]: Updating Media Source duration to 596.417   ([email protected]:1)
[log] > [stream-controller]: Loading fragment 0 cc: 0 of [0-109] level: 0, target: 0   ([email protected]:1)
[log] > [stream-controller]: IDLE->FRAG_LOADING   ([email protected]:1)
Fetching cid: QmdpAidwAsBGptFB3b6A9Pyi5coEbgjHrL3K2Qrsutmj9K/master0.ts   (stream.html:25)
Received cid: QmdpAidwAsBGptFB3b6A9Pyi5coEbgjHrL3K2Qrsutmj9K/master0.ts {size: 501960, chunks: 2}   (stream.html:25)
[log] > [stream-controller]: Loaded fragment 0 of level 0   ([email protected]:1)

Full code I'm testing with is below. Only change in test variants is switching the version number in the hls.js script file, and the url being loaded (https vs ipfs). I suspect it's an issue with the custom loader in v1.x of Hls, but cannot figure out what the problem is.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Hls Ipfs Test</title>
	<script defer src="https://cdn.jsdelivr.net/npm/ipfs/dist/index.min.js"></script>
	<script defer src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
	<script>
	//Config: select video url to stream (ipfs vs https)
	var url = 'ipfs://QmdpAidwAsBGptFB3b6A9Pyi5coEbgjHrL3K2Qrsutmj9K';
	//var url = 'https://multiplatform-f.akamaihd.net/i/multi/will/bunny/big_buck_bunny_,640x360_400,640x360_700,640x360_1000,950x540_1500,.f4v.csmil/master.m3u8';

	//define hls loader
	var HlsIpfsLoader = function(ipfsNode, debug) {
	
		//loader function
		return function() {

			//Helper: log to console
			var log = function(msg) {
				if(debug) {
					console.log.apply(console, arguments);
				}
			};

			//Helper: find ipfs path
			var findPath = async function(path) {
				//set vars
				var count = 0;
				//remove location?
				if(globalThis.location) {
					path = path.replace(globalThis.location, "");
				}
				//remove prefix?
				if(path.indexOf("ipfs://") === 0) {
					path = path.replace("ipfs://", "");
				}
				//already has ext?
				if(path.indexOf('.') === -1) {
					//check cid
					for await (var info of ipfsNode.ls(path)) {
						//valid file?
						if(info && info.type === 'file') {
							//add count
							count++;
							//m3u8 found?
							if(info.path.indexOf('.m3u8') > 0) {
								return info.path;
							}
						}
					}
					//use single file?
					if(count == 1) {
						path = info.path;
					}
				}
				//return
				return Promise.resolve(path);
			};

			//Helper: download ipfs file
			var downloadFile = async function(cid, opts) {
				//debug
				log("Fetching cid:", cid);
				try {
					//set vars
					var chunks = [];
					var length = 0;
					var offset = 0;
					//loop through chunks
					for await (var chunk of ipfsNode.cat(cid, opts)) {
						//cache chunk
						chunks.push(chunk);
						//add to length
						length += chunk.length;
						//aborted?
						if(api.stats.aborted) {
							log("Aborted IPFS streaming");
							break;
						}
					}
					//build data
					var data = new Uint8Array(length);
					//loop through chunks
					for(var chunk of chunks) {
						data.set(chunk, offset);
						offset += chunk.length;
					}
					//debug
					log("Received cid:", cid, { size: data.length, chunks: chunks.length });
					//return
					return data;
				} catch(Ex) {
					throw new Error("File not found: " + cid);
				}
			};

			//public API
			var api = {

				stats: {
					aborted: false,
					loaded: 0,
					total: 0,
					chunkCount: 0,
					bwEstimate: 0,
					retry: 0,
					loading: { start: 0, first: 0, end: 0 },
					parsing: { start: 0, end: 0 },
					buffering: { start: 0, first: 0, end: 0 }
				},

				load: function(context, config, callbacks) {
					//find ipfs path
					findPath(context.url).then(function(path) {
						//set vars
						var opts = {};
						var start = Date.now();
						//use context range?
						if(context.rangeStart) {
							//set range start
							opts.offset = context.rangeStart;
							//set range end?
							if(context.rangeEnd) {
								opts.length = context.rangeEnd - context.rangeStart;
							}
						}
						//update stats
						api.stats.loading.start = start;
						api.stats.parsing.start = start;
						api.stats.buffering.start = start;
						//download ipfs file
						downloadFile(path, opts).then(function(data) {
							//set vars
							var end = Date.now();
							//decode response?
							if(context.responseType !== 'arraybuffer') {
								data = new TextDecoder().decode(data);
							}
							//response object
							var response = {
								url: path,
								data: data
							};
							//update stats
							api.stats.loading.end = end;
							api.stats.parsing.end = end;
							api.stats.buffering.end = end;
							api.stats.loaded += data.length;
							api.stats.total += data.length;
							api.stats.chunkCount += 1;
							api.stats.bwEstimate = api.stats.loaded / (end - start);
							//success callback
							callbacks.onSuccess(response, api.stats, context);
						});
					});
				},

				abort: function() {
					//update flag
					api.stats.aborted = true;
				},

				destroy: function() {
					//do nothing
				}

			};

			//return
			return api;

		};

	};

	//define stream helper
	var stream = async function(path, callback) {
		//set vars
		var hls = new Hls({ debug: true });
		var mediaEl = document.createElement('video');
		//use ipfs?
		if(path.indexOf('ipfs://') === 0 || /^[0-9a-zA-Z]{32}/.test(path)) {
			//create ipfs node
			var node = await Ipfs.create();
			//set loader
			hls.config.loader = HlsIpfsLoader(node, true);
		}
		//attach media
		hls.attachMedia(mediaEl);
		//listen for media attached
		hls.on(Hls.Events.MEDIA_ATTACHED, function() {
			//load file
			hls.loadSource(path);
		});
		//listen for manifest parsed
		hls.on(Hls.Events.MANIFEST_PARSED, function() {
			mediaEl.controls = true;
			callback && callback(mediaEl);
		});
	}	

	//load streaming
	document.addEventListener('DOMContentLoaded', async function() {
		//stream video
		await stream(url, function(el) {
			document.getElementById('video').appendChild(el);
		});
	});
	</script>
</head>
<body>
	<div id="video"></div>
</body>
</html>

codi0 avatar Apr 08 '22 09:04 codi0

Any progress?

I've similarly been trying to write a custom loader on the latest version with no luck, and I just happened to stumble upon this issue and decided to try downgrading to version 0.14.1, where my code suddenly works.

JoakimLGit avatar May 03 '22 01:05 JoakimLGit

Unfortunately not. Have made do with 0.14.1 until someone gives some insight into what's required to make custom loaders work properly with v1.

codi0 avatar May 03 '22 06:05 codi0

Could you do a little experiment for me to confirm if I found the thing we are missing.

right above your onSuccess call add:

callbacks.onProgress(api.stats, context, response.data);

JoakimLGit avatar May 04 '22 15:05 JoakimLGit

Doesn't appear that callbacks.onProgress is defined, so I get a console error when adding that line.

codi0 avatar May 04 '22 17:05 codi0

Ah I guess you are using the same function for loading both the playlist and fragments so do a check like

if(callbacks.onProgress){ callbacks.onProgress(stats, context, data); }

JoakimLGit avatar May 04 '22 17:05 JoakimLGit

Oh yes, that does indeed work (tested with v1.1.5). Good spot!

codi0 avatar May 04 '22 17:05 codi0

Looks like this was resolved. Glad you got to the bottom of it! Loaders are required to invoke the onProgress callback.

robwalch avatar Sep 30 '23 04:09 robwalch