### Clone Repository and Install Dependencies Source: https://github.com/video-dev/hls.js/blob/master/README.md Clone the HLS.js repository and install all required project dependencies using npm ci. This is the initial setup step for development. ```sh git clone https://github.com/video-dev/hls.js.git cd hls.js # After cloning or pulling from the repository, make sure all dependencies are up-to-date npm install ci ``` -------------------------------- ### startLevel Source: https://github.com/video-dev/hls.js/blob/master/api-extractor/report/hls.js.api.md Gets or sets the initial level to start playback from. This is important for controlling the initial quality of the stream. ```APIDOC ## startLevel ### Description Gets or sets the initial level to start playback from. This is important for controlling the initial quality of the stream. ### Getter ```typescript get startLevel(): number; ``` ### Setter ```typescript set startLevel(newLevel: number); ``` ``` -------------------------------- ### Start HLS Loading Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Manually start loading HLS playlists and fragments. This is necessary when `config.autoStartLoad` is set to `false`. The `startPosition` parameter allows overriding the default start time, and `skipSeekToStartPosition` prevents seeking when media is appended. ```javascript hls.startLoad(); // or with startPosition hls.startLoad(30.5); // or with startPosition and skipSeekToStartPosition hls.startLoad(30.5, true); ``` -------------------------------- ### startLoad Source: https://github.com/video-dev/hls.js/blob/master/api-extractor/report/hls.js.api.md Starts loading the media stream. Optionally, you can specify a starting position and whether to skip seeking to it. ```APIDOC ## startLoad ### Description Starts loading the media stream. Optionally, you can specify a starting position and whether to skip seeking to it. ### Signature ```typescript startLoad(startPosition?: number, skipSeekToStartPosition?: boolean): void; ``` ``` -------------------------------- ### startLoad Source: https://github.com/video-dev/hls.js/blob/master/api-extractor/report/hls.js.api.md Starts loading the HLS stream from a specified position. ```APIDOC ## startLoad ### Description Starts loading the HLS stream from a specified position. ### Method (Not applicable, this is a method call) ### Endpoint (Not applicable, this is a method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **startPosition** (number) - The time in seconds from which to start loading the stream. ### Request Example ```javascript hls.startLoad(0); // Start loading from the beginning ``` ### Response None ``` -------------------------------- ### hls.startLevel Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Gets or sets the start level index for the first fragment. If -1, automatic start level selection based on bandwidth is used. ```APIDOC ## hls.startLevel ### Description Gets or sets the start level index (index of the first fragment that will be played back). If not overridden by user, the first level appearing in the manifest will be used. If set to -1, automatic start level selection is enabled, and playback will start from the level matching download bandwidth (determined from the download of the first segment). Default value is `hls.firstLevel`. ### Property `startLevel` ### Type number ``` -------------------------------- ### Install HLS.js with npm Source: https://github.com/video-dev/hls.js/blob/master/README.md Install HLS.js as a project dependency using npm. This is the recommended method for most projects. ```sh npm install --save hls.js ``` -------------------------------- ### hls.startPosition Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Gets the resolved start position target used for loading before media is buffered, and where playback will begin once media is buffered. ```APIDOC ## hls.startPosition ### Description get : Returns the resolved `startPosition` target (number) used for loading before media is buffered, and where playback will begin once media is buffered. ### Type Getter ``` -------------------------------- ### loadSource Source: https://github.com/video-dev/hls.js/blob/master/api-extractor/report/hls.js.api.md Loads and starts playback of a media source URL. ```APIDOC ## loadSource ### Description Loads the media source from the given URL and begins the playback process. This method should be called after `attachMedia`. ### Method `loadSource(url: string): void` ### Parameters * **url** (string) - The URL of the media source (e.g., an HLS manifest file). ``` -------------------------------- ### audioPreference Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Set a preference for selecting the best matching audio track on start. ```APIDOC ## audioPreference ### Description Specifies a preference for selecting the most suitable audio track when playback starts. This can influence the initial level selection based on available audio groups. ### Parameters - `audioPreference` (MediaPlaylist | AudioSelectionOption | undefined) - A value representing the desired audio track, track fields to match, or `undefined` to let HLS.js auto-select. ### Behavior - If set, HLS.js attempts to match the preference. - If `undefined` or not set, HLS.js automatically selects a default audio track. ``` -------------------------------- ### Get Current Start Position Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Retrieves the resolved `startPosition` target used for loading before media is buffered and where playback will begin. ```javascript const currentStartPosition = hls.startPosition; ``` -------------------------------- ### Install HLS.js Canary Channel Source: https://github.com/video-dev/hls.js/blob/master/README.md Install the canary version of HLS.js from the development branch if you prefer to work with the latest unreleased code. ```sh npm install hls.js@canary ``` -------------------------------- ### startLevel Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Set a default start level for playback. The value should be between 0 and the maximum index of `hls.levels`. ```APIDOC ## startLevel ### Description When set, use this level as the default `hls.startLevel`. Keep in mind that the `startLevel` set with the API takes precedence over the `config.startLevel` configuration parameter. ### Default Value `undefined` ### Behavior `startLevel` should be set to a value between 0 and the maximum index of `hls.levels`. ``` -------------------------------- ### Hls.Events.MANIFEST_LOADING Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Fired to signal that a manifest loading is starting. The data includes the manifest URL. ```APIDOC ## Hls.Events.MANIFEST_LOADING ### Description Fired to signal that a manifest loading starts. ### Event Data - `url`: The URL of the manifest being loaded. ### Usage Example ```javascript hls.on(Hls.Events.MANIFEST_LOADING, function(event, data) { console.log('Manifest loading:', data.url); }); ``` ``` -------------------------------- ### Configure XHR Setup for Default Loader Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Use `xhrSetup` to customize `XMLHttpRequest` instances before sending requests. This is useful for setting credentials or modifying headers. ```javascript var config = { xhrSetup: function (xhr, url) { xhr.withCredentials = true; // do send cookies }, }; ``` -------------------------------- ### subtitlePreference Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Set a preference for selecting the best matching subtitle track on start. ```APIDOC ## subtitlePreference ### Description Specifies a preference for selecting the most suitable subtitle track when playback starts. If not set, subtitles are not enabled unless a default or forced option exists. ### Parameters - `subtitlePreference` (MediaPlaylist | SubtitleSelectionOption | undefined) - A value representing the desired subtitle track, track fields to match, or `undefined` to disable automatic subtitle selection. ### Behavior - If set, HLS.js attempts to match the preference. - If `undefined` or not set, HLS.js will not enable subtitles by default, unless a default or forced subtitle track is present. ``` -------------------------------- ### hls.startLoad Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Starts or restarts playlist and fragment loading. This method is effective only after the MANIFEST_PARSED event has been triggered. It allows for manual control over the loading process, especially when autoStartLoad is disabled. ```APIDOC ## hls.startLoad(startPosition=-1, skipSeekToStartPosition=false) ### Description Start/restart playlist/fragment loading. This is only effective if MANIFEST_PARSED event has been triggered. startPosition is the initial position in the playlist. If startPosition is not set to -1, it allows to override default startPosition to the one you want (it will bypass hls.config.liveSync* config params for Live for example, so that user can start playback from whatever position). Once media is appended HLS.js will seek to the start position. Passing in a `skipSeekToStartPosition` of `true` allows loading to begin at the start position without seeking on append. This is used when multiple players contribute to buffering media to the same source for Interstitials that overlap primary content. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method None (JavaScript method) ### Endpoint None (JavaScript method) ### Parameters - **startPosition** (number) - Optional - The initial position in the playlist. Defaults to -1. - **skipSeekToStartPosition** (boolean) - Optional - If true, allows loading to begin at the start position without seeking on append. Defaults to false. ``` -------------------------------- ### Build All Production Flavors Source: https://github.com/video-dev/hls.js/blob/master/README.md Build all HLS.js flavors suitable for production deployment and CI environments. This command also installs dependencies. ```sh npm install ci npm run build ``` -------------------------------- ### Customize Media Key System Access Request Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Customize the window.navigator.requestMediaKeySystemAccess function to map key-system access requests, for example, to a recommended alternative like 'com.microsoft.playready.recommendation'. ```javascript var hls new Hls({ requestMediaKeySystemAccessFunc: (keySystem, supportedConfigurations) => { if (keySystem === 'com.microsoft.playready') { keySystem = 'com.microsoft.playready.recommendation'; } return navigator.requestMediaKeySystemAccess(keySystem, supportedConfigurations); } }); ``` -------------------------------- ### Run Development Server Source: https://github.com/video-dev/hls.js/blob/master/README.md Start the development server to host the demo page. The server recompiles on file changes and hosts files on port 8000. Access the demo at http://localhost:8000/demo/. ```sh # Run dev-server for demo page (recompiles on file-watch, but doesn't write to actual dist fs artifacts) npm run dev ``` -------------------------------- ### Set HLS Default Configuration Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md You can modify HLS.js default configurations globally. This example shows how to set `capLevelToPlayerSize` to true. ```javascript Hls.DefaultConfig.capLevelToPlayerSize = true; ``` -------------------------------- ### fetchSetup Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Fetch customization callback for the Fetch-based loader. ```APIDOC ## fetchSetup ### Description A callback function to customize Fetch API requests. It allows modification of the `Request` object and its initialization parameters. ### Parameters - `context` (object) - Contains request context information, including `context.url`. - `initParams` (object) - The Request init parameters object. ### Behavior - If `fetchSetup` is specified and the Fetch loader is used, this function is triggered to instantiate the `Request` object. - It allows users to easily tweak Fetch loader behavior. ### Example ```js var config = { fetchSetup: function (context, initParams) { // Always send cookies, even for cross-origin calls. initParams.credentials = 'include'; return new Request(context.url, initParams); }, }; ``` ``` -------------------------------- ### startPosition Source: https://github.com/video-dev/hls.js/blob/master/api-extractor/report/hls.js.api.md Gets the current start position for loading. This property indicates where the stream loading is intended to begin. ```APIDOC ## startPosition ### Description Gets the current start position for loading. This property indicates where the stream loading is intended to begin. ### Getter ```typescript get startPosition(): number; ``` ``` -------------------------------- ### xhrSetup Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md XMLHttpRequest customization callback for the default XHR-based loader. ```APIDOC ## xhrSetup ### Description A callback function to customize `XMLHttpRequest` instances before sending a request. It allows modification of the XHR object, and optionally returning a Promise to delay the request. ### Parameters - `xhr` (XMLHttpRequest) - The XMLHttpRequest object to customize. - `url` (string) - The URL being requested. ### Behavior - If `xhrSetup` is specified, it's invoked before `xhr.send()`. - `xhr.open()` should be called within `xhrSetup` if modifications require it. - If `xhrSetup` throws an error, it's caught, and `xhrSetup` is called again after opening a GET request. ### Example ```js var config = { xhrSetup: function (xhr, url) { xhr.withCredentials = true; // do send cookies }, }; ``` ``` -------------------------------- ### Create and Manage I-Frame Player Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md This example demonstrates how to create an I-Frame only HLS player instance, attach it to a secondary video element, and handle events like level updates and fragment buffering. It also shows how to load media at specific times and handle potential errors. ```typescript const mainVideo = document.getElementById('video_1'); const iframeVideo = document.getElementById('video_2'); const hls = new Hls(); let hlsIframesOnly: HlsIFramesOnly | null = null; hls.loadSource('http://example.com/primary.m3u8'); hls.attachMedia(mainVideo); // IFrame players can be created as early as MANIFEST_LOADED, but it is best to wait until after media is loaded to make sure frames are synched. hls.once(Events.INIT_PTS_FOUND, createHlsIframesOnlyIfNeeded); function createHlsIframesOnlyIfNeeded() { if (hls.url !== hlsIframesOnly?.url) { // If player was destroyed or asset url changed, remove reference. // (IFrames instance is destroyed when another source is loaded by parent Hls instance.) hlsIframesOnly = null; } if (!hlsIframesOnly && hls.iframeVariants.length) { hlsIframesOnly = hls.createIFramePlayer(); if (hlsIframesOnly) { hlsIframesOnly.attachMedia(iframeVideo); // Load the level that matches the current video element dimensions. hlsIframesOnly.startLoad(); hlsIframesOnly.once( Events.LEVEL_UPDATED, (name, { details: { fragments } }) => { /* fragments contains all iframe start times and durations */ }, ); hlsIframesOnly.on(Events.FRAG_BUFFERED, (name, { frag }) => { /* iframe buffered */ }); hlsIframesOnly.on(Events.ERROR, (name, { error }) => { if (error.name == 'QuotaExceededError') { /* MSE buffer is full */ } }); } } } function renderIFrame(currentTime) { iframeVideo.onseeked = () => null /* iframe rendered > show iframe video element and remove seeked listener */; hlsIframesOnly?.loadMediaAt(currentTime); } function preloadIFrame(time) { hlsIframesOnly?.loadMediaAt(time, { seekOnAppend: false }); } ``` -------------------------------- ### Build and Watch for Changes Source: https://github.com/video-dev/hls.js/blob/master/README.md Build HLS.js artifacts and enable watch mode. This is useful for custom development setups where you need to host the build through another server. ```sh npm run build:watch ``` -------------------------------- ### Configure Fetch Setup for Fetch Loader Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Use `fetchSetup` to customize the `Request` object and `init` parameters for the Fetch-based loader. This allows for setting credentials or modifying request headers. ```javascript var config = { fetchSetup: function (context, initParams) { // Always send cookies, even for cross-origin calls. initParams.credentials = 'include'; return new Request(context.url, initParams); }, }; ``` -------------------------------- ### Get Integrated Timeline Position and Ranges Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Access the current playback position within the integrated timeline and map out the start and end times of scheduled interstitial events. This is helpful for displaying progress bars or event markers. ```javascript const currentTime = hls.interstitialsManager.integrated.currentTime; const timelineRanges = hls.interstitialsManager.schedule.map((item) => { return { interstitial: item.event, start: item.integrated.start, end: item.integrated.end, }; }); ``` -------------------------------- ### Instantiate Hls Object and Bind to Video Element Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md This snippet shows the basic setup for HLS.js, including creating an Hls instance and attaching it to a video element. Ensure the Hls.js library is included before this code. ```javascript var video = document.getElementById('video'); var hls = new Hls(); hls.attachMedia(video); ``` -------------------------------- ### hls.levels Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Gets an array of available quality levels. ```APIDOC ## hls.levels ### Description Gets an array of available quality levels. ### Property `levels` ### Type Array ``` -------------------------------- ### Load HLS Manifest Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md After setting up the Hls instance and binding it to a video element, load the HLS manifest URL. This initiates the streaming process. ```javascript hls.loadSource('https://test.com/stream.m3u8'); ``` -------------------------------- ### Instantiate HLS with Custom Configuration Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Provide a configuration object when creating a new HLS instance to customize playback. This includes settings for buffer management, adaptive bitrate, error handling, and more. ```javascript var config = { autoStartLoad: true, startPosition: -1, debug: false, capLevelOnFPSDrop: false, capLevelToPlayerSize: false, defaultAudioCodec: undefined, initialLiveManifestSize: 1, maxBufferLength: 30, maxMaxBufferLength: 600, backBufferLength: Infinity, frontBufferFlushThreshold: Infinity, maxBufferSize: 60 * 1000 * 1000, maxBufferHole: 0.1, highBufferWatchdogPeriod: 2, nudgeOffset: 0.1, nudgeMaxRetry: 3, maxFragLookUpTolerance: 0.25, liveSyncDurationCount: 3, liveSyncOnStallIncrease: 1, liveMaxLatencyDurationCount: Infinity, liveDurationInfinity: false, preferManagedMediaSource: false, enableWorker: true, enableSoftwareAES: true, fragLoadPolicy: { default: { maxTimeToFirstByteMs: 9000, maxLoadTimeMs: 100000, timeoutRetry: { maxNumRetry: 2, retryDelayMs: 0, maxRetryDelayMs: 0, }, errorRetry: { maxNumRetry: 5, retryDelayMs: 3000, maxRetryDelayMs: 15000, backoff: 'linear', }, }, }, startLevel: undefined, audioPreference: { characteristics: 'public.accessibility.describes-video', }, subtitlePreference: { lang: 'en-US', }, startFragPrefetch: false, testBandwidth: true, progressive: false, lowLatencyMode: true, fpsDroppedMonitoringPeriod: 5000, fpsDroppedMonitoringThreshold: 0.2, appendErrorMaxRetry: 3, loader: customLoader, fLoader: customFragmentLoader, pLoader: customPlaylistLoader, xhrSetup: XMLHttpRequestSetupCallback, fetchSetup: FetchSetupCallback, abrController: AbrController, bufferController: BufferController, capLevelController: CapLevelController, fpsController: FPSController, timelineController: TimelineController, enableDateRangeMetadataCues: true, enableMetadataCues: true, enableID3MetadataCues: true, enableWebVTT: true, enableIMSC1: true, enableCEA708Captions: true, stretchShortVideoTrack: false, maxAudioFramesDrift: 1, forceKeyFrameOnDiscontinuity: true, handleMpegTsVideoIntegrityErrors: 'process', abrEwmaFastLive: 3.0, abrEwmaSlowLive: 9.0, abrEwmaFastVoD: 3.0, abrEwmaSlowVoD: 9.0, abrEwmaDefaultEstimate: 500000, abrEwmaDefaultEstimateMax: 5000000, abrBandWidthFactor: 0.95, abrBandWidthUpFactor: 0.7, abrMaxWithRealBitrate: false, abrSwitchInterval: 0, maxStarvationDelay: 4, maxLoadingDelay: 4, minAutoBitrate: 0, emeEnabled: false, licenseXhrSetup: undefined, drmSystems: {}, drmSystemOptions: {}, requestMediaKeySystemAccessFunc: requestMediaKeySystemAccess, cmcd: { sessionId: uuid(), contentId: hash(contentURL), useHeaders: false, }, }; var hls = new Hls(config); ``` -------------------------------- ### state Source: https://github.com/video-dev/hls.js/blob/master/api-extractor/report/hls.js.api.md Gets or sets the current state of the HLS player. ```APIDOC ## state ### Description Gets or sets the current state of the HLS player. ### Method (Not applicable, this is a property accessor) ### Endpoint (Not applicable, this is a property accessor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Getters * **state** (State) - Returns the current state of the HLS player. ### Setters * **state** (State) - Sets the current state of the HLS player. ### Request Example (Get) ```javascript const currentState = hls.state; console.log(currentState); ``` ### Request Example (Set) ```javascript hls.state = State.PAUSED; ``` ### Response (Get) (Type: State) - The current state of the HLS player. ``` -------------------------------- ### hls.firstLevel Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Gets the index of the first Variant appearing in the Multivariant Playlist. ```APIDOC ## hls.firstLevel ### Description Gets the index of the first Variant appearing in the Multivariant Playlist. ### Property `firstLevel` ### Type number ``` -------------------------------- ### licenseXhrSetup Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md A function to preprocess license requests. It allows modification of the license request URL, headers, and payload before the request is sent, based on operating conditions, key-session, and key-system. ```APIDOC ## licenseXhrSetup ### Description A pre-processor function for modifying license requests. The license request URL, request headers, and payload can all be modified prior to sending the license request, based on operating conditions, the current key-session, and key-system. ### Default Value `undefined` ### Type `(xhr: XMLHttpRequest, url: string, keyContext: MediaKeySessionContext, licenseChallenge: Uint8Array) => void | Uint8Array | Promise` ### Example ```js var config = { licenseXhrSetup: function (xhr, url, keyContext, licenseChallenge) { let payload = licenseChallenge; // Send cookies with request xhr.withCredentials = true; // Call open to change the method (default is POST), modify the url, or set request headers xhr.open('POST', url, true); // call xhr.setRequestHeader after xhr.open otherwise licenseXhrSetup will throw and be called a second time after HLS.js call xhr.open if (keyContext.keySystem === 'com.apple.fps') { xhr.setRequestHeader('Content-Type', 'application/json'); payload = JSON.stringify({ keyData: base64Encode(keyContext.decryptdata?.keyId), licenseChallenge: base64Encode(licenseChallenge), }); } else { xhr.setRequestHeader('Content-Type', 'application/octet-stream'); } // Return the desired payload or a Promise. // Not returning a value, or returning `undefined` or` Promise` will result in the `licenseChallenge` being used. return fetchDRMToken(this.authData).then((result) => { xhr.setRequestHeader('token', token); return payload; }); } }; ``` ``` -------------------------------- ### hls.media Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Gets the currently bound video element from the hls instance. ```APIDOC ## hls.media ### Description Gets the currently bound video element from the hls instance. ### Property `media` ### Type HTMLMediaElement | null ``` -------------------------------- ### Create and Attach Image Player for Thumbnails Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Instantiates an HlsImageIFramesOnly player and attaches an HTMLImageElement to display thumbnail previews. Listen for FRAG_BUFFERED to know when a frame is rendered. ```typescript const mainVideo = document.getElementById('video'); const thumbnailImg = document.getElementById('thumbnail') as HTMLImageElement; const hls = new Hls(); let imagePlayer: HlsImageIFramesOnly | null = null; hls.loadSource('http://example.com/primary.m3u8'); hls.attachMedia(mainVideo); hls.once(Events.MANIFEST_PARSED, () => { imagePlayer = hls.createImageIFramePlayer(); if (imagePlayer) { imagePlayer.attachImage(thumbnailImg); imagePlayer.on(Events.FRAG_BUFFERED, (name, { frag }) => { /* JPEG frame rendered to image element */ }); imagePlayer.on(Events.ERROR, (name, { error }) => { /* handle error */ }); } }); function showThumbnailAtTime(time: number) { imagePlayer?.loadMediaAt(time); } ``` -------------------------------- ### sessionId Source: https://github.com/video-dev/hls.js/blob/master/api-extractor/report/hls.js.api.md Gets the current session ID. This can be useful for tracking playback sessions. ```APIDOC ## sessionId ### Description Gets the current session ID. This can be useful for tracking playback sessions. ### Getter ```typescript get sessionId(): string; ``` ``` -------------------------------- ### hls.audioTrack Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Gets or sets the index of the selected audio track within `hls.audioTracks`. ```APIDOC ## `hls.audioTrack` ### Description Gets or sets the index of the selected audio track in `hls.audioTracks`. ### Method `get`/`set` ### Endpoint `hls.audioTrack` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **index** (number) - Required - The index of the audio track to select. ``` -------------------------------- ### Hls Class Constructor Source: https://github.com/video-dev/hls.js/blob/master/api-extractor/report/hls.js.api.md Initializes a new Hls instance with optional user configuration. ```APIDOC ## Hls Constructor ### Description Creates a new instance of the Hls player. You can provide a partial configuration object to override default settings. ### Parameters * **userConfig** (Partial) - Optional - An object containing configuration options to customize the Hls player's behavior. ``` -------------------------------- ### hls.autoLevelEnabled Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Gets a boolean indicating whether auto level selection is enabled. ```APIDOC ## hls.autoLevelEnabled ### Description Gets a boolean indicating whether auto level selection is enabled or not. ### Property `autoLevelEnabled` ### Type boolean ``` -------------------------------- ### Static Methods Source: https://github.com/video-dev/hls.js/blob/master/api-extractor/report/hls.js.api.md Provides utility methods for checking browser support and accessing default configurations. ```APIDOC ## Static Methods ### `Hls.isSupported()` Checks if the browser supports the necessary Media Source Extensions (MSE) for HLS playback. ### `Hls.isMSESupported()` An alias for `Hls.isSupported()`, checking for MSE support. ### `Hls.getMediaSource()` Returns the `MediaSource` object if supported, otherwise `undefined`. ### `Hls.DefaultConfig` Provides access to the default configuration object for Hls.js. This can be read or modified to set global defaults. ``` -------------------------------- ### Parse Query String and Get Stream Parameter (JavaScript) Source: https://github.com/video-dev/hls.js/blob/master/demo/benchmark.html Parses a query string to extract key-value pairs and retrieves a specific parameter, typically used to get the HLS stream URL from the URL's query parameters. It handles cases where the parameter might be missing. ```javascript function parseQuery(queryString) { var query = {}; var pairs = ( queryString[0] === '?' ? queryString.slice(1) : queryString ).split('&'); for (var i = 0; i < pairs.length; i++) { var pair = pairs[i].split('='); query[decodeURIComponent(pair[0])] = decodeURIComponent( pair[1] || '' ); } return query; } /* get stream from query string */ function getParameterByName(name) { var query = parseQuery(window.location.search); return query.hasOwnProperty(name) ? query[name] : undefined; } ``` -------------------------------- ### HlsPerformanceTiming Interface Source: https://github.com/video-dev/hls.js/blob/master/api-extractor/report/hls.js.api.md Interface for performance timing metrics, including start and end times. ```APIDOC ## Interface: HlsPerformanceTiming ### Description Represents performance timing metrics with start and end properties. ### Properties - **start** (number) - The start time of the event. - **end** (number) - The end time of the event. ``` -------------------------------- ### Creating a Custom Loader Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Guidance on creating custom loaders for HLS.js. ```APIDOC ## Creating a Custom Loader ### Description Instructions and information on how to implement and integrate custom loaders within HLS.js for advanced network handling. ``` -------------------------------- ### Configure MediaKeySystemConfiguration Options Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Specify optional arguments for MediaKeySystemConfiguration to be passed to requestMediaKeySystemAccess, such as robustness, encryption schemes, and session types. ```javascript { audioRobustness: 'SW_SECURE_CRYPTO', videoRobustness: 'SW_SECURE_CRYPTO', audioEncryptionScheme: null, videoEncryptionScheme: null, persistentState: 'not-allowed'; distinctiveIdentifier: 'not-allowed'; sessionTypes: ['temporary']; sessionType: 'temporary'; } ``` -------------------------------- ### playingDate Source: https://github.com/video-dev/hls.js/blob/master/api-extractor/report/hls.js.api.md Gets the current playback date. This property is useful for time-based operations or debugging. ```APIDOC ## playingDate ### Description Gets the current playback date. This property is useful for time-based operations or debugging. ### Getter ```typescript get playingDate(): Date | null; ``` ``` -------------------------------- ### Switch HLS Streams Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md To switch to a different HLS stream, first destroy the current instance and then create a new one, loading the new manifest. Ensure the video element is correctly re-attached. ```javascript hls.destroy(); hls = new Hls(); hls.loadSource('https://new.test.com/stream.m3u8'); hls.attachMedia(video); ``` -------------------------------- ### hls.bufferingEnabled Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Gets a boolean indicating whether fragment loading has been toggled with `pauseBuffering()` and `resumeBuffering()`. ```APIDOC ## hls.bufferingEnabled ### Description get : Returns a boolean indicating whether fragment loading has been toggled with `pauseBuffering()` and `resumeBuffering()`. ### Type Getter ``` -------------------------------- ### hls.firstAutoLevel Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Gets the quality level that will be used to load the first fragment when not overridden by `startLevel`. ```APIDOC ## hls.firstAutoLevel ### Description Gets the quality level that will be used to load the first fragment when not overridden by `startLevel`. ### Property `firstAutoLevel` ### Type number ``` -------------------------------- ### StreamController Methods Source: https://github.com/video-dev/hls.js/blob/master/api-extractor/report/hls.js.api.md Provides methods for controlling the HLS stream playback, such as starting, stopping, and seeking. ```APIDOC ## StreamController ### Description Manages the HLS stream playback, including loading, buffering, and error handling. ### Methods - **immediateLevelSwitch()**: Initiates an immediate switch to the next available level. - **startLoad(startPosition: number, skipSeekToStartPosition?: boolean)**: Starts loading the HLS stream from a specified position. - **stopLoad()**: Stops the HLS stream loading process. - **swapAudioCodec()**: Swaps the current audio codec. - **seekToStartPos()**: Seeks to the initial start position of the stream. ``` -------------------------------- ### Configure Loader Policies Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Customize loader policies to control retry behavior for different resource types. This example sets a timeout retry configuration for fragment loading. ```javascript var config = { fragLoadPolicy: { timeoutRetry: { maxNumRetry: 3, retryDelayMs: 500, maxRetryDelayMs: 5000, backoff: 'exponential' } } }; hls = new Hls(config); hls.loadSource('https://test.com/stream.m3u8'); ``` -------------------------------- ### version Source: https://github.com/video-dev/hls.js/blob/master/api-extractor/report/hls.js.api.md Gets the version of the hls.js library. This static property is useful for version checking and compatibility. ```APIDOC ## version ### Description Gets the version of the hls.js library. This static property is useful for version checking and compatibility. ### Getter ```typescript static get version(): string; ``` ``` -------------------------------- ### subtitleDisplay Source: https://github.com/video-dev/hls.js/blob/master/api-extractor/report/hls.js.api.md Gets or sets the visibility of subtitle display. This controls whether subtitles are shown to the user. ```APIDOC ## subtitleDisplay ### Description Gets or sets the visibility of subtitle display. This controls whether subtitles are shown to the user. ### Getter ```typescript get subtitleDisplay(): boolean; ``` ### Setter ```typescript set subtitleDisplay(value: boolean); ``` ``` -------------------------------- ### Customize License Request with licenseXhrSetup Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Use licenseXhrSetup to modify license requests before they are sent. This allows for custom headers, payloads, and request methods. The function can return a modified payload or a Promise resolving to one. Ensure xhr.open is called before setting headers. ```javascript var config = { licenseXhrSetup: function (xhr, url, keyContext, licenseChallenge) { let payload = licenseChallenge; // Send cookies with request xhr.withCredentials = true; // Call open to change the method (default is POST), modify the url, or set request headers xhr.open('POST', url, true); // call xhr.setRequestHeader after xhr.open otherwise licenseXhrSetup will throw and be called a second time after HLS.js call xhr.open if (keyContext.keySystem === 'com.apple.fps') { xhr.setRequestHeader('Content-Type', 'application/json'); payload = JSON.stringify({ keyData: base64Encode(keyContext.decryptdata?.keyId), licenseChallenge: base64Encode(licenseChallenge), }); } else { xhr.setRequestHeader('Content-Type', 'application/octet-stream'); } // Return the desired payload or a Promise. // Not returning a value, or returning `undefined` or` Promise` will result in the `licenseChallenge` being used. return fetchDRMToken(this.authData).then((result) => { xhr.setRequestHeader('token', token); return payload; }); }, }; ``` -------------------------------- ### pathways Source: https://github.com/video-dev/hls.js/blob/master/api-extractor/report/hls.js.api.md Gets the available pathways. This property provides information about the network pathways that hls.js can utilize. ```APIDOC ## pathways ### Description Gets the available pathways. This property provides information about the network pathways that hls.js can utilize. ### Getter ```typescript get pathways(): string[]; ``` ``` -------------------------------- ### hls.drift Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Gets the rate at which the edge of the current live playlist is advancing. Returns 1 if there is no advancement. ```APIDOC ## `hls.drift` ### Description Gets the rate at which the edge of the current live playlist is advancing. ### Method GET ### Endpoint `hls.drift` ### Returns (number) - The advancement rate of the live playlist edge, or 1 if none. ``` -------------------------------- ### drmSystemOptions Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Defines optional `MediaKeySystemConfiguration` arguments to be passed to `requestMediaKeySystemAccess`. ```APIDOC ## `drmSystemOptions` ### Description Define optional [`MediaKeySystemConfiguration`](https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration) arguments to be passed to `requestMediaKeySystemAccess`. ### Default `{}` ### Example ```js { audioRobustness: 'SW_SECURE_CRYPTO', videoRobustness: 'SW_SECURE_CRYPTO', audioEncryptionScheme: null, videoEncryptionScheme: null, persistentState: 'not-allowed'; distinctiveIdentifier: 'not-allowed'; sessionTypes: ['temporary']; sessionType: 'temporary'; } ``` With the default argument, `''` will be specified for each option (_i.e. no specific robustness required_). ``` -------------------------------- ### Subscribe to HLS Events Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Demonstrates how to subscribe, unsubscribe, and subscribe for a single call to HLS events like LEVEL_LOADED. Ensure Hls instance is available. ```javascript function onLevelLoaded(event, data) { var level_duration = data.details.totalduration; } // subscribe event hls.on(Hls.Events.LEVEL_LOADED, onLevelLoaded); // unsubscribe event hls.off(Hls.Events.LEVEL_LOADED, onLevelLoaded); // subscribe for a single event call only hls.once(Hls.Events.LEVEL_LOADED, onLevelLoaded); ``` -------------------------------- ### hls.url Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Gets the string of the current HLS asset passed to `hls.loadSource()`, or null if no source has been loaded. ```APIDOC ## hls.url ### Description get : string of current HLS asset passed to `hls.loadSource()`, otherwise null ### Type Getter ``` -------------------------------- ### hls.capLevelToPlayerSize Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Gets whether level capping is enabled or disables/enables it. If disabled after being enabled, `nextLevelSwitch` will be called. ```APIDOC ## hls.capLevelToPlayerSize ### Description Gets whether level capping is enabled or disabled. Sets whether level capping is enabled. If disabled after previously enabled, `nextLevelSwitch` will be immediately called. Default value is set via [`capLevelToPlayerSize`](#capleveltoplayersize) in config. ### Property `capLevelToPlayerSize` ### Type boolean ``` -------------------------------- ### Hls.Events.BUFFER_FLUSHING Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Fired when the media buffer should be flushed. The data includes the start and end offsets and the SourceBuffer type. ```APIDOC ## Hls.Events.BUFFER_FLUSHING ### Description Fired when the media buffer should be flushed. ### Event Data - `startOffset`: The start offset for flushing. - `endOffset`: The end offset for flushing. - `type`: The type of SourceBuffer (e.g., 'video', 'audio'). ### Usage Example ```javascript hls.on(Hls.Events.BUFFER_FLUSHING, function(event, data) { console.log('Buffer flushing from', data.startOffset, 'to', data.endOffset, 'for type:', data.type); }); ``` ``` -------------------------------- ### Load Manifest and Bind to Video Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Load a manifest URL using hls.loadSource() and attach the Hls object to the video element. The MANIFEST_PARSED event provides information about the loaded manifest. ```html ``` -------------------------------- ### Network Loading Control API Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md APIs for controlling the start and stop of network loading for HLS segments. ```APIDOC ## Network Loading Control API ### `hls.startLoad(startPosition=-1, skipSeekToStartPosition=false)` Starts or resumes loading HLS segments. If `startPosition` is provided, it attempts to start loading from that time in seconds. `skipSeekToStartPosition` can be used to prevent seeking if the media element is already at the desired position. ### `hls.stopLoad()` Stops the loading of HLS segments. This will pause playback and prevent further segment fetching until `startLoad()` is called again. ``` -------------------------------- ### Initialize Hls.js Player with Native Fallback Source: https://github.com/video-dev/hls.js/blob/master/demo/basic-usage.html This snippet demonstrates how to initialize an Hls.js instance if the browser supports Media Source Extensions. It also includes a fallback mechanism to use the native video element's HLS support when Hls.js is not required. ```javascript var video = document.getElementById('video'); if (Hls.isSupported()) { var hls = new Hls({ debug: true }); hls.loadSource('https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8'); hls.attachMedia(video); hls.on(Hls.Events.MEDIA_ATTACHED, function () { video.muted = true; video.play(); }); } else if (video.canPlayType('application/vnd.apple.mpegurl')) { video.src = 'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8'; video.addEventListener('canplay', function () { video.play(); }); } ``` -------------------------------- ### url Source: https://github.com/video-dev/hls.js/blob/master/api-extractor/report/hls.js.api.md Gets the current media stream URL. This property reflects the URL of the HLS manifest being played. ```APIDOC ## url ### Description Gets the current media stream URL. This property reflects the URL of the HLS manifest being played. ### Getter ```typescript get url(): string | null; ``` ``` -------------------------------- ### createImageIFramePlayer Source: https://github.com/video-dev/hls.js/blob/master/api-extractor/report/hls.js.api.md Creates an Hls instance for playing back I-Frame-only playlists intended for image generation. ```APIDOC ## createImageIFramePlayer ### Description Creates a new Hls instance specifically designed for generating images from I-Frame-only playlists. This is optimized for image extraction tasks. ### Method `createImageIFramePlayer(configOverride?: Partial): HlsImageIFramesOnly | null` ### Parameters * **configOverride** (Partial) - Optional - Configuration options to override the default settings for the image I-Frame player. ``` -------------------------------- ### ttfbEstimate Source: https://github.com/video-dev/hls.js/blob/master/api-extractor/report/hls.js.api.md Gets the Time To First Byte (TTFB) estimate. This metric is useful for network performance analysis. ```APIDOC ## ttfbEstimate ### Description Gets the Time To First Byte (TTFB) estimate. This metric is useful for network performance analysis. ### Getter ```typescript get ttfbEstimate(): number; ``` ``` -------------------------------- ### createIFramePlayer Source: https://github.com/video-dev/hls.js/blob/master/api-extractor/report/hls.js.api.md Creates an Hls instance specifically for playing back I-Frame-only playlists. ```APIDOC ## createIFramePlayer ### Description Creates a new Hls instance configured to handle I-Frame-only playlists. This is useful for scenarios like generating thumbnails or seeking previews. ### Method `createIFramePlayer(configOverride?: Partial): HlsIFramesOnly | null` ### Parameters * **configOverride** (Partial) - Optional - Configuration options to override the default settings for the I-Frame player. ``` -------------------------------- ### nextLevel Source: https://github.com/video-dev/hls.js/blob/master/api-extractor/report/hls.js.api.md Gets or sets the next level to switch to. This property is useful for manually controlling the ABR logic. ```APIDOC ## nextLevel ### Description Gets or sets the next level to switch to. This property is useful for manually controlling the ABR logic. ### Getter ```typescript get nextLevel(): number; ``` ### Setter ```typescript set nextLevel(newLevel: number); ``` ``` -------------------------------- ### InitPTSFoundData Interface Source: https://github.com/video-dev/hls.js/blob/master/api-extractor/report/hls.js.api.md Data structure for when an initialization PTS is found. ```APIDOC ## Interface: InitPTSFoundData ### Description Contains information related to the discovery of an initialization Presentation Time Stamp (PTS). ### Properties - **frag** (MediaFragment) - The media fragment associated with the init PTS. - **id** (PlaylistLevelType) - The ID of the playlist level. - **initPTS** (number) - The initialization PTS value. - **timescale** (number) - The timescale of the media. - **timestampOffsets** (TimestampOffset[]) - An array of timestamp offsets. - **trackId** (number) - The ID of the track. ``` -------------------------------- ### hls.playingDate Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Gets the datetime value relative to `media.currentTime` for the active level Program Date Time, if present. ```APIDOC ## `hls.playingDate` ### Description Gets the datetime value relative to `media.currentTime` for the active level Program Date Time. ### Method GET ### Endpoint `hls.playingDate` ### Returns (Date) - The Program Date Time value if present. ``` -------------------------------- ### Configure DRM License Servers Source: https://github.com/video-dev/hls.js/blob/master/docs/API.md Define license server URLs and optional server certificate URLs for different key systems like Widevine and FairPlay. ```javascript drmSystems: { 'com.apple.fps': { licenseUrl: 'https://your-fps-license-server/path', serverCertificateUrl: 'https://your-fps-license-server/certificate/path', }, 'com.widevine.alpha': { licenseUrl: 'https://your-widevine-license-server/path' } } ```