### Complete HTML Page for Standard dash.js Setup
Source: https://dashif.org/dash.js/pages/quickstart/setup
A comprehensive HTML page demonstrating the standard dash.js player setup. It includes the video element, the dash.js library inclusion, and the manual JavaScript script for player initialization and manifest loading.
```HTML
dash.js Rocks
```
--------------------------------
### Complete HTML Page for Alternative dash.js Setup
Source: https://dashif.org/dash.js/pages/quickstart/setup
A full HTML page demonstrating the alternative dash.js player setup. It leverages the `data-dashjs-player` attribute on the video element, allowing the MediaPlayerFactory to automatically initialize the player when the dash.js library is loaded.
```HTML
Dash.js Rocks
```
--------------------------------
### Complete HTML Page for dash.js ES Module Setup
Source: https://dashif.org/dash.js/pages/quickstart/setup
A full HTML page demonstrating how to set up dash.js using ES Modules directly in the browser. It imports the `MediaPlayer` class from a CDN and then initializes it with a video element and a DASH manifest URL.
```HTML
dash.js Rocks
```
--------------------------------
### Include dash.js Library Script in HTML
Source: https://dashif.org/dash.js/pages/quickstart/setup
Adds the main dash.js library ('dash.all.min.js') to the HTML document, typically by referencing it in a script tag before the closing body tag. This step is essential for both standard and alternative player setups.
```HTML
...
```
--------------------------------
### HTML Video Element for MediaPlayerFactory Auto-Init
Source: https://dashif.org/dash.js/pages/quickstart/setup
Defines an HTML5 video element configured for the alternative dash.js setup using MediaPlayerFactory. The `data-dashjs-player` attribute and `src` pointing to a DASH manifest enable automatic player instantiation upon library load.
```HTML
```
--------------------------------
### Create Basic HTML Video Element for dash.js
Source: https://dashif.org/dash.js/pages/quickstart/setup
Defines a standard HTML5 video element with controls, identified by 'videoPlayer', ready for manual dash.js integration. This element serves as the target for the MediaPlayer instance.
```HTML
```
--------------------------------
### Example Configuration for AbandonRequestRule in dash.js
Source: https://dashif.org/dash.js/pages/usage/abr/abandon-request-rule
This JavaScript example demonstrates how to configure the `AbandonRequestRule` within the dash.js player settings. It shows how to activate the rule and set its `abandonDurationMultiplier`, `minSegmentDownloadTimeThresholdInMs`, and `minThroughputSamplesThreshold` parameters.
```JavaScript
player.updateSettings({
streaming: {
abr: {
rules: {
abandonRequestsRule: {
active: true,
parameters: {
abandonDurationMultiplier: 1.8,
minSegmentDownloadTimeThresholdInMs: 500,
minThroughputSamplesThreshold: 6
}
}
}
}
}
});
```
--------------------------------
### Initialize dash.js in TypeScript/Webpack Project
Source: https://dashif.org/dash.js/pages/quickstart/setup
Demonstrates how to import dash.js and an additional module (like Smooth Streaming) within a TypeScript or Webpack-based JavaScript project. It then proceeds to initialize the MediaPlayer with a manifest URL, targeting a video element.
```TypeScript
import * as dashjs from 'dashjs';
import '../node_modules/dashjs/dist/modern/esm/dash.mss.min.js';
let url = "https://playready.directtaps.net/smoothstreaming/SSWSS720H264/SuperSpeedway_720.ism/Manifest";
let player = dashjs.MediaPlayer().create();
player.initialize(document.querySelector('#myMainVideoPlayer'), url, true);
```
--------------------------------
### Initialize dash.js MediaPlayer Manually
Source: https://dashif.org/dash.js/pages/quickstart/setup
Initializes the dash.js MediaPlayer instance programmatically. It creates a player, associates it with a specific video element using its ID, and loads a DASH manifest URL for playback. The third parameter enables auto-play.
```JavaScript
var url = "https://dash.akamaized.net/envivio/EnvivioDash3/manifest.mpd";
var player = dashjs.MediaPlayer().create();
player.initialize(document.querySelector("#videoPlayer"), url, true);
```
--------------------------------
### Example Functional Test in dash.js
Source: https://dashif.org/dash.js/pages/testing/functional-test
This JavaScript snippet demonstrates a typical functional test structure in dash.js. It initializes a player adapter, plays a DASH manifest, and asserts that the player transitions to a playing state, progresses playback, and does not encounter critical errors. The test uses common utility functions for setup and assertions.
```JavaScript
import Constants from '../../src/Constants.js';
import Utils from '../../src/Utils.js';
import {
checkIsPlaying,
checkIsProgressing,
checkNoCriticalErrors,
initializeDashJsAdapter
} from '../common/common.js';
const TESTCASE = Constants.TESTCASES.PLAYBACK.PLAY;
Utils.getTestvectorsForTestcase(TESTCASE).forEach((item) => {
const mpd = item.url;
describe(`${TESTCASE} - ${item.name} - ${mpd}`, () => {
let playerAdapter;
before(() => {
playerAdapter = initializeDashJsAdapter(item, mpd);
})
after(() => {
playerAdapter.destroy();
})
it(`Checking playing state`, async () => {
await checkIsPlaying(playerAdapter, true);
})
it(`Checking progressing state`, async () => {
await checkIsProgressing(playerAdapter);
});
it(`Expect no critical errors to be thrown`, () => {
checkNoCriticalErrors(playerAdapter);
})
})
})
```
--------------------------------
### Build dash.js Distribution Files
Source: https://dashif.org/dash.js/pages/quickstart/installation
A sequence of bash commands to set up the dash.js project locally and generate its distribution files. This includes cloning the official repository, checking out the master branch, installing all necessary Node.js dependencies, and finally running the build script.
```bash
git clone https://github.com/Dash-Industry-Forum/dash.js.git
```
```bash
git checkout -b master origin/master
```
```bash
npm install
```
```bash
npm run build
```
--------------------------------
### Initialize dash.js Player and Seek Example
Source: https://dashif.org/dash.js/pages/usage/timing-apis
Demonstrates how to initialize the dash.js MediaPlayer with a video element and a content URL, then perform a basic seek operation to a specific time using the `seek()` method.
```JavaScript
var video = document.querySelector('video');
var player = dashjs.MediaPlayer().create();
player.initialize(video, url, false);
player.seek(10)
```
--------------------------------
### MPD EventStream Element Example
Source: https://dashif.org/dash.js/pages/usage/event-handling
Illustrates an example of an `EventStream` element in an MPD, showing how events of the same type are grouped and signaled directly within the MPD, including event duration and presentation time.
```XML
someMessage
```
--------------------------------
### dash.js Live Playback Seek Relative to DVR Window Start
Source: https://dashif.org/dash.js/pages/usage/timing-apis
Illustrates how to use the `seek()` method in dash.js for live content to seek a specific duration relative to the DVR window's start. This example calculates a seek point 20 seconds behind the live edge by subtracting from the total duration.
```JavaScript
var video = document.querySelector('video');
var player = dashjs.MediaPlayer().create();
player.initialize(video, url, false);
var duration = player.duration()
player.seek(duration - 20);
```
--------------------------------
### Install dash.js 4.0.0-npm via npm
Source: https://dashif.org/dash.js/pages/developers/migration-guides/3-to-4
This command installs the corrected version of dash.js, 4.0.0-npm, from the npm registry. This specific version was published to address a configuration error with the original 4.0.0 tag, ensuring developers can access the intended release.
```npm
npm install dashjs@4.0.0-npm
```
--------------------------------
### Example SupplementalProperty Descriptor for DVB Font Download
Source: https://dashif.org/dash.js/pages/usage/subtitles-and-captions/dvb-font-downloading
This XML snippet provides a complete example of a `SupplementalProperty` descriptor used to signal a downloadable font within an MPD. It specifies the DVB font download scheme, a value of '1', and includes the `dvb:url`, `dvb:fontFamily`, and `dvb:mimeType` attributes to define the font resource.
```XML
```
--------------------------------
### Include vtt.js Library
Source: https://dashif.org/dash.js/pages/usage/subtitles-and-captions/custom-webvtt-rendering
Includes the `vtt.js` library, a dependency located in the dash.js `contrib` folder, which is necessary for custom WebVTT rendering functionality.
```HTML
```
--------------------------------
### Example Calculation of New Playback Rate in dash.js
Source: https://dashif.org/dash.js/pages/usage/low-latency
This JavaScript example demonstrates how the new playback rate is calculated given specific parameters for `cpr`, `delta latency`, and `d`. It illustrates the application of the core formula to determine the adjusted rate when the current latency exceeds the target.
```JavaScript
cpr = 0.5
delta latency = current latency - target latency = 5 - 2 = 3
d = delta latency * 5 = 3 * 5 = 15
s = (cpr * 2) / (1 + Math.pow(Math.E, -d)) = (0.5 * 2) / (1 + 3.0590232050182605e-7) = 0.999999694097773
new rate = (1 - cpr) + s = (1 - 0.5) + 0.999999694097773 = 1.499999694097773
```
--------------------------------
### Set Initial Bitrate for Audio/Video in dash.js
Source: https://dashif.org/dash.js/pages/usage/abr/settings
Shows how to define the initial bitrate for audio or video tracks before playback begins. The `initialBitrate` setting, specified in kilobits per second (kbps), allows applications to control the starting quality of the stream.
```JavaScript
player.updateSettings({
streaming: {
abr: {
initialBitrate: { audio: -1, video: 800 }
}
}
});
```
--------------------------------
### Migrate getDVRWindowSize() to getDvrWindow()
Source: https://dashif.org/dash.js/pages/developers/migration-guides/4-to-5
The `getDVRWindowSize()` method in dash.js v4 has been removed. Use `getDvrWindow()` instead to obtain information about the current DVR window, including its start time, end time, and size.
```APIDOC
v4: `getDVRWindowSize()`
v5: `getDvrWindow()`
Description: Returns information about the current DVR window including the start time, the end time, the window size.
```
--------------------------------
### APIDOC: dash.js Buffer Configuration Options
Source: https://dashif.org/dash.js/pages/usage/buffer-management
This section describes the various configuration options available for managing the media buffer within the dash.js player. It details parameters such as `initialBufferLevel`, `bufferToKeep`, and different `bufferTime` settings, along with their purpose and application for various quality levels and content types.
```APIDOC
Buffer Configuration Options:
initialBufferLevel:
Description: Initial buffer level to be reached before playback is automatically started.
Note: Applies only at playback start, not after seek or buffer dry.
bufferToKeep:
Description: Defines how much backward buffer to keep (behind current play position).
bufferTimeDefault:
Description: Forward buffer target when not playing at top quality.
bufferTimeAtTopQuality:
Description: Forward buffer target when playing the top quality. dash.js tries to build a larger buffer at top quality for stability.
bufferTimeAtTopQualityLongForm:
Description: Forward buffer target when playing the top quality for long form content.
longFormContentDurationThreshold:
Description: Threshold defining if media is considered long form content, affecting top quality buffer targets.
```
--------------------------------
### Example dash.js UTC Synchronization Configuration
Source: https://dashif.org/dash.js/pages/usage/clock-sync
Demonstrates a complete JavaScript configuration object for UTC Time synchronization in dash.js, showing how to set various parameters like `enable`, `backgroundAttempts`, and `defaultTimingSource` within the player's settings.
```javascript
player.updateSettings({
streaming: {
utcSynchronization: {
enable: true,
useManifestDateHeaderTimeSource: true,
backgroundAttempts: 2,
timeBetweenSyncAttempts: 30,
maximumTimeBetweenSyncAttempts: 600,
minimumTimeBetweenSyncAttempts: 2,
timeBetweenSyncAttemptsAdjustmentFactor: 2,
maximumAllowedDrift: 100,
enableBackgroundSyncAfterSegmentDownloadError: true,
defaultTimingSource: {
scheme: 'urn:mpeg:dash:utc:http-xsdate:2014',
value: 'http://time.akamai.com/?iso&ms'
}
}
}
})
```
--------------------------------
### Configure dash.js Buffer Settings via updateSettings
Source: https://dashif.org/dash.js/pages/usage/buffer-management
This JavaScript example demonstrates how to programmatically modify the default buffer settings in a dash.js player instance. It utilizes the `player.updateSettings()` method to adjust key buffer parameters such as `bufferTimeAtTopQuality`, `bufferTimeAtTopQualityLongForm`, `bufferTimeDefault`, and `longFormContentDurationThreshold`.
```JavaScript
player.updateSettings({
streaming: {
buffer: {
bufferTimeAtTopQuality: 20,
bufferTimeAtTopQualityLongForm: 30,
bufferTimeDefault: 10,
longFormContentDurationThreshold: 300
}
}
});
```
--------------------------------
### MPD InbandEventStream Element Example
Source: https://dashif.org/dash.js/pages/usage/event-handling
Demonstrates the XML structure for signaling an InbandEventStream element within an MPD, specifying the schemeIdUri and value for inband events.
```XML
```
--------------------------------
### Example of Parsed ID3 Message Data
Source: https://dashif.org/dash.js/pages/usage/event-handling
Illustrates the structure of `event.messageData` (raw ID3 data) and `event.parsedMessageData` (parsed ID3 frames) when `dash.js` processes ID3 time metadata for inband events, specifically showing a 'PRIV' frame example.
```JavaScript
event.messageData = Uint8Array(89)[...]
event.parsedMessageData = [
{
"key": "PRIV",
"info": "com.elementaltechnologies.timestamp.utc",
"data": {}
}
]
```
--------------------------------
### Attach HTML Container to dash.js Player
Source: https://dashif.org/dash.js/pages/usage/subtitles-and-captions/custom-webvtt-rendering
Attaches the previously defined HTML `
` element (identified by its ID) to the dash.js player instance, linking it for custom WebVTT rendering.
```JavaScript
let vttRenderingDiv = document.querySelector("#vtt-rendering-div");
player.attachVttRenderingDiv(vttRenderingDiv)
```
--------------------------------
### Enable Custom WebVTT Rendering in dash.js
Source: https://dashif.org/dash.js/pages/usage/subtitles-and-captions/custom-webvtt-rendering
Configures the dash.js player settings to enable custom WebVTT rendering by setting `customRenderingEnabled` to true within the streaming text options.
```JavaScript
player.updateSettings({
streaming: {
text: {
webvtt: {
customRenderingEnabled: true
}
}
}
})
```
--------------------------------
### Define MediaPlayer Playback and Manifest Events
Source: https://dashif.org/dash.js/pages/developers/migration-guides/3-to-4
Defines various event constants used within the MediaPlayer, including playback status (progress, rate changes, seeking, stalling, starting, time updates, waiting), manifest validity changes, and event mode triggers (on start, on receive), as well as conformance violations and representation switches.
```JavaScript
this.PLAYBACK_PROGRESS = 'playbackProgress';
this.PLAYBACK_RATE_CHANGED = 'playbackRateChanged';
this.PLAYBACK_SEEKED = 'playbackSeeked';
this.PLAYBACK_SEEKING = 'playbackSeeking';
this.PLAYBACK_SEEK_ASKED = 'playbackSeekAsked';
this.PLAYBACK_STALLED = 'playbackStalled';
this.PLAYBACK_STARTED = 'playbackStarted';
this.PLAYBACK_TIME_UPDATED = 'playbackTimeUpdated';
this.PLAYBACK_WAITING = 'playbackWaiting';
this.MANIFEST_VALIDITY_CHANGED = 'manifestValidityChanged';
this.EVENT_MODE_ON_START = 'eventModeOnStart';
this.EVENT_MODE_ON_RECEIVE = 'eventModeOnReceive';
this.CONFORMANCE_VIOLATION = 'conformanceViolation';
this.REPRESENTATION_SWITCH = 'representationSwitch';
```
--------------------------------
### Set Initial Audio Track by Language in dash.js
Source: https://dashif.org/dash.js/pages/usage/track-selection
This snippet demonstrates how to initialize the dash.js player and specify an initial audio track based on its language code using the `setInitialMediaSettingsFor` function. This ensures the player starts with the desired audio stream.
```JavaScript
player.initialize(videoElement, url, true);
player.setInitialMediaSettingsFor('audio', {
lang: 'et-ET'
});
```
--------------------------------
### Example CMAF Chunk Structure for Low Latency
Source: https://dashif.org/dash.js/pages/usage/low-latency
This example illustrates the internal structure of CMAF segments designed for low latency, showing multiple 'moof' (Movie Fragment) and 'mdat' (Media Data) boxes. This multi-box per segment structure is crucial for enabling rapid processing and delivery of media fragments, supporting the low latency requirements.
```text
[styp] size=8+16
[prft] size=8+24
[moof] size=8+96
[mfhd] size=12+4
sequence number = 827234
[traf] size=8+72
[tfhd] size=12+16, flags=20038
track ID = 1
default sample duration = 1001
default sample size = 15704
default sample flags = 1010000
[tfdt] size=12+8, version=1
base media decode time = 828060233
[trun] size=12+12, flags=5
sample count = 1
data offset = 112
first sample flags = 2000000
[mdat] size=8+15704
[prft] size=8+24
[moof] size=8+92
[mfhd] size=12+4
sequence number = 827235
[traf] size=8+68
[tfhd] size=12+16, flags=20038
track ID = 1
default sample duration = 1001
default sample size = 897
default sample flags = 1010000
[tfdt] size=12+8, version=1
base media decode time = 828061234
[trun] size=12+8, flags=1
sample count = 1
data offset = 108
[mdat] size=8+897
```
--------------------------------
### Initialize dash.js Player and Retrieve Current Playback Time
Source: https://dashif.org/dash.js/pages/usage/timing-apis
This JavaScript snippet demonstrates how to initialize the dash.js MediaPlayer, associate it with an HTML video element, load a DASH manifest URL, and then query the current playback time using the player's API. It showcases basic player setup and interaction.
```JavaScript
var video = document.querySelector('video');
var player = dashjs.MediaPlayer().create();
player.initialize(video, url, false);
var time = player.time();
```
--------------------------------
### Storing Chunk Download Times for Moof-based Throughput Estimation
Source: https://dashif.org/dash.js/pages/usage/low-latency
Demonstrates the JavaScript logic for recording start and end timestamps of individual CMAF chunks (moof/mdat boxes) during download. This approach is used by the moof-based throughput estimation algorithm in dash.js.
```javascript
// Store the start time of each chunk download
const flag1 = boxParser.parsePayload(['moof'], remaining, offset);
if (flag1.found) {
// Store the beginning time of each chunk download
startTimeData.push({
ts: performance.now(),
bytes: value.length
});
}
const boxesInfo = boxParser.findLastTopIsoBoxCompleted(['moov', 'mdat'], remaining, offset);
if (boxesInfo.found) {
const end = boxesInfo.lastCompletedOffset + boxesInfo.size;
// Store the end time of each chunk download
endTimeData.push({
ts: performance.now(),
bytes: remaining.length
});
}
```
--------------------------------
### Example MPEG-DASH Manifest for LCEVC Enhanced Content
Source: https://dashif.org/dash.js/pages/usage/lcevc
This XML snippet presents a sample MPEG-DASH Media Presentation Description (MPD) file. It illustrates the structure for defining audio and video adaptation sets, specifically showcasing how LCEVC (Low Complexity Enhancement Video Coding) content is represented with its unique codec ('lvc1') and dependency IDs for scalable video streams. The manifest includes details like media presentation duration, segment templates, and representation properties.
```xml
dash/
...
...
...
```
--------------------------------
### Add HTML Container for WebVTT Rendering
Source: https://dashif.org/dash.js/pages/usage/subtitles-and-captions/custom-webvtt-rendering
Provides an HTML `
` element to serve as the target container for custom WebVTT subtitle rendering within the web page, typically placed relative to the video element.
```HTML
```
--------------------------------
### Synchronize Multiple dash.js Players with Live Delay and Catchup
Source: https://dashif.org/dash.js/pages/usage/live-streaming
This example illustrates how to synchronize multiple dash.js player instances. By setting a common `liveDelay` (e.g., 10 seconds) and enabling `liveCatchup` mode, both players will attempt to play at roughly the same position relative to the live edge, ensuring synchronized playback.
```JavaScript
player.updateSettings({
streaming: {
delay: {
liveDelay: 10
},
liveCatchup: {
enabled: true
}
},
})
```
--------------------------------
### Configure Common Media Server Data (CMSD) in dash.js
Source: https://dashif.org/dash.js/pages/usage/cmsd
This example demonstrates how to enable and configure Common Media Server Data (CMSD) settings within the dash.js player. It shows how to enable CMSD parsing, apply the maximum suggested bitrate (`mb`) from CMSD in ABR logic, and set the weight ratio for estimated throughput (`etp`) from CMSD, influencing the player's ABR decisions.
```JavaScript
player.updateSettings({
streaming: {
cmsd: {
enabled: true,
abr: {
applyMb: true,
etpWeightRatio: 0.5
}
}
}
})
```
--------------------------------
### Prioritize DRM Key Systems in dash.js
Source: https://dashif.org/dash.js/pages/usage/drm
This example shows how to prioritize specific DRM systems, such as Widevine over Playready, by assigning a `priority` attribute to each system within the `protectionData`. A lower numerical value indicates a higher priority, influencing the order in which dash.js attempts to support DRM systems.
```JavaScript
const protData = {
"com.widevine.alpha": {
"serverURL": "someurl",
"priority": 1
},
"com.microsoft.playready": {
"serverURL": "someurl",
"priority": 2
}
}
player.setProtectionData(protData)
```
--------------------------------
### Execute dash.js Functional Tests via Karma
Source: https://dashif.org/dash.js/pages/testing/functional-test
This command line snippet shows how to execute the dash.js functional test suite using the Karma Testrunner. It specifies the Karma configuration file, a test configuration file (e.g., 'local' for browser setup), and a streams configuration file (e.g., 'smoke' for defining test streams). This allows for automated and configurable test execution.
```Shell
karma start test/functional/config/karma.functional.conf.cjs --configfile=local --streamsfile=smoke
```
--------------------------------
### Initialize dash.js MediaPlayer for Smooth Streaming
Source: https://dashif.org/dash.js/pages/usage/mss
This JavaScript code initializes a dash.js MediaPlayer instance, attaches it to a video element, sets protection data (for DRM-protected content), and provides the stream URL. This setup is common for both DASH and Smooth Streaming content, allowing the player to load and play the specified media source.
```JavaScript
let video, player;
player = dashjs.MediaPlayer().create();
video = document.querySelector('video');
player.initialize(); /* initialize the MediaPlayer instance */
player.attachView(video); /* tell the player which videoElement it should use */
player.setProtectionData(protData); /* set protection data (sets license server when required) */
player.attachSource(streamUrl); /* provide the manifest source */
```
--------------------------------
### Configure Initial Track Selection Mode in dash.js
Source: https://dashif.org/dash.js/pages/usage/track-selection
This example demonstrates how to explicitly set the initial track selection mode for the dash.js player. By updating the `selectionModeForInitialTrack` setting to values like `highestBitrate`, `firstTrack`, `highestEfficiency`, or `widestRange`, developers can control how the player chooses the initial track from available options.
```JavaScript
player.updateSettings({
streaming: {
selectionModeForInitialTrack: 'highestBitrate'
}
})
```
--------------------------------
### dash.js Live Playback Seek to Absolute Presentation Time
Source: https://dashif.org/dash.js/pages/usage/timing-apis
Demonstrates using the `seekToPresentationTime()` method in dash.js for live content to seek to an absolute presentation timestamp. This example calculates a seek point 20 seconds behind the live edge by subtracting from the DVR window's end time.
```JavaScript
var video = document.querySelector('video');
var player = dashjs.MediaPlayer().create();
player.initialize(video, url, false);
var dvrWindowEnd = player.getDvrWindow().end
player.seekToPresentationTime(dvrWindowEnd - 20);
```
--------------------------------
### Configure dash.js Throughput Calculation Mode and Sample Settings
Source: https://dashif.org/dash.js/pages/usage/abr/throughput-calculation
This JavaScript example demonstrates how to update the dash.js player settings to change the default throughput calculation mode to 'BYTE_SIZE_WEIGHTED_HARMONIC_MEAN' and adjust the number of samples used for VOD content, while disabling automatic sample size adjustment.
```JavaScript
player.updateSettings({
streaming: {
abr: {
throughput: {
averageCalculationMode: dashjs.Constants.THROUGHPUT_CALCULATION_MODES.BYTE_SIZE_WEIGHTED_HARMONIC_MEAN,
sampleSettings: {
vod: 5,
enableSampleSizeAdjustment: false
}
}
}
}
});
```
--------------------------------
### Define Custom Initial Track Selection Function in dash.js
Source: https://dashif.org/dash.js/pages/usage/track-selection
This example illustrates how to create a custom JavaScript function, `getTrackWithLowestBitrate`, to determine which track should be initially selected. The function is then registered with the dash.js player using `setCustomInitialTrackSelectionFunction`, allowing for highly specific track selection logic beyond the default options.
```JavaScript
var getTrackWithLowestBitrate = function (trackArr) {
let min = Infinity;
let result = [];
let tmp;
trackArr.forEach(function (track) {
tmp = Math.min.apply(Math, track.bitrateList.map(function (obj) {
return obj.bandwidth;
}));
if (tmp < min) {
min = tmp;
result = [track];
}
});
return result;
}
player.setCustomInitialTrackSelectionFunction(getTrackWithLowestBitrate);
```
--------------------------------
### Define Main Entry Point for dash.js NPM Package (v4.x)
Source: https://dashif.org/dash.js/pages/quickstart/installation
Illustrates the `main` entry point configuration in `package.json` for dash.js versions 4.x and older, pointing to the minified UMD build.
```JSON
{
"main": "dist/dash.all.min.js"
}
```
--------------------------------
### Define Multiple Entry Points for dash.js NPM Package (v5.x)
Source: https://dashif.org/dash.js/pages/quickstart/installation
Shows the comprehensive `package.json` entry point configuration for dash.js versions 5.x and newer, including `types`, `import`, `default`, `browser`, `script`, and `require` fields to support various module environments.
```JSON
{
"types": "./index.d.ts",
"import": "./dist/modern/esm/dash.all.min.js",
"default": "./dist/modern/esm/dash.all.min.js",
"browser": "./dist/modern/umd/dash.all.min.js",
"script": "./dist/modern/umd/dash.all.min.js",
"require": "./dist/modern/umd/dash.all.min.js"
}
```
--------------------------------
### Initialize dash.js Player and Akamai Controlbar
Source: https://dashif.org/dash.js/pages/usage/controlbar
This snippet provides the essential HTML structure for a video player with Akamai Controlbar elements and the corresponding JavaScript initialization logic. It demonstrates how to include the controlbar's assets (JS and CSS), create a dash.js player instance, and then bind and initialize the ControlBar to the player.
```HTML
00:00:00
00:00:00
```
```JavaScript
function init() {
var url = 'https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps.mpd';
var videoElement = document.querySelector('.videoContainer video');
var player = dashjs.MediaPlayer().create();
player.initialize(videoElement, url, true);
var controlbar = new ControlBar(player);
controlbar.initialize();
}
```
--------------------------------
### Set Initial Media Settings for Text Tracks
Source: https://dashif.org/dash.js/pages/developers/migration-guides/3-to-4
Demonstrates how to set initial media settings for text tracks using the `player.setInitialMediaSettingsFor` method, specifying language and role. This method is the recommended approach for configuring text tracks.
```JavaScript
player.setInitialMediaSettingsFor('text', {
lang: 'eng,
role: 'caption
});
```
--------------------------------
### MediaPlayer.js API Changes Summary
Source: https://dashif.org/dash.js/pages/developers/migration-guides/3-to-4
Provides an overview of recent API modifications in MediaPlayer.js, detailing deprecated methods and new configuration approaches for media settings and track switching. It highlights the use of `setInitialMediaSettingsFor` and direct configuration via the `streaming` object.
```APIDOC
MediaPlayer.js API Changes:
- player.setInitialMediaSettingsFor(type: string, settings: object):
- Purpose: Set initial media settings for a given track type (e.g., 'text').
- Parameters:
- type: 'text' (currently only one type for text tracks)
- settings: object { lang: string, role: string } (e.g., { lang: 'eng', role: 'caption' })
- Note: Replaces setTextDefaultLanguage and getTextDefaultLanguage.
- Configuration: streaming.text.defaultEnabled:
- Type: boolean
- Purpose: Enable text tracks by default.
- Example: streaming: { text: { defaultEnabled: true } }
- Configuration: streaming.trackSwitchMode:
- Type: object
- Purpose: Configure track switch mode for video and audio.
- Properties: video: string, audio: string
- Example: streaming: { trackSwitchMode: { video: mode, audio: mode } }
- Note: Replaces setTrackSwitchModeFor and getTrackSwitchModeFor.
```
--------------------------------
### Advanced Learn2Adapt-LowLatency (L2A-LL) Tuning Parameters
Source: https://dashif.org/dash.js/pages/usage/abr/l2a
This section details advanced configuration parameters for the Learn2Adapt-LowLatency (L2A-LL) algorithm, located in `streaming/rules/abr/L2ARule.js`. These parameters allow fine-tuning of the algorithm's behavior, such as optimization horizon and reactiveness to network volatility, and are intended for experienced users who have consulted the associated research paper.
```APIDOC
Parameter: horizon
Description: Optimization horizon. Specifies the amount of steps required to achieve convergence. In live streaming settings, this parameter must be kept low for stable performance.
Default Value: 4
Impact: Higher 'horizon' leads to more aggressive bitrate selection (higher 'vl') and less exploration (large 'alpha'). Not advisable for live streaming scenarios with short buffers. Alteration is not suggested as the selected value has been experimentally verified.
Parameter: react
Description: Reactiveness to volatility (abrupt throughput drops). This parameter is used to recalibrate the 'l2AParameter.Q'.
Default Value: 2
Impact: Higher 'react' results in a more conservative algorithm (higher l2AParameter.Q). Values higher than the selected (react=2) may make the algorithm select the lowest bitrate for extended periods until recovery of 'l2AParameter.Q'. Alteration is not suggested as the chosen value has been experimentally selected.
```
--------------------------------
### Registering dash.js Application Event Listeners
Source: https://dashif.org/dash.js/pages/usage/event-handling
Shows how to register listeners for specific application events in `dash.js` using the `player.on()` method. It demonstrates listening for events based on `schemeIdUri` and utilizing different dispatch modes like `EVENT_MODE_ON_START` and `EVENT_MODE_ON_RECEIVE`.
```JavaScript
const SCHEMEIDURI = "urn:scte:scte35:2013:xml";
const EVENT_MODE_ON_START = dashjs.MediaPlayer.events.EVENT_MODE_ON_START;
const EVENT_MODE_ON_RECEIVE = dashjs.MediaPlayer.events.EVENT_MODE_ON_RECEIVE;
player.on(SCHEMEIDURI, showStartEvent, null);
player.on(SCHEMEIDURI, showReceiveEvent, null, { mode: EVENT_MODE_ON_RECEIVE });
```
--------------------------------
### MediaPlayerEvents#PLAYBACK_NOT_ALLOWED Event
Source: https://dashif.org/dash.js/pages/developers/migration-guides/3-to-4
Sent when playback is not allowed, for example, if a user gesture is required to initiate playback.
```APIDOC
MediaPlayerEvents#PLAYBACK_NOT_ALLOWED
Description: Sent when playback is not allowed (for example if user gesture is needed).
Value: 'playbackNotAllowed'
```
--------------------------------
### JavaScript Configure SwitchHistoryRule in dash.js Player
Source: https://dashif.org/dash.js/pages/usage/abr/switch-history-rule
This JavaScript example demonstrates how to activate and configure the `SwitchHistoryRule` within the dash.js player's settings. It shows how to set the `active` status, `minimumSampleSize`, and `switchPercentageThreshold` parameters for the rule.
```JavaScript
player.updateSettings({
streaming: {
abr: {
rules: {
switchHistoryRule: {
active: true,
parameters: {
minimumSampleSize: 8,
switchPercentageThreshold: 0.075
}
}
}
}
}
});
```
--------------------------------
### dash.js CMCD Configuration Settings API
Source: https://dashif.org/dash.js/pages/usage/cmcd
Detailed documentation of the CMCD configuration options available in dash.js, outlining each parameter's purpose, data type, and default values where applicable.
```APIDOC
CmcdSettings:
applyParametersFromMpd:
type: boolean
description: Enable if dash.js should use the CMCD parameters defined in the MPD
enabled:
type: boolean
description: Enable or disable the CMCD reporting.
sid:
type: string (UUID)
description: GUID identifying the current playback session. Should be defined in UUID format
cid:
type: string
description: A unique string to identify the current content. If not specified it will be a hash of the MPD URL.
rtp:
type: number
description: The requested maximum throughput that the client considers sufficient for delivery of the asset. If not specified this value will be dynamically calculated in the CMCDModel based on the current buffer level.
rtpSafetyFactor:
type: number
description: This value is used as a factor for the rtp value calculation: rtp = minBandwidth * rtpSafetyFactor. If not specified this value defaults to 5. Note that this value is only used when no static rtp value is defined.
default: 5
mode:
type: string ('query' | 'header')
description: The method to use to attach cmcd metrics to the requests. 'query' to use query parameters, 'header' to use http headers.
default: 'query'
enabledKeys:
type: string[]
description: This value is used to specify the desired CMCD parameters. Parameters not included in this list are not reported.
includeInRequests:
type: string[]
description: Specifies which HTTP GET requests shall carry parameters.
default: ['segment', 'mpd']
version:
type: number
description: The version of the CMCD to use.
default: 1
```
--------------------------------
### Enable Text Tracks by Default via Configuration
Source: https://dashif.org/dash.js/pages/developers/migration-guides/3-to-4
Shows how to configure the player to enable text tracks by default using the `streaming.text.defaultEnabled` setting within the player's configuration object.
```JavaScript
streaming:
{
text: {
defaultEnabled: true
}
}
```