Skip to content

About

EPAS Client SDK for Web

Topics

Resources

Security policy

Stars

2 stars

Watchers

1 watching

Forks

Repository files navigation

Badge OSC

Player Analytics Client SDK Web

Part of Eyevinn Player Analytics Specification (EPAS). To be used together with Eyevinn Player Analytics Eventsink

npm install @eyevinn/player-analytics-client-sdk-web

EPAS backend in Open Source Cloud

The quickest way to get started is to setup an EPAS compatible backend in Eyevinn Open Source Cloud

EPAS pipeline in OSC

  1. Setup an Eventsink in OSC as described in the documentation.
  2. Setup an Analytics Worker and Clickhouse Database by following the instructions in the documentation
  3. Add Clickhouse as datasource in Grafana and start visualizing the metrics

Usage

Automatic Event Listening

import { PlayerAnalyticsConnector } from "@eyevinn/player-analytics-client-sdk-web";

// Create your instance and set the analytics eventsink endpoint
const analytics = new PlayerAnalyticsConnector(
  "https://your-eventsink-url.io"
);

// Initiate the analytics with the base data needed
// This will create your session in the backend
try {
  await analytics.init({
    sessionId: "generated-unique-uuid-session-id",
  });

  // Get your video element from the site, or your video player of choice
  const videoElement = document.querySelector("video");
  // Load the analytics library with the video element to fetch the events
  analytics.load(videoElement);
} catch (err) {
  console.error(err);
  // Remove event listeners and heartbeat timers if init fails.
  analytics.deinit();
}

Non-blocking init() and autoplay

load() does not have to wait for init() to resolve. You may call load() immediately after init() starts (without awaiting it) — any events produced before the handshake completes are queued and flushed, in order, once the session is established:

const analytics = new PlayerAnalyticsConnector("https://your-eventsink-url.io");

// Start the handshake but don't await it...
analytics.init({ sessionId: "generated-unique-uuid-session-id" });
// ...attach the player right away so no early events are missed.
analytics.load(videoElement);

This matters for autoplay: if the video starts playing while init() is still in flight, the playing event fires before the SDK's listeners are attached. To avoid losing it, load() inspects the element and, if it is already playing, emits a playing event itself and starts the heartbeat (queued/deferred until the handshake completes). Attaching with load() as early as possible ensures the playing event and heartbeats are captured even for autoplaying content.

Due to bitrate changes not being reported, and errors not being reported in any descriptive way, there is a possibility to do separate calls for these events - which you may trigger based on your video player of choice following these examples.

analytics.reportBitrateChange({
  bitrate: 246.440, // bitrate in Kbps
  width: 320, // optional, video width in pixels
  height: 136, // optional, video height in pixels
  videoBitrate: 0, // optional, if available provide the bitrate for the video track
  audioBitrate: 0, // optional, if available provide the bitrate for the audio track
});
// error is fatal, i.e. sends a stopped event as well
analytics.reportError({
  category: "", // optional, eg. NETWORK, DECODER, etc.
  code: "",
  message: "", // optional
  data: {}, // optional
});

// warning is not fatal
analytics.reportWarning({
  category: "", // optional, eg. NETWORK, DECODER, etc.
  code: "",
  message: "", // optional
  data: {}, // optional
});
// when leaving the player, to stop the analytics in a correct manner
analytics.reportStop();
analytics.destroy();

Manual Event Triggering

Use the PlayerAnalytics class directly for full control over when events are sent.

import { PlayerAnalytics } from "@eyevinn/player-analytics-client-sdk-web";

// Create your instance and set the analytics eventsink endpoint
const playerAnalytics = new PlayerAnalytics("https://your-eventsink-url.io");
await playerAnalytics.initiateAnalyticsReporter({
  sessionId: "generated-unique-uuid-session-id",
});

// then trigger the method calls accordingly, e.g.
const videoElement = document.querySelector("video");
videoElement.addEventListener("play", () => {
  playerAnalytics.playing({
    event: "playing",
    timestamp: Date.now(),
    playhead: videoElement.currentTime,
    duration: videoElement.duration,
    sessionId: "generated-unique-uuid-session-id",
  });
});

Report Metadata

You can report metadata at a later stage in your code and tailor the callbacks for your tech stack, for example when you have parsed your manifest. In this example we're using hls.js with the PlayerAnalyticsConnector:

import Hls from "hls.js";
import { PlayerAnalyticsConnector } from "@eyevinn/player-analytics-client-sdk-web";

const analytics = new PlayerAnalyticsConnector("https://your-eventsink-url.io");
await analytics.init({
  sessionId: "generated-unique-uuid-session-id",
});

const hls = new Hls();
const videoElement = document.querySelector("video");

analytics.load(videoElement);
hls.attachMedia(videoElement);
hls.loadSource(src);
hls.on(Hls.Events.LEVEL_LOADED, (event, data) => {
  analytics.reportMetadata({
    live: data?.details?.live,
    contentTitle: "My Video",
    contentUrl: src,
  });
});

These are the available keys for metadata, which can be sent anytime between an init and a stopped call.

export type TMetadataEventPayload = {
  live?: boolean;
  contentTitle?: string;
  contentId?: string;
  contentUrl?: string;
  drmType?: string;
  userId?: string;
  deviceId?: string;
  deviceModel?: string;
  deviceType?: string;
  timeZone?: string; // device IANA time zone, added automatically (see below)
  [key: string]: string | boolean; // additional custom metadata
}

Automatic timeZone

reportMetadata automatically adds a timeZone key holding the device's IANA time zone (e.g. "Europe/Stockholm"), resolved from the built-in Intl.DateTimeFormat().resolvedOptions().timeZone. Hosted Open Analytics pipelines use it to derive the viewer's country when it cannot be resolved from the request IP.

  • If you pass your own timeZone, it is sent unchanged and overrides the automatic value.
  • In environments without a working Intl, the key is simply omitted (nothing is thrown).

Events Tracked

When you call analytics.load(videoElement) on PlayerAnalyticsConnector, the SDK attaches listeners via @eyevinn/media-event-filter and emits the following EPAS events automatically:

Native trigger EPAS event
Media element load loading (sent on load())
First playable state loaded
playing (or already playing at load()) playing (also starts the heartbeat)
pause paused
seeking seeking
seeked seeked
Buffer stall buffering
Buffer recovery buffered
ended stopped (reason: "ended")
Page close / reload (pagehide / page unload) stopped (reason: "aborted")

Hiding the tab (visibilitychange → hidden) does not end a playing session — since 0.4.0 (#44) a still-playing session survives a tab switch, so only pagehide / page unload triggers the auto stopped (reason: "aborted").

bitrate_changed, error, warning, metadata, and manual stopped (reason: "aborted") are not auto-detected — call the corresponding report* methods when you have the data. A heartbeat event is sent every heartbeatInterval ms while the player is in the playing state (see Init Parameters below).

Playhead & duration units (EPAS version handshake)

EPAS defines playhead and duration as integer milliseconds (-1 when unknown). To stay compatible with eventsinks that predate this, the SDK negotiates the unit from the version the eventsink advertises as epasVersion in its init response:

  • EPAS >= 0.7.0: the SDK sends playhead/duration as integer milliseconds and adds an sdk field ({ "name": "web", "version": "<this package's version>" }) to every event. The sdk field tells the eventsink the values are already in milliseconds, matching the Android and iOS/Swift SDKs.
  • EPAS < 0.7.0, epasVersion missing or "n/a", or a failed init: the SDK keeps the legacy wire format — playhead/duration in seconds and no sdk field — so nothing changes for an eventsink validating against spec <= 0.6.0 (which rejects the sdk field with a 400).

The -1 "unknown" sentinel is always sent as -1 and is never converted. The version comparison is numeric semver (so 0.10.0 is correctly newer than 0.7.0). The same mode is used on the unload beacon path.

Unload-time delivery (page close / reload)

When the page is closed or reloaded mid-session, the SDK delivers the final stopped event (reason: "aborted") over navigator.sendBeacon instead of a normal fetch. The beacon is sent as a text/plain JSON body with no X-EPAS-* headers, which keeps it a CORS "simple request" so the browser does not issue a preflight — a preflight is dropped while the page unloads, which is why the stopped event was previously lost. The eventsink reads the event from the JSON body (body.event), so this is a fully supported way to send unload-time events.

Where navigator.sendBeacon is unavailable, the SDK falls back to fetch(..., { keepalive: true }) with the same text/plain JSON body.

The unload listeners are attached automatically on load() and removed on deinit() / destroy(). The stopped event is only sent once per session, so an explicit reportStop(), a reportError(), or an ended event already reported for the session suppresses the unload beacon.

Constructor Parameters

Both PlayerAnalyticsConnector and PlayerAnalytics share the same constructor signature (eventsinkUrl, debug?, onError?):

Parameter Type Default Description
eventsinkUrl string (required) URL to your eventsink endpoint
debug boolean false When true, logs events to console instead of sending HTTP requests
onError TOnSendError undefined Optional callback invoked when a send fails. Falls back to console.warn if not provided

Init Parameters

export interface IPlayerAnalyticsConnectorInitOptions {
  sessionId?: string;    // Generated by the backend if not provided
  shardId?: string;      // Optional grouping key for sharding events in the pipeline
  heartbeatInterval?: number; // Defaults to HEARTBEAT_INTERVAL (see src/utils/constants.ts)
}

Example:

const analytics = new PlayerAnalyticsConnector(
  "https://eyevinnlab-epasdev.eyevinn-player-analytics-eventsink.auto.prod.osaas.io/"
);
await analytics.init({
  sessionId: `demo-page-${Date.now()}`,
  shardId: "myshard1",
  heartbeatInterval: 10000,
});

Error Handling

By default, send failures are logged to console.warn. You can provide an optional onError callback (see Constructor Parameters above) to handle errors programmatically:

import {
  PlayerAnalyticsConnector,
  TAnalyticsSendError,
  TPlayerAnalyticsEvent,
} from "@eyevinn/player-analytics-client-sdk-web";

const analytics = new PlayerAnalyticsConnector(
  "https://your-eventsink-url.io",
  false, // debug
  (error: TAnalyticsSendError, event: TPlayerAnalyticsEvent) => {
    // error.status - HTTP status code (e.g. 404), undefined for network errors
    // error.statusText - HTTP status text (e.g. "Not Found")
    // error.message - Human-readable error description
    // event - the analytics event that failed to send
    console.error(`Analytics send failed: ${error.message}`, event.event);
  }
);

API Reference

PlayerAnalyticsConnector

High-level API that automatically listens to HTMLVideoElement events.

Method Description
init(options) Connect to eventsink and create a session
load(videoElement) Attach to a video element and start listening for events
reportBitrateChange(payload) Report a bitrate change event
reportError(payload) Report a fatal error (also sends a stopped event)
reportWarning(payload) Report a non-fatal warning
reportMetadata(payload) Report metadata (content info, device info, etc.)
reportStop() Report that playback was stopped by the user
deinit() Stop heartbeat and remove event listeners (keeps instance reusable)
destroy() Fully tear down the instance

PlayerAnalytics

Low-level API implementing the EPAS PlayerAnalyticsClientModule interface. initiateAnalyticsReporter() must be called before any event method — other calls no-op with a warning until then.

Lifecycle

Method Description
initiateAnalyticsReporter(options) Connect to eventsink and create a session (required first call). Accepts IPlayerAnalyticsInitOptions.
destroy() Tear down the reporter and discard queued events.

EPAS event methods

Each accepts a full EPAS event object.

Method Event Type
init(data) TInitEvent
heartbeat(data) THeartbeatEvent
loading(data) TLoadingEvent
loaded(data) TLoadedEvent
playing(data) TPlayingEvent
pause(data) TPausedEvent
buffering(data) TBufferingEvent
buffered(data) TBufferedEvent
seeking(data) TSeekingEvent
seeked(data) TSeekedEvent
bitrateChanged(data) TBitrateChangedEvent
error(data) TErrorEvent
warning(data) TWarningEvent
stopped(data) TStoppedEvent
metadata(data) TMetadataEvent

Exports

Classes

Class Description
PlayerAnalyticsConnector High-level, auto-listening API (see above)
PlayerAnalytics Low-level, EPAS-compliant API (see above)

Types

import type {
  IPlayerAnalyticsConnectorInitOptions,
  IPlayerAnalyticsInitOptions,
  TAnalyticsSendError,
  TOnSendError,
  TPlayerAnalyticsEvent,
} from "@eyevinn/player-analytics-client-sdk-web";
Type Description
IPlayerAnalyticsConnectorInitOptions Options passed to PlayerAnalyticsConnector.init() — { sessionId?, shardId?, heartbeatInterval? }
IPlayerAnalyticsInitOptions Options passed to PlayerAnalytics.initiateAnalyticsReporter() — same shape as above
TAnalyticsSendError { status?: number; statusText?: string; message: string } — status/statusText are set on HTTP errors, absent on network errors
TOnSendError (error: TAnalyticsSendError, event: TPlayerAnalyticsEvent) => void
TPlayerAnalyticsEvent Union of all EPAS event types — re-exported from @eyevinn/player-analytics-specification

Development

Run the demo page by npm start

Release

  • Pull latest master
  • npm version patch | minor | major
  • This triggers an update of the version in package.json + creates a tag with that version number
  • This will automatically be pushed to Github upon success.
  • At github.com go to releases (far right)
    • click "Draft a new release"
    • choose your tag
    • give it a name (preferably your version number, e.g. v0.0.1)
    • click "Auto-generate release notes"
    • click "Publish release"
  • A Github Action is triggered to do the releases towards the npmjs and github packages repositories.


About Eyevinn

We are Eyevinn Technology, and we help companies in the TV, media, and entertainment sectors optimize costs and boost profitability through enhanced media solutions. We are independent in a way that we are not commercially tied to any platform or technology vendor. As our way to innovate and push the industry forward, we develop proof-of-concepts and tools. We share things we have learn and code as open-source.

With Eyevinn Open Source Cloud we enable to build solutions and applications based on Open Web Services and avoid being locked in with a single web service vendor. Our open-source solutions offer full flexibility with a revenue share model that supports the creators.

Read our blogs and articles here:

Want to know more about Eyevinn, contact us at info@eyevinn.se!

About

EPAS Client SDK for Web

Topics

Resources

Security policy

Stars

2 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages