Connectors
@mattebox/player-core@0.11.0Needs mattebox ^0.21.0.
A connector maps a programme id from your content API to what the player loads: the sources, the metadata, the chapters, the markers, or a block. You register one connector per source type. You then load a programme by its type and id, or by its type and data.
Connectors are part of @mattebox/player-core. The core calls the
connector, and <mattebox-player> applies the result. You can use them
with createPlayer or with the element.
The Connector interface
A Connector is an object with a type, an optional fetch and a
resolve:
import type { Connector } from '@mattebox/player-core';
interface Episode {
readonly title: string;
readonly show: string;
readonly hls: string;
readonly image: string;
readonly region?: string;
}
export const tv: Connector<Episode> = {
type: 'example/episode',
async fetch(id, signal) {
const response = await fetch(`https://api.example.com/episodes/${id}`, { signal });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
},
resolve(episode) {
const metadata = { title: episode.title, subtitle: episode.show, image: episode.image };
if (episode.region === 'CH') {
return { sources: [], block: { message: 'Only available in Switzerland.' }, metadata };
}
return { sources: [{ url: episode.hls }], metadata };
},
};
| Member | What it does |
|---|---|
type |
The source type the connector handles, such as srgssr/urn. Any string of your choice that contains a slash |
fetch(id, signal) |
Fetches the programme’s data from your content API. Optional: without it, the source must carry data |
resolve(data, signal) |
Returns the resolution for the data. It can be asynchronous, for example to fetch a token |
The resolution
resolve returns an object with three fields:
| Field | What it is |
|---|---|
sources |
The sources to try in order, as a sources list. Each can carry drm and videoTracks |
block |
Why the programme does not play. A block wins: nothing loads |
metadata |
The programme’s metadata: title, subtitle, description, image, poster, chapters, markers |
Connectors in createPlayer
Pass the connectors to createPlayer, and load a programme by its type
and id:
import { createPlayer, matteboxHandler, nativeHandler } from '@mattebox/player-core';
import { tv } from './connectors/tv.js';
const player = createPlayer(video, {
handlers: [matteboxHandler(), nativeHandler()],
connectors: [tv],
});
player.on('programme', (programme) => {
heading.textContent = programme?.metadata?.title ?? '';
});
await player.load({ type: 'example/episode', id: 'ep-1042' });
loadcallsfetch, thenresolve, then plays the sources.player.programmeis what the load resolved: the sources, the metadata and the block, and the type, id and data of the connector source. It is null before a load and after an unload.- The
programmeevent fires when a load resolves, and with null at an unload. - A blocked programme loads nothing, and
loadrejects withBlocked.
Connectors in MatteboxPlayerElement.define
Pass the same list in the element’s options, once for every player of the page:
import { MatteboxPlayerElement } from '@mattebox/player';
MatteboxPlayerElement.define({ connectors: [tv] });
Then set the id as src and the connector’s type as type:
<mattebox-player controls="custom" src="ep-1042" type="example/episode"></mattebox-player>
From a script, set the same in sources:
player.sources = [{ type: 'example/episode', id: 'ep-1042' }];
new MatteboxPlayerElement({ connectors: [tv] })gives them to one player.- A player reads its options at its first load. Call
define()before then, at the top of your module. player.programmeand theprogrammechangeevent are the core’s programme andprogrammeevent.programmechangefires beforesourcechange.
How the element applies the metadata
The element applies the resolution before the session starts:
Field of metadata |
Where it goes |
|---|---|
title, subtitle |
<mbx-title>, for each attribute the page leaves out: heading, subheading |
poster |
The video’s poster, unless the player has a poster attribute. The last programme’s goes as a load starts |
chapters |
engine.chapters.set, unless the player has a chapters attribute. An engine session only |
markers |
player.markers, as chapter 11 describes |
image, description |
Nothing. Read them from player.programme. Set artwork on <mbx-title> to show the image there |
A block shows on the error screen as block() shows it: see
chapter 11.
Load with data: skip fetch
Set data on the source instead of an id. The core calls resolve only,
and makes no request to your API:
const episode = await myCache.get('ep-1042');
player.sources = [{ type: 'example/episode', id: 'ep-1042', data: episode }];
- Use this when your page already fetched the data, for a list or a page rendered on your server, or when your tests use fixtures.
- The id is optional with data. Give it to name the programme to your trackers.
- A connector without
fetchtakes data only. - A connector is never required. A source of another type, or a plain URL, loads as before.
Preload a programme: player.preload()
preload resolves a connector source ahead of its load: the connector
fetches and resolves the programme, and the core preloads its first
source. The next load of the same programme takes that resolution and
asks your API nothing:
const next = { type: 'example/episode', id: 'ep-1043' };
// During the closing credits of the programme that plays.
await player.player?.preload(next);
upNext.textContent = player.player?.preloaded?.metadata?.title ?? '';
// At the end.
player.sources = [next];
- The load takes the preload of the same type and id, or of the same data object.
- The core keeps one preload, for
keepSeconds: 30 seconds by default, as long as the engine keeps a preloaded manifest. A resolution can carry a token that expires, so an older one resolves again. - A load takes a preload once. A second load of the programme, such as a retry, asks your API again.
- When the preload failed, the load asks the connector again and reports what it says then.
preloadedis the programme the last preload resolved, such as the title an up next card shows. A blocked programme preloads none of its sources, andpreloadedcarries its block.- The playlist preloads its next item this way: see chapter 07.
Error codes
A connector failure is a fatal error of category connector:
code |
When |
|---|---|
CONNECTOR_UNKNOWN |
No connector is registered for the source’s type |
CONNECTOR_FAILED |
fetch or resolve threw. context.message says why |
CONNECTOR_NO_SOURCE |
The resolution has neither sources nor a block |
The context carries the type and the id. A programme that failed still
fires programme, with no sources, so a tracker sees the error.
Abort signal, mixed source lists and CORS
- A new load aborts the fetch in flight: the
signalyourfetchandresolveget fires. Pass it to your own requests. - A list can mix plain sources and connector sources. Each connector source resolves in its place, and the first one names the programme.
- A connector runs in the page, so the browser’s CORS rules apply to every request it makes.
Demo connectors
The demo’s “Broadcasters” tab has a connector for each public broadcaster whose API allows cross-origin requests: SRG SSR, SVT, ARD, 3Cat and DW. SRG SSR and ARD have a search, 3Cat and DW list their latest videos, and SVT has a fixed list, because its listing API does not allow cross-origin requests. Each connector maps the broadcaster’s data to a resolution, and the broadcaster’s block reasons to messages. “Show the data” fetches the data and lets you edit it, and “Play this data” plays it without a second fetch.
The SRG SSR connector probes the browser’s key systems, each at the
highest robustness it grants, and sends them to the IL as
drmPlayerCapabilities.
The IL then lists only the resources this browser can decrypt.
The connectors live in demo/src/connectors/. They are examples, not
published packages.
Example
A page that plays an episode by id, and preloads the next one during the credits, so it starts with no request to the content API:
<mattebox-player controls="custom" src="ep-1042" type="example/episode">
<mbx-title></mbx-title>
<mbx-error-screen></mbx-error-screen>
<mbx-control-bar>
<mbx-play-button></mbx-play-button>
<mbx-seek-bar></mbx-seek-bar>
</mbx-control-bar>
</mattebox-player>
<script type="module">
import { MatteboxPlayerElement } from '@mattebox/player';
import { tv } from './connectors/tv.js';
MatteboxPlayerElement.define({ connectors: [tv] });
const player = document.querySelector('mattebox-player');
const next = { type: 'example/episode', id: 'ep-1043' };
let asked = false;
player.media.addEventListener('timeupdate', () => {
const credits = player.markers
.within(player.media.currentTime)
.some((marker) => marker.kind === 'closing-credits');
if (credits && !asked) {
asked = true;
player.player?.preload(next);
}
});
player.media.addEventListener('ended', () => {
player.sources = [next];
});
</script>
A list of programmes is shorter with the playlist, which preloads each next item itself:
import { createPlaylist } from '@mattebox/player-playlist';
createPlaylist(player).load([
{ src: 'ep-1042', type: 'example/episode' },
{ src: 'ep-1043', type: 'example/episode' },
]);