Web Channel Express - PhenixRTS Docs

Channel Express

Single-step configuration based API for setting up a channel - a one-size-fits-all solution for all your one-to-many streaming applications. The Channel Express extends the lower-level Room Service API to provide easy solutions to:

Initializing

Initialization is a critical step in the lifecycle of viewing a channel. Once ChannelExpress is initialized, the client connects to our Platform. This connection utilizes sophisticated recovery mechanisms to deal with network changes and/or temporary connectivity issues.

Due to the inherent scale that some channels bring along, the ChannelExpress needs to be initialized as soon as possible after the end user loads the web app. This approach provides our platform the necessary telemetry to adjust the capacity to the actual size of the audience which may exceed hundreds of thousands of concurrent users.

const channelExpressOptions = {
  authToken: token,
};

var channelExpress = new sdk.express.ChannelExpress(channelExpressOptions);

Initializing Options

Name Type Description
features (optional) [Array Feature] The list of features you would like supported
onError (optional) Function Function to be called when authentication fails or a failure occurs that is unrecoverable.
authToken (optional) String An authentication token used to connect to the platform.
pcastExpress (optional) [object PCastExpress] Optionally pass in an already instantiated PCastExpress. This reduces the amount of overhead and is preferred to instantiating separate instances. If provided backendUri and authenticationData are not required.
treatBackgroundAsOffline (optional) Boolean Treat background as offline. This is especially useful on iOS browsers where the network connection may be stopped when the browser is in background. This forces a reconnect upon entering foreground which can greatly improve the time to reconnect.
reAuthenticateOnForeground (optional) Boolean Re-authenticate when entering foreground. This will force the session and connection to be revalidated upon entering foreground. This is automatically set to true if the treatBackgroundAsOffline option is enabled.
shakaLoader (optional) function(callback) Function that asynchronously returns the instance of Shaka Player. See npm.js shaka-player. Certified version 2.5.X.
webPlayerLoader (optional) function(callback) Function that asynchronously returns the instance of the Phenix Web Player. It's recommended to use the Phenix Web Player to play DASH/HLS streams. See npm.js phenix-web-player. Certified version >=2020.0.2.

Clean Up Channel Express

Dispose of all connections and clean up handlers.

channelExpress.dispose();

Enabling DASH/HLS Playback

The player for DASH/HLS is loaded asynchronously to enable lazy loading for this functionality on-demand. This speeds up startup and thus time to first frame for the real-time use case by not loading modules that are not required.

Plain Vanilla Javascript Example

options.webPlayerLoader = function (callback) {
  var script = document.createElement('script');
  script.onload = function () {
    callback(window['phenix-web-player']);
  };
  script.src =
    'https://dl.phenixrts.com/WebPlayer/2020.0.latest/phenix-web-player-bundled.min.js';

document.head.appendChild(script);
};
options.shakaLoader = function (callback) {
  var script = document.createElement('script');
  script.onload = function () {
    callback(window.shaka);
  };
  script.src =
    'https://ajax.googleapis.com/ajax/libs/shaka-player/2.5.14/shaka-player.compiled.js';

document.head.appendChild(script);
};

React.js + Webpack 4.X Example:

options.webPlayerLoader = (callback) => {
  import(/* webpackChunkName: "phenix-web-player" */ 'phenix-web-player')
    .then((module) => {
      const webPlayer = module.default;

callback(webPlayer);
    })
    .catch((e) => {
      console.error('Failed to load phenix web player', e);

callback(null);
    });
};
options.shakaLoader = (callback) => {
    import(/* webpackChunkName: "shaka-player" */ 'shaka-player').then(module => {
        const shaka = module.default;
        const canPlayHls: document.createElement('video').canPlayType('application/vnd.apple.mpegURL') === 'maybe';

if (!canPlayHls && !shaka.Player.isBrowserSupported()) {
          shaka.polyfill.installAll();
        }

callback(shaka);
    }).catch(e => {
        console.error('Failed to load shaka', e);

callback(null);
    });
};

View a Channel

Join a channel and automatically view the most recent content published to that channel.

View example on Github

var options = {
  alias: 'MyAwesomeChannel',
  videoElement: document.querySelector('#myVideoId'),
};

channelExpress.joinChannel(
  options,
  function joinChannelCallback(error, response) {
    if (error) {
      // Handle error
    }

if (response.status === 'room-not-found') {
      // Handle channel not found - Create a Channel Or Publish to a Channel
    } else if (response.status !== 'ok') {
      // Handle error
    }

// Successfully joined channel
    if (response.status === 'ok' && response.channelService) {
      // Do something with channelService
    }
  },
  function subscriberCallback(error, response) {
    if (error) {
      // Handle error
    }

if (response.status === 'no-stream-playing') {
      // Handle no stream playing in channel - Wait for one to start
    } else if (response.status !== 'ok') {
      // Handle error
    }

// Successfully subscribed to most recent channel presenter
    if (response.status === 'ok' && response.mediaStream) {
      // Do something with mediaStream
    }

if (response.renderer) {
      // Returned if videoElement option passed in - Do something with renderer

response.renderer.on('autoMuted', function handleAutoMuted() {
        // The browser refused to play video with audio therefore the stream was started muted.
        // Handle this case properly in your UI so that the user can unmute its stream
      });

response.renderer.on('failedToPlay', function handleEnded(reason) {
        if (reason === 'failed-to-play') {
          // Failed to play media stream
        }
        if (reason === 'failed-to-play-unmuted') {
          // Failed to play media stream given the auto mute was disabled
        }
        if (reason === 'paused-by-background') {
          // Unable to resume playback after pause in Safari
        }
      });
    }
  }
);

View Channel Parameters

Name Type Description
options (required) Options Options to join channel with
joinChannelCallback (required) Function Function to call on success/failure of joining the channel. See Join Channel Callback Arguments
subscriberCallback (required) Function Function to call on when the most recent presenter changes. See Express Subscribe Callback Arguments

View Channel Options

Name Type Default Value Description
alias (required) String Alias of the channel to view
channelId (optional) String Alternative to alias - Id of the channel to view
streamSelectionStrategy (optional) String most-recent Strategy for selecting streams
streamToken (optional) String A stream token used to connect to the stream.
subscriberOptions (optional) [Object SubscriberOptions] Additional options to use when subscribing.
videoElement (optional) html5 video element Video element to attach media stream to. If nothing is passed in, you may manually attach the media stream to an element.

Stream Selection Strategy

Strategy Description
most-recent Select the most recent stream. Viewing stream changes any time a stream starts or is updated in the room.
high-availability Select streams for increased reliability and redundancy. Viewing stream will only change in the event of a failure of the prior selected stream.

Join Channel Callback Response

Name Type Description
status String The status of the operation. See Join Channel Callback Status Codes.
channelService [object ChannelService] The channel service object.
channel [object Channel] An immutable channel object containing the information about the channel.

Join Channel Callback Status Codes

Status Description
ok Successfully joined the channel.
not-found The channel that is being joined does not exist.
varies Joining channel failed for other reasons.

[object ChannelService]

Name Signature Returns Description
getChatService () [object ChatService] The chat service associated with the channel.

[object Channel]

Name Signature Returns Description
getChannelId () string The channel ID.
getObservableAlias () Observable(of string) Observable of channel alias.
getObservableName () Observable(of string) Observable of channel name.
getObservableDescription () Observable(of string) Observable of channel description.
getObservableType () Observable(of string) Observable of channel type. Will be equal to Channel.
getObservableMembers () Observable(of array) Observable of array of visible members in the channel.
toJson () object Returns channel object with current observable values.

[object Member]

Name Signature Returns Description
getSessionId () string The session ID of the member.
getObservableRole () Observable(of string) Observable of member role.
getObservableState () Observable(of string) Observable of member state.
getObservableScreenName () Observable(of string) Observable of member screen name.
getObservableStreams () Observable(of array) Observable of array of streams belonging to the member.
getObservableLastUpdate () Observable(of number) Observable of utc timestamp.
getLastUpdate () Number Current last update value of the member.

Member Roles

Role Description
Participant Member with streams and is visible to all members.
Audience Member with no streams and is not visible to other members.
Presenter Presenter participant member.
Moderator Privileged participant member.

Member States

Role Description
Active Member is active.
Passive Member is not active.
HandRaised Member is requesting to become active.
Inactive Member is not active.
Offline Member has left the room.

[object Stream]

The stream object represent any stream resource.

Name Signature Returns Description
getUri () string The stream uri representing the stream resource
getType () string The stream type
getObservableAudioState () Observable(of string) Observable of stream video state
getObservableVideoState () Observable(of string) Observable of stream audio state

Stream Types

Type Description
Presentation Presentation stream
Audio Audio-only stream
User General purpose stream

Stream Track States

State Description
TrackEnabled Track is enabled
TrackDisabled Track is disabled
TrackEnded Track has ended

Join Channel Subscriber Callback Status Codes

Status Description
ok Successfully subscribed to the presenter.
no-stream-playing There is no presenter in channel to subscribe to. Waiting for a presenter to appear in channel.
unsupported-features The type of stream is not compatible with the enabled feature set of the browser. E.g. real-time on IE.
unauthorized Access to stream was not authorized. Check if your edge token uses the correct channel alias.
varies Subscribe to presenter failed for other reasons. Note that channel express automatically retries failure conditions that are retriable including failover.

[Object SubscriberOptions]

Name Type Default Description
targetLatency (optional) number 8 The target latency to achieve when playing back Dash or HLS streams.
receiveAudio (optional) boolean true Whether or not to receive audio on the stream.
receiveVideo (optional) boolean true Whether or not to receive video on the stream.
disableAudioIfNoOutputFound (optional) boolean false Whether to disable audio if no audio is found to avoid stream monitor failures.
disableAutoMuting (optional) boolean false Whether to disable fall back to muted streams if browser refuses auto play of audio.
iceConnectionTimeout (optional) number 12000 The default timeout in milliseconds for the ICE connection to successfully connect.
tags (optional) Array of Strings Tags for the stream

Publish to a Channel

Publish a local or remote media to a channel. Users that are viewing the channel will see your media.

Publishing remote media from the WebSDK is deprecated. Remote media should be published using the REST API.

View example on Github

var options = {
  channel: {
    name: 'MyAwesomeChannel',
    alias: 'MyAwesomeChannelAlias', // Not required but if it is provided we will use this as the alias instead of pre-generating one for you.
  },
  publishToken: 'DIGEST:...',
  mediaConstraints: { audio: true, video: true },
  videoElement: document.querySelector('#myVideoId'),
};

channelExpress.publishToChannel(options, function callback(error, response) {
  if (error) {
    // Handle error
  }

if (response.status !== 'ok') {
    // Handle error
  }

// Successfully published to channel
  if (response.status === 'ok' && response.publisher) {
    // Do something with publisher
  }
});

Publish To Channel Parameters

Name Type Description
options (required) Options Options to publish to channel with
callback (required) Function Function to call on success/failure of publishing to the channel

Publish To Channel Options

Name Type Default Value Description
channel (required) Object Channel Options
capabilities (optional) (deprecated) Array The list of all capabilities to publish with.
mediaConstraints (required) Object Media constraints on getting the user media. For example - {audio: true, video: true}
userMediaStream (optional) Object alternative to mediaConstraints - you can pass user media stream returned from getUserMedia.
streamUri (optional) String alternative to mediaConstraints. Use to publish remote media. Link to remote media (mp4, rtmp, etc.)
streamType (optional) String Presenter Type of stream to publish. See Stream Types
memberRole (optional) String Presentation Role of member to join channel as (used if not already in channel). See Member Roles
resolution (optional) number 720 Desired size of the video
frameRate (optional) number 15 Desired frame rate of the video
aspectRatio (optional) string 16x9 Desired aspect ratio of the video
onResolveMedia (optional) function Returns the options that were used to successfully get user media
publishToken (optional) String This token is a publish token that will include all capabilities and access rights to publish.
videoElement (optional) html5 video element Video element to attach media stream to. If nothing is passed you may manually attach the media stream to an element.
monitor (optional) Object Options for monitoring a publisher for failure.
connectOptions (optional) Array of Strings List of options for publishing from a remote source.
tags (optional) Array of Strings Tags for the stream
prerollSkipDuration (optional) int 500 Remote media only. The amount of milliseconds to skip at the beginning of the media.

Channel Options

Name Type Default Value Description
name (required) String Channel Name
alias (Optional) String Channel Alias
description (Optional) String Description of the Channel

Publish To Channel Callback Arguments

Name Type Description
status String The status of the operation. See Publish Callback Status Codes
publisher [object Publisher] Phenix publisher object

Create a Channel (deprecated)

Creation of Channels from client SDKs is deprecated. Channels should be created by the backend using the REST API.

var options = {
  channel: {
    name: 'MyAwesomeChannel',
    alias: 'MyAwesomeChannelAlias', // Not required but if it is provided we will use this as the alias instead of pre-generating one for you.
  },
};

channelExpress.createChannel(options, function callback(error, response) {
  if (error) {
    // Handle error
  }

if (response.status === 'already-exists') {
    // Channel already exists
    // Do something with channelService
  } else if (response.status !== 'ok') {
    // Handle error
  }

// Successfully created channel
  if (response.status === 'ok' && response.channelService) {
    // Do something with channelService
  }
});

Express Create Channel Parameters

Name Type Description
options (required) Options Options to create channel with
callback (required) Function Function to call on success/failure of creating to the channel. See Create Channel Callback Arguments

Express Create Channel Options

Name Type Default Value Description
channel (required) Object Channel Options

Express Create Channel Callback Arguments

Name Type Description
status String The status of the operation. See Create Room Callback Status Codes
channel [object Room] Immutable Phenix room object.