Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions packages/hls-video-element/hls-video-element.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const HlsVideoMixin = (superclass) => {

#airplaySourceEl = null;
#config = null;
#loadId = 0;

constructor() {
super();
Expand Down Expand Up @@ -60,6 +61,8 @@ const HlsVideoMixin = (superclass) => {
}

async load() {
// Each call supersedes any earlier call that is still waiting on a tick.
const loadId = ++this.#loadId;
const isFirstLoad = !this.api;

this.#destroy();
Expand All @@ -76,6 +79,7 @@ const HlsVideoMixin = (superclass) => {
if (Hls.isSupported()) {
// Wait 1 tick to allow other attributes to be set.
await Promise.resolve();
if (loadId !== this.#loadId) return;

this.api = new Hls({
// Mimic the media element with an Infinity duration for live streams.
Expand Down Expand Up @@ -267,6 +271,7 @@ const HlsVideoMixin = (superclass) => {

// Wait 1 tick so this.nativeEl is sure to be defined.
await Promise.resolve();
if (loadId !== this.#loadId) return;

// Use native HLS. e.g. iOS Safari.
if (this.nativeEl.canPlayType('application/vnd.apple.mpegurl')) {
Expand Down
27 changes: 27 additions & 0 deletions packages/hls-video-element/test/test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { test } from 'zora';
import { Hls } from '../hls-video-element.js';

function createVideoElement() {
return fixture(`<hls-video
Expand Down Expand Up @@ -88,6 +89,32 @@ test('getTemplateHTML keeps the config inside the config script', async function
);
});

test('changing src twice in the same tick creates a single hls.js instance', async function (t) {
const video = document.createElement('hls-video');
video.setAttribute('muted', '');
document.body.append(video);

const originalAttachMedia = Hls.prototype.attachMedia;
const instances = new Set();
Hls.prototype.attachMedia = function (media) {
if (media === video.nativeEl) instances.add(this);
return originalAttachMedia.call(this, media);
};

try {
video.src = 'https://stream.mux.com/r4rOE02cc95tbe3I00302nlrHfT023Q3IedFJW029w018KxZA.m3u8';
video.src = 'https://stream.mux.com/1EFcsL5JET00t00mBv01t00xt00T4QeNQtsXx2cKY6DLd7RM.m3u8';
await delay(200);

t.equal(instances.size, 1, 'creates one hls.js instance');
t.equal(video.api?.url, video.src, 'loads the latest src');
t.equal(video.nativeEl.querySelectorAll('source').length, 1, 'adds one source element');
} finally {
Hls.prototype.attachMedia = originalAttachMedia;
video.remove();
}
});

function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
Expand Down