HLS.js is a comprehensive JavaScript library that implements an HTTP Live Streaming (HLS) client for web browsers. It enables smooth playback of video streams using HTML5 video elements and MediaSource Extensions, providing advanced transmuxing capabilities, adaptive bitrate streaming, and extensive format support.
npm install hls.jsimport Hls from "hls.js";For CommonJS:
const Hls = require("hls.js");Named imports for advanced usage:
import {
Hls,
Events,
ErrorTypes,
ErrorDetails,
isSupported,
isMSESupported
} from "hls.js";import Hls from "hls.js";
// Check browser support
if (Hls.isSupported()) {
const video = document.getElementById("video") as HTMLVideoElement;
const hls = new Hls();
// Attach media element
hls.attachMedia(video);
// Listen for media attachment
hls.on(Hls.Events.MEDIA_ATTACHED, () => {
console.log("Media element attached");
// Load HLS manifest
hls.loadSource("https://example.com/stream.m3u8");
});
// Listen for manifest parsing
hls.on(Hls.Events.MANIFEST_PARSED, (event, data) => {
console.log(`Manifest loaded with ${data.levels.length} quality levels`);
// Start playback
video.play();
});
// Handle errors
hls.on(Hls.Events.ERROR, (event, data) => {
console.error("HLS Error:", data);
});
} else if (video.canPlayType("application/vnd.apple.mpegurl")) {
// Native HLS support (Safari)
video.src = "https://example.com/stream.m3u8";
} else {
console.error("HLS is not supported");
}HLS.js is built around several key components:
Main Hls class providing streaming functionality, media attachment, and playback control.
declare class Hls {
constructor(userConfig?: Partial<HlsConfig>);
// Core methods
attachMedia(media: HTMLMediaElement): void;
detachMedia(): void;
loadSource(url: string): void;
startLoad(startPosition?: number): void;
stopLoad(): void;
destroy(): void;
// Properties
readonly config: HlsConfig;
readonly levels: Level[];
currentLevel: number;
loadLevel: number;
readonly media: HTMLMediaElement | null;
readonly url: string | null;
}Automatic and manual quality level selection with bandwidth estimation.
interface Hls {
// Quality levels
readonly levels: Level[];
currentLevel: number;
nextLevel: number;
loadLevel: number;
readonly autoLevelEnabled: boolean;
readonly manualLevel: number;
// Bandwidth estimation
bandwidthEstimate: number;
readonly abrEwmaDefaultEstimate: number;
readonly ttfbEstimate: number;
}Multi-track audio and subtitle support with dynamic switching.
interface Hls {
// Audio tracks
readonly allAudioTracks: MediaPlaylist[];
readonly audioTracks: MediaPlaylist[];
audioTrack: number;
setAudioOption(option: AudioSelectionOption): MediaPlaylist | null;
// Subtitle tracks
readonly allSubtitleTracks: MediaPlaylist[];
readonly subtitleTracks: MediaPlaylist[];
subtitleTrack: number;
subtitleDisplay: boolean;
setSubtitleOption(option: SubtitleSelectionOption): MediaPlaylist | null;
}Live stream support with DVR, low-latency modes, and latency control.
interface Hls {
readonly liveSyncPosition: number | null;
readonly latency: number;
readonly maxLatency: number;
targetLatency: number | null;
readonly drift: number | null;
lowLatencyMode: boolean;
readonly playingDate: Date | null;
}Comprehensive event system for monitoring playback state and handling errors.
interface HlsEventEmitter {
on<E extends keyof HlsListeners>(
event: E,
listener: HlsListeners[E],
context?: any
): void;
once<E extends keyof HlsListeners>(
event: E,
listener: HlsListeners[E],
context?: any
): void;
off<E extends keyof HlsListeners>(
event: E,
listener?: HlsListeners[E],
context?: any
): void;
emit<E extends keyof HlsListeners>(
event: E,
name: E,
eventObject: Parameters<HlsListeners[E]>[1]
): boolean;
}
enum Events {
MANIFEST_LOADING = "hlsManifestLoading",
MANIFEST_LOADED = "hlsManifestLoaded",
MANIFEST_PARSED = "hlsManifestParsed",
LEVEL_SWITCHING = "hlsLevelSwitching",
LEVEL_SWITCHED = "hlsLevelSwitched",
ERROR = "hlsError",
// ... many more events
}Comprehensive error types, recovery mechanisms, and retry logic.
enum ErrorTypes {
NETWORK_ERROR = "networkError",
MEDIA_ERROR = "mediaError",
KEY_SYSTEM_ERROR = "keySystemError",
MUX_ERROR = "muxError",
OTHER_ERROR = "otherError"
}
enum ErrorDetails {
MANIFEST_LOAD_ERROR = "manifestLoadError",
MANIFEST_LOAD_TIMEOUT = "manifestLoadTimeout",
FRAG_LOAD_ERROR = "fragLoadError",
// ... 50+ specific error types
}Utilities for detecting MediaSource Extensions and codec support.
function isSupported(): boolean;
function isMSESupported(): boolean;
function getMediaSource(): typeof MediaSource | undefined;Extensible architecture with pluggable controllers and utilities.
// Controllers
class AbrController { /* ABR logic */ }
class BufferController { /* Buffer management */ }
class EMEController { /* DRM/encryption */ }
class ContentSteeringController { /* CDN steering */ }
// Loaders
class XhrLoader { /* XMLHttpRequest loader */ }
class FetchLoader { /* Fetch API loader */ }
// Utilities
class M3U8Parser { /* Manifest parsing */ }
class Cues { /* VTT cue management */ }declare class Hls {
static readonly version: string;
static readonly Events: typeof Events;
static readonly ErrorTypes: typeof ErrorTypes;
static readonly ErrorDetails: typeof ErrorDetails;
static readonly DefaultConfig: HlsConfig;
static isSupported(): boolean;
static isMSESupported(): boolean;
}interface HlsConfig {
// Loading configuration
maxBufferLength: number;
maxBufferSize: number;
maxBufferHole: number;
lowBufferWatchdogPeriod: number;
highBufferWatchdogPeriod: number;
// ABR configuration
abrEwmaDefaultEstimate: number;
abrEwmaSlowVoD: number;
abrEwmaFastVoD: number;
abrEwmaSlowLive: number;
abrEwmaFastLive: number;
// Network configuration
manifestLoadingTimeOut: number;
manifestLoadingMaxRetry: number;
fragLoadingTimeOut: number;
fragLoadingMaxRetry: number;
// And many more configuration options...
}
interface Level {
readonly bitrate: number;
readonly width: number;
readonly height: number;
readonly codecSet: string;
readonly url: string[];
readonly details: LevelDetails | undefined;
}
interface MediaPlaylist {
readonly id: number;
readonly name: string;
readonly lang: string | undefined;
readonly assocLang: string | undefined;
readonly characteristics: string | undefined;
readonly channels: string | undefined;
readonly uri: string;
}
// Fragment and segment types
interface Fragment {
readonly url: string;
readonly start: number;
readonly duration: number;
readonly level: number;
readonly sn: number;
readonly cc: number;
}
interface BaseSegment {
readonly uri: string;
readonly byteRange?: [number, number];
readonly duration: number;
}
interface Part extends BaseSegment {
readonly duration: number;
readonly independent?: boolean;
readonly gap?: boolean;
}
// Loader and loading types
interface LoadStats {
aborted: boolean;
loaded: number;
retry: number;
total: number;
chunkCount: number;
bwEstimate: number;
loading: { start: number; first: number; end: number };
parsing: { start: number; end: number };
buffering: { start: number; first: number; end: number };
}
// Level details and streaming metadata
interface LevelDetails {
readonly endSN: number;
readonly startSN: number;
readonly fragments: Fragment[];
readonly totalduration: number;
readonly averagetargetduration: number;
readonly type: string;
readonly live: boolean;
readonly m3u8: string;
readonly version: number | null;
}
// Date range for timed metadata
interface DateRange {
readonly id: string;
readonly startDate: Date;
readonly endDate?: Date;
readonly duration?: number;
readonly plannedDuration?: number;
readonly class?: string;
readonly endOnNext?: boolean;
}
// Level encryption key
interface LevelKey {
readonly method: string;
readonly uri?: string;
readonly iv?: Uint8Array;
readonly keyFormat?: string;
readonly keyFormatVersions?: string;
}
// HLS-specific types
interface HlsUrlParameters {
[key: string]: string;
}
interface HlsSkip {
skippedSegments: number;
recentlyRemovedDateranges: string[];
}
// Playlist level type enum
enum PlaylistLevelType {
MAIN = "main",
AUDIO = "audio",
SUBTITLE = "subtitle"
}
// Metadata schema
enum MetadataSchema {
dateRange = "com.apple.quicktime.HLS.dateRange",
emsg = "https://aomedia.org/emsg/ID3"
}
// Transmuxer chunk metadata
interface ChunkMetadata {
readonly level: number;
readonly sn: number;
readonly part: number;
readonly partial: boolean;
readonly chunkIndex: number;
}
// Error handling
interface NetworkErrorAction {
action: number;
flags: ErrorActionFlags;
retryCount?: number;
retryConfig?: any;
}
interface ErrorActionFlags {
[key: string]: boolean;
}