Example: HLS example code

Last modified: Tuesday May 21, 2024.

This example code enables you to view the live and recorded video streams from two cameras connected to your Alta Aware deployment, and to view a bookmarked saved clip. The output can be viewed in a browser using <localhost>.

To view the camera streams:

  1. Create an Aware user with only the permissions needed for your stream type (live stream or playback ). Ensure that this user is assigned to a suitable, minimum permission, User Group.
  2. Modify the example code to match the information from your Alta Aware deployment.
    Values you need to change are:
    • <deploymentname> — The first part of the URL you use to access your Alta Aware deployment.
    • <region> — The second part of the URL you use to access your Alta Aware deployment.
    • <deviceGUID> — Find this information by using the Alta Aware Devices tool , and selecting the required camera.
    • <username> — The user name that has been set up with the minimum necessary permissions.
    • <password> — The password for the user.
  3. Save the modified HTML file to a convenient location on your computer.
  4. If viewing across the web, ensure that you configure the CORS list. See How to: Configure cross-origin resource sharing in Alta Aware.
  5. From a Command Prompt, run the command npx http-server -p 80.
    This creates a simple static HTTP server to enable you to test the example code locally.
  6. Open a Chrome browser window, and enter localhost/<location and filename>
    The Demo page loads, and after a few seconds, the video streams are displayed.

The following example uses 3rd-party Javascript HLS client libraries from https://cdn.jsdelivr.net.

Table 1 – Example HTML code to display two camera streams

 
			
<DOCTYPE html>
	<html lang="en">
		<head>
			<meta charset="UTF-8">
			<meta name="viewport" content="width=device-width, initial-scale=1.0">
			<title>Alta Aware HLS Demo</title>
			<style>
				.video-container {
					display: flex;
					justify-content: space-between;
					align-items: center;
					gap: 20px;
				}
				.video-wrapper {
					flex: 1;
					text-align: center;
				}
				video {
					width: 100%;
				}
			</style>
		</head>
		<body>
			<h1>Alta Aware HLS Demo</h1>
			<div class="video-container">
				<div class="video-wrapper">
					<h2>Live video</h2>
						<video id="video1" controls autoplay muted>
							Your browser does not support the video tag.
						</video>
				</div>
				<div class="video-wrapper">
					<h2>Playback recorded video</h2>
						<video id="video2" controls autoplay muted>
							Your browser does not support the video tag.
						</video>
				</div>
				<div class="video-wrapper">
					<h2>Bookmarked saved clip</h2>
						<video id="video3" controls autoplay muted>
							Your browser does not support the video tag.
						</video>
				</div>
			</div>
					
			<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
			<script>
				function setupHlsPlayer(videoElementId, streamUrl, username, password) {
					var hls = new Hls({
						xhrSetup: function(xhr, url) {
							var basicAuth = 'Basic ' + btoa(username + ':' + password);
							xhr.setRequestHeader('Authorization', basicAuth);
							xhr.withCredentials = true;
						},
						maxBufferLength: 120,
						maxMaxBufferLength: 180,
						maxBufferSize: 200 * 1024 * 1024,
						maxBufferHole: 0.1,
						lowBufferWatchdogPeriod: 1,
						highBufferWatchdogPeriod: 5,
						startLevel: -1,
						capLevelToPlayerSize: true,
						enableWorker: true,
						liveSyncDurationCount: 3,
						enableSoftwareAES: false,
						debug: true
					});
					var video = document.getElementById(videoElementId);
					video.autoplay = true;
					video.muted = true;
					if (Hls.isSupported()) {
						hls.attachMedia(video);
						hls.on(Hls.Events.MEDIA_ATTACHED, function () {
							console.log(`video and hls.js are now bound together for ${videoElementId}!`);
							hls.loadSource(streamUrl);
							hls.on(Hls.Events.MANIFEST_PARSED, function(event, data) {
								console.log(`manifest loaded for ${videoElementId}, found ${data.levels.length} quality levels`);
								video.play();
							});
						});
						hls.on(Hls.Events.ERROR, function (event, data) {
							var errorType = data.type;
							var errorDetails = data.details;
							var errorFatal = data.fatal;
							console.warn(`HLS error for ${videoElementId}: ${errorType} - ${errorDetails}`);
							if (errorFatal) {
								switch (data.type) {
									case Hls.ErrorTypes.NETWORK_ERROR:
										console.error(`Fatal network error encountered for ${videoElementId}, trying to recover...`);
										hls.startLoad();
										break;
									case Hls.ErrorTypes.MEDIA_ERROR:
										console.error(`Fatal media error encountered for ${videoElementId}, trying to recover...`);
										hls.recoverMediaError();
										break;
									default:
										hls.destroy();
										break;
								}
							}
						});
					} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
						video.src = streamUrl;
						video.addEventListener('canplay', function() {
							video.play();
						});
					}
				}
				var streamUrl1 = 'https://<deploymentname>.stream.<region>.alta.avigilon.com/hls/streams/index?deviceId=<deviceGUID>';
				var streamUrl2 = 'https://<deploymentname>.stream.<region>.alta.avigilon.com/hls/playback/index?deviceId=<deviceGUID>&startTimestamp=<timestamp>';
				var streamUrl3 = 'https://<deploymentname>.stream.<region>.alta.avigilon.com/hls/bookmark/<BookmarkToken>&node=<source>/index';
				
				setupHlsPlayer('video1', streamUrl1, '<username>', '<password>');
				setupHlsPlayer('video2', streamUrl2, '<username>', '<password');
				setupHlsPlayer('video3', streamUrl3, '<username>', '<password');
			</script>
		</body>
	</html>
			
		

When developing your own integrations using hls.js or other HLS player libraries, ensure that you enable support for 3rd-party cookies on the XmlHttpRequest used by the player. The example shown achieves this by using xhr.withCredentials = true.