Web SDK 2
We are currently working on the next generation of web SDK that is smaller and even faster than its prior generation. It is currently available for real-time viewing of channels. Please refer to npmjs.org for the latest available version.
Channel Viewer
Join a channel and automatically view the most recent content published to that channel.
View interactive and editable example on JSFiddle
var videoElement = document.getElementsByTagName('video')[0];
var channel = phenix.Channels.createChannel({
videoElement: videoElement,
token: token
});
channel.authorized.subscribe(function(authorized) {
if (!authorized) {
// Channel is unauthorized, skipping retry of start. Please provide a new token and invoke channel.start()
}
});
channel.autoMuted.subscribe(function(autoMuted) {
if (autoMuted) {
// Show unmute button so a user-triggered action triggers channel.unmute()
}
});
channel.autoPaused.subscribe(function(autoPaused) {
if (autoPaused) {
// Show play button so a user-triggered action triggers channel.play()
}
});
Parameters
Name | Type | Description |
---|---|---|
options (required) | CreateChannelOptions | Options to join channel with |
Create Channel Options
Name | Type | Default Value | Description |
---|---|---|---|
videoElement (required) | HTMLMediaElement | Video element that will show the stream | |
token (required) | String | EdgeToken used to connect and authenticate to the platform and subscribe to a stream. |
Creating EdgeToken
To generate EdgeToken you must have a channel ID or an alias. Check out our EdgeAuth libraries for how to generate edge tokens on your backend. This is the recommended way to issue authentication tokens.
[object Channel]
Name | Type | Description |
---|---|---|
authorized | Observable(boolean) | Observable for channel authorized state. |
autoMuted | Observable(boolean) | Observable for channel autoMuted state. |
autoPaused | Observable(boolean) | Observable for channel autoPaused state. |
clearBitrateLimit | Function | Clear bitrate limit that was prior set. View example on Github |
failureCount | Observable(number) | Observable for channel failureCount. |
loading | Observable(boolean) | Observable is channel loading. |
online | Observable(boolean) | Observable is channel online. |
playing | Observable(boolean) | Observable is channel playing. |
rtcStats | Observable(RtcMonitorStatistic) | Observable for channel RTC stats check. |
setBitrateLimit | Function | Set a bitrate limit for the received stream. View example on Github |
standby | Observable(boolean) | Observable is channel in standby mode. |
state | Observable(ChannelState) | Observable that returns channel current state. |
stopped | Observable(boolean) | Observable is channel stopped. |
streamId | String | Stream ID. |
token | String | EdgeToken used to connect and authenticate to the platform and subscribe to a stream. |
tokenExpiring | Observable(boolean) | Observable that returns tokenExpiring state. |
videoElement | VideoElement | Video element that will show the stream. |
Channel State
Role | Value | Description |
---|---|---|
Offline | 1 | Channel is in Offline state. |
Starting | 2 | Channel is already starting, skipping retry of start. |
Paused | 3 | Channel is paused, skipping retry of start. Please invoke play(). |
Playing | 4 | Channel is playing, skipping retry of start. |
Recovering | 5 | Channel tries to recover from some state will retry to reconnect. |
Reconnecting | 6 | Channel is reconnecting after being disconnected. |
StandBy | 7 | Channel will try to connect to the stream in StandBy interval (15000ms). |
Stopped | 8 | Channel is stopped, skipping retry of start. |
Unauthorized | 9 | Channel is unauthorized, skipping retry of start. Please provide a new token and invoke start(). |
GeoRestricted | 10 | Channel is geo restricted, skipping retry of start. Please provide a new token and invoke start(). |
GeoBlocked | 11 | Channel is geo blocked, skipping retry of start. Please provide a new token and invoke start(). |
Error | 12 | Channel is not able to subscribe to stream due to a general failed subscription. |
UnsupportedFeature | 13 | Channel is not supporting the requested feature on this browser. This can be due to browser limitations or missing configuration for a player for the requested capability. |
Rtc Monitor Statistic Object
Property | Value |
---|---|
audio | RtcStatistic Audio Object |
video | RtcStatistic Video Object |
RtcStatistic Audio Object
Property | Type | Description |
---|---|---|
ssrc | Number | An integer which uniquely identifies the source of the RTP stream. |
mediaType | String | Kind/Media type of the stream. |
timestamp | Number | UNIX time stamp of when the statistics is captured. |
bytesReceived | Number | Bytes received. |
packetsLost | Number | Packets lost. |
packetsReceived | Number | Packets received. |
codec | String | Codec used to decode data. |
roundTripTime | Number | Round Trip Time of the webRTC connection. |
RtcStatistic Video Object
Property | Type | Description |
---|---|---|
ssrc | Number | An integer which uniquely identifies the source of the RTP stream. |
mediaType | String | Kind/Media type of the stream. |
timestamp | Number | UNIX time stamp of when the statistics is captured. |
bytesReceived | Number | Bytes received. |
framesDecoded | Number | Frames decoded. |
packetsLost | Number | Packets lost. |
packetsReceived | Number | Packets received. |
codec | String | Codec used to decode data. |
fps | Number | Frames per second. |
roundTripTime | Number | Round Trip Time of the webRTC connection. |
Limit Bitrate
Limit the bitrate limit for the received stream. View example on Github
Parameters
Property | Type | Description |
---|---|---|
bitrateLimitInBitsPerSecond | Number | Bitrate limit of the stream. |
var bitrateLimitInBitsPerSecond = 500000;
channel.setBitrateLimit(bitrateLimitInBitsPerSecond);
Clear Bitrate Limit
Clear bitrate limit that was prior set. View example on Github
channel.clearBitrateLimit();
Hosted Backend
A hosted backend provides a highly scalable channel viewer UI that can be used as a web page or embedded into any web page. It is a turn key solution that provides fast time to market without compromise in quality and scale.
The hosted backend is hosted on the Phenix infrastructure and benefits from the resilience and failover capabilities of the Phenix platform.
In order to be able to use a hosted backend, your account needs to be provisioned accordingly. Please contact your primary Phenix technical support contact if you wish to use a hosted backend.
Embedding A Channel
A channel from a hosted backend can be embedded via <iframe>
. Additional options are require to assure smooth playback across all platforms.
<iframe src="https://demo.phenixrts.com/channel/#embedded_channel" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen webkitallowfullscreen>
<p>Your browser does not support iframes.</p>
</iframe>
Lifecycle Events
You can listen to lifecycle events for the embedded channel. The channel uses the postMessage
API to securely send notifications to the parent window.
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event) {
console.log({timeStamp: event.timeStamp, data: event.data});
}
Types of Lifecycle Events
Lifecylce events are emitted for the view channel API, both for joining the channel and stream subscriptions.
Joining A Channel
After the channel joined successfully, it emits a lifecycle event for the join channel callback.
{
"timeStamp": 312.5,
"data": {
"channelAlias": "embedded_channel",
"action": "joinChannel",
"type": "joinChannelCallback",
"status": "ok"
}
}
In case there is an issue joining the channel, the status will be one of the join channel callback status codes.
Subscribing to A Stream
Subsequently, when the channel subscribed to the active stream, it emits a lifecycle event for the subscriber callback.
{
"timeStamp": 692.3,
"data": {
"channelAlias": "embedded_channel",
"action": "joinChannel",
"type": "subscriberCallback",
"status": "ok"
}
}
In case there is an issue subscribing to an active stream, the status will be one of the join channel subscriber callback status codes.
Edge Authentication
You can use EdgeAuth tokens with the channel viewer of your hosted backend.
<iframe src="https://demo.phenixrts.com/channel/?edgeAuth=<your-token>#embedded_channel" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen webkitallowfullscreen>
<p>Your browser does not support iframes.</p>
</iframe>
To detect the case when the edge auth token has expired and must be refreshed, please listen for the subscriberCallback
with status unauthorized
.
Web SDK
The Web SDK APIs are split into two main categories: Express and Low-Level. We recommend that you start with the Express API as this:
- Simplifies integration
- Automatically recovers from stream failures
- Handles edge cases such as network reconnects
For more information see the Express API
If you find that the Express API doesn’t work for you, take a look at our Lower Level API;
Latest Release
Please refer to npmjs.org for the latest available version.
Bundling in your app
The Web SDK is available on GitHub and can be installed as a pre-built universal module using several dependency management tools. The Web SDK may be included directly in the browser or bundled using your favorite bundling tool such as Webpack or Rollup. For a full list of browser support see Browser Support
Yarn
yarn add phenix-web-sdk
NPM
npm install -S phenix-web-sdk
Bower
bower install -S phenix-web-sdk
Bundles
The universal module is available uncompressed and minified.
phenix-web-sdk.js
phenix-web-sdk.min.js
For support with React Native use the following bundles. For more information about integrating in your React Native app, see Initializing with React Native.
phenix-web-sdk-react-native.js
phenix-web-sdk-react-native.min.js
Including with a bundler
Use your favorite bundling tool such as Webpack or Rollup.
ES6 Modules
import * as sdk from 'phenix-web-sdk';
// Or Import just what you need
import {express, utils, net} from 'phenix-web-sdk';
Common JS
const sdk = require('phenix-web-sdk');
AMD
define(['phenix-web-sdk'], function (sdk) {
// use sdk
});
Loading Directly in the Browser
Load it directly in the browser in a script tag.
var sdk = window['phenix-web-sdk'];
Initializing With Ember.js
If you are using ember.js for your frontend, then you can add the Web SDK by generating a vendor shim:
ember generate vendor-shim phenix-web-sdk
Then modify ember-cli-build.js as shown:
Add the following imports in your ember-cli-build.js:
app.import({
development: 'bower_components/phenix-web-sdk/dist/phenix-web-sdk.js',
production: 'bower_components/phenix-web-sdk/dist/phenix-web-sdk.min.js'
});
app.import('vendor/shims/phenix-web-sdk.js');
After that you can use the Web SDK in your code:
import sdk from 'phenix-web-sdk';
// use sdk
Production
We recommend that you include the minified version of the web-sdk in your production app or bundle(s). We optimize this bundle for size using smart transformations.
Alias with webpack
You can alias phenix-web-sdk in your webpack production config to use the minified version.
{
resolve: {
alias: {
'phenix-web-sdk': path.resolve(__dirname, '../node_modules', 'phenix-web-sdk/dist/phenix-web-sdk.min.js'),
}
}
}
Browser Support
Real-Time Support Matrix
OS | OS Version | Platform | Platform Version | Codecs | Publishing | Subscribing |
---|---|---|---|---|---|---|
macOS | 10.13+ | Chrome | 56+ | VP8, H264 | ✅ | ✅ |
macOS | 10.13+ | Firefox | 30+ | VP8, H264 | ✅ | ✅ |
macOS | 10.13+ | Opera | 43+ | VP8, H264 | ✅ | ✅ |
macOS | 10.13+ | Safari | 11+ | VP8 (10.14.4+)*, H264 | ✅ | ✅ |
Unix | 16+ Ubuntu | Chrome | 56+ | VP8, H264 | ✅ | ✅ |
Unix | 16+ Ubuntu | Firefox | 30+ | VP8, H264 | ✅ | ✅ |
Windows | 8+ | Chrome | 56+ | VP8, H264 | ✅ | ✅ |
Windows | 8+ | Firefox | 30+ | VP8, H264 | ✅ | ✅ |
Windows | 10+ | Edge | 80+ | VP8, H264 | ✅ | ✅ |
Windows | 10+ | Edge | 15-18 | VP8, H264 | ✅ | |
Windows | 8+ | Opera | 43+ | VP8, H264 | ✅ | ✅ |
Windows | 8+ | IE | 10+ | Flash fallback | ||
Android | 7+ | Chrome | 56+ | VP8, H264 (Partial) | ✅ | ✅ |
Android | 7+ | Firefox | 44+ | VP8, H264 | ✅ | ✅ |
iOS | 11+ | Safari | 11+ | VP8 (12.2+), H264 | ✅ | ✅ |
iOS | 11+ | Chrome | 66+ | H264 | ✅ | ✅ |
* Also available for macOS 10.13.6 and 10.12.6
Live Support Matrix (HLS + Dash)
To enable HLS or DASH live streaming, you can add the Streaming capability on the publisher
OS | OS Version | Platform | Platform Version | Players |
---|---|---|---|---|
macOS | 10.13+ | Chrome | 23+ | Phenix Web Player, Shaka |
macOS | 10.13+ | Firefox | 42+ | Phenix Web Player, Shaka |
macOS | 10.13+ | Safari | 6+ | HLS Native, hls.js |
Unix | 16+ Ubuntu | Chrome | 23+ | Phenix Web Player, Shaka |
Unix | 16+ Ubuntu | Firefox | 42+ | Phenix Web Player, Shaka |
Windows | 8+ | Chrome | 23+ | Phenix Web Player, Shaka |
Windows | 10+ | Edge | 80+ | Phenix Web Player, Shaka |
Windows | 10+ | Edge | 15-18 | Phenix Web Player, Shaka |
Windows | 8+ | Firefox | 42+ | Phenix Web Player, Shaka |
Windows | 8+ | IE | 11+ | Phenix Web Player |
Android | 7+ | Chrome | 23+ | Phenix Web Player, Shaka |
Android | 7+ | Firefox | 42+ | Phenix Web Player, Shaka |
Android | 7+ | Webview | 36+ | Phenix Web Player, Shaka |
iOS | 11+ | Safari | 6+ | HLS Native |
iOS | 11+ | Chrome | 56+ | HLS Native |
iOS | 11+ | Webview | 6+ | HLS Native |
React Native Support
In order to use the web-sdk with React Native we require that you first shim WebRTC via react-native-webrtc and then shim the Web SDK.
For a full example, see our Example
Shim the webrtc globals
import {
RTCPeerConnection,
RTCIceCandidate,
RTCSessionDescription,
RTCView,
MediaStream,
MediaStreamTrack,
getUserMedia
} from 'react-native-webrtc';
global = Object.assign(global, {
RTCPeerConnection,
RTCIceCandidate,
RTCSessionDescription,
RTCView,
MediaStream,
MediaStreamTrack,
getUserMedia
});
After that you need to include the Web SDK and shim the environment
import sdk from 'phenix-web-sdk/dist/phenix-web-sdk-react-native.min';
sdk.util.RTC.shim();
// use sdk
Express Web SDK
Our Express APIs provide a simple, single-step API for the easiest integration of streaming into your application
Common Use Cases
- Channel (one to many) -> Channel
- Group Broadcast (few to many) -> Room
- Group Chat (many to many) -> Room
- One to One Chat -> Room
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:
- View a channel
- Publish to a channel
- Create a channel
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 inherit 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.
var channelExpress = new sdk.express.ChannelExpress(options);
Options
Name | Type | Description |
---|---|---|
adminApiProxyClient (optional) | [object AdminApiProxyClient] | The class responsible for requesting auth and stream tokens. |
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. If not passed in, one will be generated automatically by querying the provided backend uri (may happen multiple times depending on the lifetime of the session). |
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.
The exact approach how to load the player asynchronously depends on the bundling framework. Webpack 4.X supports lazy loading.
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 interactive and editable example on JSFiddle
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
}
});
}
});
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 |
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. If wildcard tokens are not enabled on the stream and no stream token is passed in, then one will be generated automatically by querying the provided backend uri (may happen multiple times depending on the lifetime of the session). | |
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 Room 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 no 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 condition 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.
View interactive and editable example on JSFiddle
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
}
});
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 |
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 the 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 |
enableWildcardCapability (optional) (deprecated) | bool | true | Generate wildcard stream tokens to be appended to member’s stream uri. Reduces time for subscribing to published stream. |
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. If not passed in, it will be generated for you | |
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 |
Publish Screen to a Channel
Publish your screen, tab, or application window to a channel. The channel will be created if a channel corresponding to the Channel Options passed does not exist. If you have not entered the channel via joinChannel or publishToChannel methods then a model for Self will be created.
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.publishScreenToChannel(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
}
});
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 room |
Options
Name | Type | Default Value | Description |
---|---|---|---|
channel (required) | Object | Channel Options | |
capabilities (optional) (deprecated) | Array | The list of all capabilities to publish with. | |
mediaConstraints (optional) | Object | {screen: true} | Media constraints on the getting the user media. |
userMediaStream (optional) | Object | alternative to mediaConstraints - you can pass user media stream returned from getUserMedia. |
|
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 |
enableWildcardCapability (optional) (deprecated) | bool | true | Generate wildcard stream tokens to be appended to member’s stream uri. Reduces time for subscribing to published stream. |
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: {monitorFrameRate: false, videoBitRateThreshold: 1000, conditionCountForNotificationThreshold: 8}} |
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 |
Publish Screen 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
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
}
});
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 |
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 |
Room Express
Single-step configuration based API for setting up a room - a solution for all your other streaming applications including Group Broadcast, Group Chat, and One to One Chat. The Room Express extends the lower-level Room Service API to provide easy solutions to:
- Join, create, and publish to a rooms
- Subscribe to streams of members in a room
Initializing
var roomExpress = new sdk.express.RoomExpress(options);
Options
Name | Type | Description |
---|---|---|
adminApiProxyClient (optional) (deprecated) | [object AdminApiProxyClient] | It manages tokens if they are not passed in via options. Can not be used together with authToken, publishToken and streamToken options. |
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 | A token used for authentication. |
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. |
Clean Up Room Express
Dispose of all connections and clean up handlers.
roomExpress.dispose();
Join a Room
Join a room and automatically subscribe to member changes.
var options = {
role: 'Audience',
alias: 'MyAwesomeRoomAlias', // Not required but if its provided we will use this as the alias instead of pre-generating one for you.
screenName: 'MyAwesomeScreenName'
};
roomExpress.joinRoom(options, function joinRoomCallback(error, response) {
if (error) {
// Handle error
}
if (response.status === 'room-not-found') {
// Handle room not found - Create a Room Or Publish to a Room
} else if (response.status !== 'ok') {
// Handle error
}
// Successfully joined room
if (response.status === 'ok' && response.roomService) {
// Do something with roomService
}
}, function membersChangedCallback(members) {
// Successfully subscribed to observable members
// Do something with members
});
Parameters
Name | Type | Description |
---|---|---|
options (required) | Options | Options to join room with |
joinRoomCallback (required) | Function | Function to call on success/failure of joining the room |
membersChangedCallback (required) | Function | Function to call on when the participant members in the room changes. Returns array of Members. |
Options
Name | Type | Default Value | Description |
---|---|---|---|
role (required) | String | Member Role to join room as | |
alias (required) | String | Alias of the room to view | |
roomId (optional) | String | Alternative to alias - Id of the room to view | |
screenName (optional) | String | Member screen name to join room with | |
streams (optional) | Array of Objects | Streams to join room with |
Express Join Room Callback Arguments
Name | Type | Description |
---|---|---|
status | String | The status of the operation. See Join Room Callback Status Codes |
roomService | [object RoomService] | Phenix room service object |
room | [object Room] | Immutable Phenix room object |
Subscribe to a Member’s Stream
Subscribe to a room member’s stream and automatically handle audio and video state changes.
var memberStream = member.getObservableStreams().getValue()[0];
var options = {
videoElement: document.querySelector('#myVideoId')
};
roomExpress.subscribeToMemberStream(memberStream, options, function callback(error, response) {
if (error) {
// Handle error
}
if (response.status !== 'ok') {
// Handle error
}
// Successfully subscribed to stream
if (response.status === 'ok' && response.mediaStream) {
// Do something with mediaStream
}
});
Parameters
Name | Type | Description |
---|---|---|
memberStream (required) | [object Stream] | The room member’s stream to subscribe to |
options (required) | Subscribe to Member’s Stream Options | PCast Express Subscribe Options to subscribe to member stream with. |
callback (required) | Function | Function to call on success/failure of subscribing to the member stream |
Subscribe to Member’s Stream Options
Name | Type | Default Value | Description |
---|---|---|---|
streamToken (optional) | String | The subscribe token generated using the Admin API. If not passed one will be generated automatically by querying the backend uri that was passed when instantiating the Express API. | |
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 | Monitor Options | |
connectOptions (optional) | Array of Strings | List of options for subscribing | |
tags (optional) | Array of Strings | Tags for the stream | |
subscriberOptions (optional) | [Object SubscriberOptions] | Additional options to use when subscribing. |
Publish to a Room
Publish to a local or remote media to a room. The room will be created if a room corresponding to the Room Options passed does not exist. If you have not entered the room via joinRoom or publishToRoom methods then a model for Self will be created.
var options = {
room: {
name: 'MyAwesomeRoom',
alias: 'MyAwesomeRoomAlias' // Not required but if its provided we will use this as the alias instead of pre-generating one for you.
},
streamType: 'User',
memberRole: 'Participant',
publishToken: 'DIGEST:...',
mediaConstraints: {audio: true, video: true},
videoElement: document.querySelector('#myVideoId')
};
roomExpress.publishToRoom(options, function callback(error, response) {
if (error) {
// Handle error
}
if (response.status !== 'ok') {
// Handle error
}
// Successfully published to room
if (response.status === 'ok' && response.publisher) {
// Do something with publisher
}
});
Parameters
Name | Type | Description |
---|---|---|
options (required) | Options | Options to publish to room with |
callback (required) | Function | Function to call on success/failure of publishing to the room |
Options
Name | Type | Default Value | Description |
---|---|---|---|
room (required) | Object | Room Options | |
streamType (required) | String | Type of stream to publish. See Stream Types | |
memberRole (required) | String | Role of member to join room as (used if not already in room). See Member Roles | |
capabilities (optional) (deprecated) | Array | The list of all capabilities to publish with. | |
mediaConstraints (required) | Object | Media constraints on the getting the user media. For example - {audio: true, video: true} |
|
userMediaStream (optional) | Object | alternative to getUserMediaOptions - you can pass user media stream returned from getUserMedia. |
|
streamUri (optional) | String | alternative to getUserMediaOptions . Use to publish remote media. Link to remote media (mp4, rtmp, etc.) |
|
enableWildcardCapability (optional) (deprecated) | bool | true | Generate wildcard stream tokens to be appended to member’s stream uri. Reduces time for subscribing to published stream. |
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. |
Publish To Room Callback Arguments
Name | Type | Description |
---|---|---|
status | String | The status of the operation. See Publish Callback Status Codes |
publisher | [object Publisher] | Phenix publisher object |
Publish Screen to a Room
Publish your screen, tab, or application window to a room. The room will be created if a room corresponding to the Room Options passed does not exist. If you have not entered the room via joinRoom or publishToRoom methods then a model for Self will be created.
var options = {
room: {
name: 'MyAwesomeRoom',
alias: 'MyAwesomeRoomAlias' // Not required but if its provided we will use this as the alias instead of pre-generating one for you.
},
publishToken: 'DIGEST:...',
streamType: 'User',
memberRole: 'Participant',
videoElement: document.querySelector('#myVideoId')
};
roomExpress.publishScreenToRoom(options, function callback(error, response) {
if (error) {
// Handle error
}
if (response.status !== 'ok') {
// Handle error
}
// Successfully published to room
if (response.status === 'ok' && response.publisher) {
// Do something with publisher
}
});
Parameters
Name | Type | Description |
---|---|---|
options (required) | Options | Options to publish to room with |
callback (required) | Function | Function to call on success/failure of publishing to the room |
Options
Name | Type | Default Value | Description |
---|---|---|---|
room (required) | Object | Room Options | |
streamType (required) | String | Type of stream to publish. See Stream Types | |
memberRole (required) | String | Role of member to join room as (used if not already in room). See Member Roles | |
capabilities (optional) (deprecated) | Array | The list of all capabilities to publish with. | |
mediaConstraints (optional) | Object | {screen: true} | Media constraints on the getting the user media. |
userMediaStream (optional) | Object | alternative to getUserMediaOptions - you can pass user media stream returned from getUserMedia. |
|
enableWildcardCapability (optional) (deprecated) | bool | false | Generate wildcard stream tokens to be appended to member’s stream uri. Reduces time for subscribing to published stream. |
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: {monitorFrameRate: false, videoBitRateThreshold: 1000, conditionCountForNotificationThreshold: 8}} |
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 |
Publish Screen To Room 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 Room
Create a room of any type.
var options = {
room: {
name: 'MyAwesomeRoom',
alias: 'MyAwesomeRoomAlias' // Not required but if its provided we will use this as the alias instead of pre-generating one for you.
}
};
roomExpress.createRoom(options, function callback(error, response) {
if (error) {
// Handle error
}
if (response.status === 'already-exists') {
// Room already exists
// Do something with roomService
} else if (response.status !== 'ok') {
// Handle error
}
// Successfully created room
if (response.status === 'ok' && response.room) {
// Do something with room
}
});
Options
Name | Type | Default Value | Description |
---|---|---|---|
room (required) | Object | Room Options |
Express Create Room Callback Arguments
Name | Type | Description |
---|---|---|
status | String | The status of the operation. See Create Room Callback Status Codes |
room | [object Room] | Immutable Phenix room object |
Features
The list of features that you would like to support in order of preference. If a feature is not supported for playback on a device OR the published stream does not have that feature enabled (via capabilities) then the SDK will fall back to the next feature.
Default Features
By default, our SDK uses [‘real-time’, ‘dash’, ‘hls’].
Supported Features
Type | Description |
---|---|
real-time | Use Web RTC for delivery |
rtmp | Use rtmp (flash player required) for delivery |
dash | Use dash for delivery (requires MSE support) |
hls | Use hls for delivery (requires MSE or Native HLS) |
Enabling only real time playback
Pass [‘real-time’] as the features to the ChannelExpress or RoomExpress constructor options.
const channelExpress = new sdk.express.ChannelExpress({features: ['real-time']});
Digging Deeper - PCast Express
The PCast Express API extends the PCast API to provide a single-step, configuration based API for:
- Publishing local medias
- Publishing remote media (ingest)
- Subscribing to published streams
This API is intended to be used as a supplement to the Room Express although it can be used to stream all on its own.
Initializing
var pcastExpress = new sdk.express.PCastExpress(options);
Options
Name | Type | Description |
---|---|---|
backendUri (required) | String | URL to your backend. We send requests here to authenticate and get streaming tokens. |
authenticationData (required) | Object | Your authentication data for the user. On every request, this will be sent to your backend through a HTTP POST request and all its attributes would be accessible on the request body. |
onError (optional) | Function | Function to be called when authentication fails or a failure occurs that is unrecoverable. |
authToken (optional) | String | The authentication token generated using the Admin API. If not passed one will be generated automatically by querying the provided backendUri (may happen multiple times depending on the lifetime of the session). |
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. |
Get PCast Express from Room Express
Get the underlying instance from an already instantiated Room Express. This is preferred to creating another instance as this will introduce more overhead.
var pcastExpress = roomExpress.getPCastExpress();
Publishing Local Media
Publish local user media:
- Camera
- Microphone
- Screen (on supported devices)
var options = {
publishToken: 'DIGEST:...',
mediaConstraints: {audio: true, video: true},
videoElement: document.querySelector('#myVideoId')
};
pcastExpress.publish(options, function callback(error, response) {
if (error) {
// Handle error
}
if (response.status !== 'ok') {
// Handle error
}
// Successfully published
if (response.status === 'ok' && response.publisher) {
// Do something with publisher
}
});
Parameters
Name | Type | Description |
---|---|---|
options (required) | object | Publish options |
callback (required) | function | Callback for error/success handling |
Publish options
Name | Type | Default Value | Description |
---|---|---|---|
capabilities (optional) (deprecated) | Array | The list of all capabilities to publish with. | |
mediaConstraints (required) | Object | Media constraints on the 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. |
|
resolution (optional) | number | 720 | Desired size for the video equal to the height for landscape and width for portrait aspect ratios. |
frameRate (optional) | number | 15 | Desired frame rate for the video |
aspectRatio (optional) | string | 16x9 | Desired aspect ratio for 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 |
Callback Arguments
Name | Type | Description |
---|---|---|
status | String | The status of the operation. See Publish Callback Status Codes |
publisher | [object Publisher] | Phenix publisher object |
Publishing Remote Media (Ingest)
Publish from remote sources into the Phenix platform. This enables us to distribute your source media using the Phenix platform. After publishing users may subscribe to the stream using either pcast subscribe or express subscribe.
var options = {
publishToken: 'DIGEST:...',
streamUri: 'https://routeToMyVideo/video.mp4',
videoElement: document.querySelector('#myVideoId')
};
pcastExpress.publishRemote(options, function callback(error, response) {
if (error) {
// Handle error
}
if (response.status !== 'ok') {
// Handle error
}
// Successfully published
if (response.status === 'ok' && response.publisher) {
// Do something with publisher
}
});
Parameters
Name | Type | Description |
---|---|---|
options (required) | object | Publish Remote options |
callback (required) | function | Callback for error/success handling |
Publish Remote Options
Name | Type | Default Value | Description |
---|---|---|---|
capabilities (optional) (deprecated) | Array | The list of all capabilities to publish with. | |
streamUri (required) | String | Link to remote media (mp4, rtmp, etc.) | |
publishToken (optional) | String | This token is a publish token that will include all capabilities and access rights to publish. To publish from external resource your token need to have publish-uri capability. |
|
connectOptions (optional) | Array of Strings | List of options for publishing from a remote source. | |
tags (optional) | Array of Strings | Tags for the stream | |
frameRate (optional) | Object | Frame rate constraints. For example - {max: 30, exact: 30} |
|
prerollSkipDuration (optional) | int | 500 | The amount of milliseconds to skip at the beginning of the media. |
Callback Arguments
Name | Type | Description |
---|---|---|
status | String | The status of the operation. See Publish Callback Status Codes |
publisher | [object Publisher] | Phenix publisher object |
Publish a Screen Share
Publish your screen, tab, or application window. This method optimizes the monitoring and delivery of the stream for the typical conditions for screen sharing. Supported on both Firefox and Chrome. See Screen Sharing for more information on support.
var options = {
streamToken: 'DIGEST:...',
videoElement: document.querySelector('#myVideoId')
};
pcastExpress.publishScreen(options, function callback(error, response) {
if (error) {
// Handle error
}
if (response.status !== 'ok') {
// Handle error
}
// Successfully published
if (response.status === 'ok' && response.publisher) {
// Do something with publisher
}
});
Parameters
Name | Type | Description |
---|---|---|
options (required) | object | Publish Screen options |
callback (required) | function | Callback for error/success handling |
Publish Screen Options
Name | Type | Default Value | Description |
---|---|---|---|
capabilities (optional) (deprecated) | Array | The list of all capabilities to publish with. | |
mediaConstraints (optional) | Object | {screen: true} | Media constraints on the getting the user media. |
userMediaStream (optional) | Object | alternative to mediaConstraints - you can pass user media stream returned from getUserMedia. |
|
resolution (optional) | number | 720 | Desired size for the video |
frameRate (optional) | number | 15 | Desired frame rate for the video |
aspectRatio (optional) | string | 16x9 | Desired aspect ratio for 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: {monitorFrameRate: false, videoBitRateThreshold: 1000, conditionCountForNotificationThreshold: 8}} |
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 |
Callback Arguments
Name | Type | Description |
---|---|---|
status | String | The status of the operation. See Publish Callback Status Codes |
publisher | [object Publisher] | Phenix publisher object |
Subscribing to Published Media
Subscribe to streams published with the Phenix platform
var options = {
streamId: publisher.getStreamId(),
publishToken: 'DIGEST:...',
videoElement: document.querySelector('#myVideoId')
};
pcastExpress.subscribe(options, function callback(error, response) {
if (error) {
// Handle error
}
if (response.status !== 'ok') {
// Handle error
}
// Successfully subscribed
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
}
});
}
}
});
Parameters
Name | Type | Description |
---|---|---|
options (required) | object | Subscribe options |
callback (required) | function | Callback for error/success handling |
Subscribe Options
Name | Type | Default Value | Description |
---|---|---|---|
streamId (required) | String | The stream ID of the published stream | |
capabilities (optional) (deprecated) | Array | The list of all capabilities to subscribe with. | |
streamToken (optional) | String | A stream token used to connect to the stream. | |
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 | Monitor Options | |
connectOptions (optional) | Array of Strings | List of options for subscribing | |
tags (optional) | Array of Strings | Tags for the stream | |
subscriberOptions (optional) | [Object SubscriberOptions] | Additional options to use when subscribing. |
Sample Monitor Options
var monitorOptions = {
options: {
// Optional: Additional options for monitoring a stream
conditionCountForNotificationThreshold: 4
// Number of conditions before triggering callback
},
callback: function monitorCallback(error, response) {
// Optional: Handle monitor event
if (error) {
// Handle error
}
if (response.retry) {
response.retry();
// Re-connects publisher or subscriber stream
}
}
}
Monitor Options
Name | Type | Default Value | Description |
---|---|---|---|
options (optional) | Object | Additional Monitoring options | |
callback (optional) | Function | call function for handling monitor event |
Additional Monitoring options
Name | Type | Default Value | Description |
---|---|---|---|
conditionCountForNotificationThreshold | Number | 3 | Number of consecutive “conditions” that can occur before the callback is triggered. A condition is counted whenever one of the below thresholds is violated. |
frameRateThreshold | Number | 2 | Framerate below which the condition count is incremented (fps) |
videoBitRateThreshold | Number | 6000 | Video bitrate below which the condition count is incremented (bps) |
audioBitRateThreshold | Number | 5000 | Audio bitrate below which the condition count is incremented (bps) |
monitoringInterval | Number | 4000 | When the state is healthy, how often to check the state (milliseconds) |
conditionMonitoringInterval | Number | 1500 | After a condition, how often to check the state (milliseconds) |
monitorFrameRate | Bool | true | Enable or disable the frameRateThreshold |
monitorBitRate | Bool | true | Enable or disable the videoBitRateThreshold and audioBitRateThreshold |
monitorState | Bool | true | Enable or disable monitoring of the native state of the RTCPeerConnection |
Express Subscribe Callback Arguments
Name | Type | Description |
---|---|---|
status | String | The status of the operation. See Subscribe Callback Status Codes |
mediaStream | [object MediaStream] | Phenix media stream object |
renderer | [object Renderer] | Optionally returns Phenix renderer if videoElement option is passed in |
retry | Function | Optionally returns a function to retry subscription if unable to start stream |
Subscribing to Screen Share
Subscribe to screen share streams published with the Phenix platform. This method optimizes the monitoring and delivery of the stream for the typical conditions for screen sharing.
var options = {
streamId: publisher.getStreamId(),
capabilties: [], // Defaults to Real-Time
videoElement: document.querySelector('#myVideoId')
};
pcastExpress.subscribe(options, function callback(error, response) {
if (error) {
// Handle error
}
if (response.status !== 'ok') {
// Handle error
}
// Successfully subscribed
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
}
});
}
}
});
Parameters
Name | Type | Description |
---|---|---|
options (required) | object | Subscribe options |
callback (required) | function | Callback for error/success handling |
Subscribe To Screen Share Options
Name | Type | Default Value | Description |
---|---|---|---|
streamId (required) | String | The stream ID of the published stream | |
capabilities (optional) (deprecated) | Array | The list of all capabilities to subscribe with. | |
streamToken (optional) | String | A stream token used to connect to the stream. | |
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: {monitorFrameRate: false, videoBitRateThreshold: 1000, conditionCountForNotificationThreshold: 8}} |
Options for monitoring a publisher for failure. |
connectOptions (optional) | Array of Strings | List of options for subscribing | |
tags (optional) | Array of Strings | Tags for the stream | |
subscriberOptions (optional) | [Object SubscriberOptions] | Additional options to use when subscribing. |
Subscribe to Screen Share Callback Arguments
Name | Type | Description |
---|---|---|
status | String | The status of the operation. See Subscribe Callback Status Codes |
mediaStream | [object MediaStream] | Phenix media stream object |
renderer | [object Renderer] | Optionally returns Phenix renderer if videoElement option is passed in |
retry | Function | Optionally returns a function to retry subscription if unable to start stream |
Express Get User Media
Get local user media. Use for more granular control over requesting media and handling failure. We automatically resolve any constraint errors when getting the user media:
- for a resolution issue (width or height): drop to the next closest resolution (resolution isn’t supported on the requested device)
- for a frame rate issue: remove the frame rate constraint (frame rate isn’t supported on device)
- for an aspect ratio issue: drop to next aspect ratio at highest requested resolution (aspect ratio at resolutions is not supported)
var options = {
mediaConstraints: {audio: true, video: true},
resolution: 1080,
frameRate: 30,
aspectRatio: '4x3'
};
pcastExpress.getUserMedia(options, function callback(error, response) {
if (error) {
// Handle error
}
if (response.status !== 'ok') {
// Handle error
}
// Successfully got user media
if (response.status === 'ok' && response.userMedia) {
// Do something with userMedia
}
});
Parameters
Name | Type | Description |
---|---|---|
options (required) | object | Publish options |
callback (required) | function | Callback for error/success handling |
Get User Media options
Name | Type | Default Value | Description |
---|---|---|---|
mediaConstraints (required) | Object | Media constraints on the getting the user media. For example - {audio: true, video: true} |
|
resolution (optional) | number | 720 | Desired size of the video |
frameRate (optional) | number | 15 | Desired frame rate for the video |
aspectRatio (optional) | string | 16x9 | Desired aspect ratio for the video |
onResolveMedia (optional) | function | Returns the options that were used to successfully get user media |
Callback Arguments
Name | Type | Description |
---|---|---|
status | String | The status of the operation. |
userMedia | native MediaStream | The browser’s native media stream object. |
Supported Resolutions
Any resolution may be passed. If we are unable to get the user media at that resolution we will drop to the next closest resolution at that aspect ratio in the table below. We will continue dropping to the next closest resolution until we run out of options or the user media is successfully received. Similarly, when all resolution options at an aspect ratio are exhausted we will attempt to resolve the highest resolution requested at the next lowest aspect ratio.
Aspect Ratio | Resolution (Longer dimension) | Shorter dimension | Description |
---|---|---|---|
9x16 | 3840 | 2160 | 4K (UHD) |
1920 | 1080 | 1080p (FHD) | |
1366 | 768 | ||
1280 | 720 | 720p (HD) | |
1024 | 576 | ||
854 | 480 | 480p | |
640 | 360 | 360p (nHD) | |
320 | 180 | ||
3x4 | 1600 | 1200 | UXGA |
1440 | 1080 | ||
960 | 720 | ||
800 | 600 | SVGA | |
768 | 576 | ||
640 | 480 | VGA | |
480 | 360 | ||
320 | 240 | QVGA | |
160 | 120 | QQVGA | |
16x9 | 2160 | 3840 | 4K (UHD) |
1080 | 1920 | 1080p (FHD) | |
768 | 1366 | ||
720 | 1280 | 720p (HD) | |
576 | 1024 | ||
480 | 854 | 480p | |
360 | 640 | 360p (nHD) | |
180 | 320 | ||
4x3 | 1200 | 1600 | UXGA |
1080 | 1440 | ||
720 | 960 | ||
600 | 800 | SVGA | |
576 | 768 | ||
480 | 640 | VGA | |
360 | 480 | ||
240 | 320 | QVGA | |
120 | 160 | QQVGA |
Supported Frame Rates
60, 30, 15, or any other value. If a frame rate is not resolved we will request media without the frame rate constraint.
Get PCast
Get the underlying instance of the PCast. This is preferred to creating another instance as this will introduce more overhead.
var pcast = pcastExpress.getPCast();
Clean up PCast Express
Dispose of all active connections and clean up all handlers.
var pcastExpress = pcastExpress.dispose();
Admin API Proxy
Used for requesting Streaming tokens and Authentication tokens.
const adminApiProxyClient = new sdk.net.AdminApiProxyClient();
HTTP Based Requests
By default we send HTTP requests to retrieve Streaming and Authentication tokens.
Name | Signature | Returns | Default |
---|---|---|---|
getBackendUri | () | string | “ |
setBackendUri | (uri) | void | |
getEndpointPaths | () | [Object EndpointPaths] | Default Endpoints |
setEndpointPaths | ([Object EndpointPaths]) | void | |
getAuthenticationData | () | [Object] | |
setAuthenticationData | ([Object]) | void | |
getAuthenticationDataLocationInPayload | () | string | ‘body’ |
setAuthenticationDataLocationInPayload | (location) | string |
Backend Uri
Url to your backend. We send a request here to authenticate and get streaming tokens.
adminApiProxyClient.setBackendUri('https://mybackend.com/');
const backendUri = adminApiProxyClient.getBackendUri();
Endpoint Paths
Paths to request Streaming and Authentication tokens from.
adminApiProxyClient.setEndpointPaths({createStreamTokenPath: '/phenix/stream', createAuthTokenPath: '/phenix/auth'});
const endPointPaths = adminApiProxyClient.getEndpointPaths();
[object EndpointPaths]
Name | Type | Default Value | Description |
---|---|---|---|
createStreamTokenPath (required) | String | ‘/stream’ | The endpoint to request a stream token from. |
createAuthTokenPath (required) | String | ‘/auth’ | The endpoint to request an auth token from. |
Authentication Data
Your authentication data for the user. We add this on every request made. You may use any of the Locations in the http payload.
adminApiProxyClient.setAuthenticationData({userName: 'myUserName', password: 'UserPassword'});
const authenticationData = adminApiProxyClient.getAuthenticationData();
Authentication Data Location in Payload
Location of the authentication data in the HTTP payload.
adminApiProxyClient.setAuthenticationDataLocationInPayload('header');
const location = adminApiProxyClient.getAuthenticationDataLocationInPayload();
Locations in Payload
Location | Description |
---|---|
body | Add the authenticationData object to the body of the request |
header | Add the authenticationData object as headers |
Custom Requests
Provide tokens using your own mechanism. Use this if you are pre-generating tokens and providing them to your users.
Name | Signature | Returns | Default |
---|---|---|---|
getRequestHandler | () | function | null |
setRequestHandler | (function) | void |
adminApiProxyClient.setRequestHandler(function handleRequestCallback(requestType, data, callback) {
myCustomTokenFactory.createToken(type, data).then(token => {
return callback(token);
});
});
const requestHandler = adminApiProxyClient.getRequestHandler();
Parameters
Name | Type | Description |
---|---|---|
handleRequestCallback (required) | Function | Handler for token generation. This function is called every time a new token is needed. |
Handle Request Callback
Name | Type | Description |
---|---|---|
requestType | String | Which token to generate. |
data | [Object] | The data needed to generate the token. Matches the API for generating stream tokens or generating auth tokens. |
callback | Function | The callback to call with the requested token. |
Request Type
Type | Description |
---|---|
auth | Generate an auth token. |
stream | Generate a stream token. |
Web Examples
You can find our Web examples on GitHub.
Channel Publisher
A simple example that shows how to publish to a channel using the Phenix Web SDK.
Native GUM Channel Publisher
An advanced example that shows how to publish a native GetUserMedia stream to a channel using the Phenix Web SDK. This allows, for example, to publish a portrait video in browsers that support capturing with the corresponding GetUserMedia constraints.
Channel Viewer 2
A simple example that shows how to view a channel using the Phenix Web SDK 2.
Channel Viewer
A simple example that shows how to view a channel using the Phenix Web SDK.
Embedded Channel Frame
A simple example that shows how to view a channel using the Embedded Channel.