npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@istreamplanet/preview-player

v1.1.2

Published

PreviewPlayer JavaScript Client

Downloads

2

Readme

PreviewPlayer Javascript Client

Javascript client for playing back PreviewPlayer streams. The following complete example shows how easy it is to use:

<html>
  <head>
    <!-- Include transpiled preview-player.js somehow, e.g. via webpack -->
    <script src="preview-player.min.js"></script>
  </head>
  <body>
    <video id="vid" autoplay></video>

    <script>
      // Get the video element from above.
      var video = document.querySelector('#vid');

      // Create a PreviewPlayer instance for a given video ID and set up handlers.
      var previewPlayer = new PreviewPlayer(video, 'SERVER:PORT/video/ID', 'token');

      previewPlayer.on('error', function(err) {
        // Print any errors to the Javascript console for debugging.
        console.log(err);
      });
    </script>
  </body>
</html>

Architecture

The client creates a persistent WebSocket connection to the backend. If the connection is successful it waits for control messages and media data blobs. Control messages tell it how to create media source elements which are used to feed the data blobs into the associated HTML <video> element.

New dynamic media source URLs are created as needed when streams change or are restarted. These URLs should be set on the video element like in the example above.

            /- Text control messages -> Create media source
WebSocket -<
            \- Binary blob messages -> Load into media source (buffer)

Clients will automatically reconnect when the WebSocket connection is lost.

Usage

npm install --save @istreamplanet/preview-player.js

Running tests

To run tests, execute the following command:

$ npm test

Reference

Constructor

PreviewPlayer([video], [url], [preflightMetadata])

Create a new PreviewPlayer instance. Takes an optional HTML video element, optional playback URL without the protocol and optional data to send to the server when the connection is first opened.

// Get the video element:
const video = document.querySelector('#my-video');
const url = 'host:port/video/id';
const preflightMetadata = {
  identity: 'identity',
  token: 'token'
};

// Create and play back a stream:
let mp = new PreviewPlayer(video, url, preflightMetadata);

// Create but call `play` separately. It is safe to call `play`
// multiple times:
mp = new PreviewPlayer(video, null, preflightMetadata);
mp.play(url, preflightMetadata);

// Or, manage everything yourself if you want:
mp = new PreviewPlayer();
mp.on('source', src => {
  video.src = src;
})
mp.on('buffer-updated', (source, buffer, start, end) => {
  // Seek into the buffer if playback falls behind.
  if (video.currentTime < start) {
    video.currentTime = start
  }
})
mp.on('error', err => {
  console.log(err);
  mp.destroy();
  mp = null;
})
video.addEventListener('canplay', () => {
  video.play();
})

Instance Properties

preview-player.source

The MediaSource for the current stream.

preview-player.buffer

The SourceBuffer attached to the MediaSource above.

preview-player.ws

The WebSocket connection to the server that is used to read control messages and video stream data.

Instance Methods

previewPlayer.initWithPreviewStreamsData(previewStreamsData)

Initialize the PreviewPlayer with the given previewStreamsData.

previewPlayer.initWithPreviewStreamsData(JSON.parse(`
{
  "audio_tracks": [
    {
      "bitrate": <string>,
      "codec_string": <string>,
      "id": <int>,
      "num_channels": <int>,
      "sample_rate": <int>
    }
  ],
  "default_audio_track": {
    "bitrate": <string>,
    "codec_string": <string>,
    "id": <int>,
    "num_channels": <int>,
    "sample_rate": <int>
  },
  "default_url": "https://example.net/v1/<cluster>/org/<orgName>/ext_id/<channelExtId>/play?vid_id=<int>&aud_id=<int>",
  "default_video_track": {
    "bitrate": <int>,
    "codec_string": <string>,
    "frame_rate": <float>,
    "height": <int>,
    "id": <int>,
    "width": <int>
  },
  "token": <string>,
  "video_tracks": [
    {
      "bitrate": <int>,
      "codec_string": <string>,
      "frame_rate": <float>,
      "height": <int>,
      "id": <int>,
      "width": <int>
    }
  ]
}
`))

previewPlayer.destroyPreviewStreamsData()

Destroy the data in the player set by the previously given previewStreamsData.

previewPlayer.destroyPreviewStreamsData()

previewPlayer.onRecoverable(function() { return <previewStreamsData> })

When a recoverable event occurs, calls the provided function to get the new previewStreamsData. Will backoff if the function encounters any errors and attempt again up until a maximum retry. If the maxRetry passed in is equivalent to zero, then the player will attempt to recover with backoff until success.

preview.Player.onRecoverable(function() {
  // Makes a call to the edgestream service to retrieve new previewStreamsData.
  return previewStreamsData
}, 5)

previewPlayer.getPlayableVideoTracks()

Returns the video tracks that are playable by the current browser the video is embedded in.

let videoTracks = previewPlayer.getPlayableVideoTracks()

previewPlayer.getPlayableAudioTracks()

Returns the audio tracks that are playable by the current browser the video is embedded in.

let audioTracks = previewPlayer.getPlayableAudioTracks()

previewPlayer.getVideoTracks()

Returns all the video tracks that are part of the passed in previewStreamsData.

let videoTracks = previewPlayer.getVideoTracks()

previewPlayer.getAudioTracks()

Returns all the audio tracks that are part of the passed in previewStreamsData.

let audioTracks = previewPlayer.getAudioTracks()

previewPlayer.getCurrentVideoTrack()

Returns the current video tracks that is being played by the player.

let videoTrack = previewPlayer.getCurrentVideoTrack()

previewPlayer.getCurrentAudioTrack()

Returns the current audio tracks that is being played by the player.

let audioTrack = previewPlayer.getCurrentAudioTrack()

previewPlayer.on(name, handler)

Register a new event handler.

previewPlayer.on('error', err => {
  console.log(`Error playing back! ${err}`);
})

previewPlayer.playTracks(videoTrackId, audioTrackId)

Start playback of a new video URL with the given video and audio track ids.

previewPlayer.playTracks(1, 2);

previewPlayer.destroy()

Destroy and clean up the player. It is not safe to use the instance after destroy has been called.

previewPlayer.destroy();

Events

The following events are available for attaching a listener:

Event | Arguments | Description ----- | --------- | ----------- bufferUpdated | source, buffer, start, end | The media source buffer has been updated. error | err | An error occurred. destroyed | n/a | PreviewPlayer instance has cleaned up and is ready to be garbage collected. source | source | A new source is ready and can be attached to an HTML <video> element's src attribute. latencyToSource | latencyToSource | Estimate of the client player's latency to the source being consumed by the transcoder powering the stream. unrecoverable | [ERR_VIDEO_AUDIO_TRACK_MISSING, ERR_URL_MISSING, ERR_TOKEN_MISSING] | Unable to play the stream. Error message provided to add clarity as to why it cannot be played. recoverable | [ERR_AUTHENTICATION_FAILED] | Unable to play the stream but can be recovered utilizing the onRecoverable method.