Web PCast™ API - PhenixRTS Docs

PCast™ API

Create

const pcast = new sdk.lowLevel.PCast(options);

Create Options

Name Type Default Description
disableMultiplePCastInstanceWarning (optional) boolean false Whether or not to disable logging of a warning message when multiple instances of a pcast are in use at the same time.
disableGlobalErrorListener (optional) boolean false Whether or not to disable listening and logging of window.onerror events.
disableBeforeUnload (optional) boolean false Whether or not to dispose of the pcast instance on unload events
disableConsoleLogging (optional) boolean false Whether or not to disable console logging
deviceId (optional) string '' A unique identifier to use for analytics purposes.
features (optional) Array Features The list of features to support for subscribers.

Connect and Authenticate

Connect and Authenticate example

pcast.start(
  authToken,
  function authenticationCallback(pcast, status, sessionId) {
    // Upon success, called with status="ok" and a valid "sessionId"
    // At any time when authentication is required with status="unauthorized"
  },
  function onlineCallback(pcast) {
    // Called when connected to the streaming platform
  },
  function offlineCallback(pcast) {
    // Called when disconnected from the streaming platform
  }
);

Authentication Parameters

Name Type Description
authToken (required) string The authentication token generated using the Phenix EdgeAuth library
authenticationCallback (required) function (pcast, status, sessionId) Called upon successful authentication or when authentication failed or has to be redone. Upon successful authentication, the authenticationCallback will be called with status="ok". If at any time a new authToken is required, then the authenticationCallback is called with status="unauthorized" to indicate that we are no longer authenticated.
onlineCallback (required) function (pcast) Called when the client is connected to the streaming platform
offlineCallback (required) function (pcast) Called when the client is disconnected from the streaming platform. Ongoing streams may continue while we are temporarily disconnected. However, no new streams can be started while being disconnected. The client automatically tries to reconnect and will call onlineCallback when it succeeds in doing so or eventually call authenticationCallback to indicate that re-authentication is required.

Authentication Callback Status Codes

Status Valid Fields Description
ok sessionId Authentication succeeded, the sessionId is populated
unauthorized none Authentication failed or re-authentication required
capacity none The system is currently experiencing heavy load and is adding new resources - Please try again shortly
network-unavailable none Unable to connect to the backend
varies none Authentication failed for other reasons

Disconnecting

Disconnect example:

pcast.stop();

This will trigger the offlineCallback provided in pcast.start().

Stopping a client will terminate any streams published and viewed by the client.

Getting Local User Media

Acquire the local user media stream using the built-in browser interface.

Acquire the local user media stream

var options = {
  audio: true,
  video: true,
};

pcast.getUserMedia(
  options,
  function userMediaCallback(pcast, status, userMediaStream, error) {
    // status="ok" with a userMediaStream matching the provided options
    // status="failed" otherwise with error
  }
);

User Media Parameters

Name Type Description
options (required) [object Options] The options defining the requested user media stream
userMediaCallback (required) function (pcast, status, userMediaStream, error) Upon acquiring of the user media stream, the userMediaCallback will be called with status="ok". If the user media is currently used by another application, then you may receive a status="conflict". If the operation fails with status="failed" then the error describes the reason of why the acquisition of the local user media failed.

[object Options]

Name Type Default Value Description
audio boolean or object false Whether or not to acquire the local microphone stream or a constraint definition for audio
video boolean or object false Whether or not to acquire the local video stream or a constraint definition for video
screen boolean or object false Whether or not to share the local screen/application or a constraint definition for screen

Constraints definitions can be anything supported by the browser. Please be aware that Firefox 38+ supports the newer constraint format. Different browsers may support and interpret constraints differently. Most recent version will return an error if constraints cannot be fulfilled.

User Media Callback Status Codes

Status Valid Fields Description
ok userMediaStream Operation succeeded and a valid user media stream is provided
conflict error Operation failed due to user media being unavailable, e.g. another application is using the camera
failed error Operation failed and the error describes the cause
HTTPS is the new standard

Please serve your page over HTTPS. Starting with Google Chrome 47, HTTP applications will no longer be allowed access to the user's camera and microphone and any call to getUserMedia() will be denied.

Publish a Stream

var tags = ['my-tag'];

pcast.publish(
  streamToken,
  userMediaStream,
  function publishCallback(pcast, status, publisher) {
    // status="ok" with "publisher" object to control the stream
    // The "streamId" of the publisher
    var streamId = publisher.getStreamId();

if (publisher.hasEnded()) {
      // Checks if the publisher has ended
    }

publisher.setPublisherEndedCallback(
      function publisherEndedCallback(publisher, reason, reasonDescription) {
        // Called when the stream has ended
      }
    );

// To stop later
    publisher.stop('I-am-done-publishing');
  },
  tags
);

Publish Parameters

Name Type Description
streamToken (required) string The publish token generated using the Phenix EdgeAuth library
userMediaStream (required) [object UserMediaStream] The local user media stream acquired with pcast.getUserMedia(...)
publishCallback (required) function Called upon completion of the operation
tags (optional) array of strings Tags that will be provided with the stream notifications to your backend callback endpoint

Publish Callback Arguments

Name Type Description
pcast [object PCast] The pcast instance
status string The status of the operation
publisher [object Publisher] The publisher if the operation succeeded

Publish Callback Status Codes

Status Description
ok The operation succeeded
failed The operation failed
capacity The system is currently experiencing heavy load and is adding new resources - Please try again shortly

[object Publisher]

Name Signature Returns Description
getStreamId () string The stream ID of the published stream
hasEnded () boolean True, if the stream has ended; false otherwise
setPublisherEndedCallback (function publisherEndedCallback(publisher, reason, reasonDescription)) void Sets the callback for stream ended notifications
stop (string reason) void Ends the stream with the provided reason
monitor (options, monitorCallback) void Enables monitoring of publisher status. See Monitor a Publisher

Publisher Ended Callback Arguments

Name Type Description
publisher [object Publisher] The publisher instance the notification belongs to
reason string The reason of the why the stream ended
reasonDescription string The custom message passed to stop() or more details

Stream Ended Reason

Reason Description
ended The stream ended normally
failed The stream failed
censored The stream was censored
maintenance A maintenance event caused this stream to be terminated
capacity The stream was terminated due to capacity limitations
app-background The stream was terminated due to the mobile app entering into the background
custom A custom termination reason is provided in the "reasonDescription" field

Monitor A Publisher

currentPublisher.monitor(
  { conditionCountForNotificationThreshold: 8 },
  function (publisher, reason, description) {
    if (currentPublisher === publisher) {
      switch (reason) {
        case 'client-side-failure':
          // handle failure event, redo stream
          break;
        default:
          // no failure has occurred, handle monitor event
          break;
      }
    }
  }
);

Monitor Publisher Parameters

Name Type Description
options (required) [object Options] Options for the publisher monitor event.
monitorCallback (required) function (publisher, reason, description) Called upon every monitor event until publisher ends.

[object Options]

Name Type Default Value Description
frameRateThreshold int 2 Threshold of frame rate at which monitor event is triggered
videoBitRateThreshold int 6000 Threshold of video bit rate at which monitor event is triggered
audioBitRateThreshold int 5000 Threshold of audio bit rate at which monitor event is triggered
conditionCountForNotificationThreshold int 3 The number of times any condition should be met before monitor event is triggered
monitoringInterval int 4000 How frequently the publisher should be monitored if the condition count is not exceeded.
monitorFrameRate boolean true Should the frame rate be monitored?
monitorBitRate boolean true Should the bit rate be monitored?
monitorState boolean true Should the publisher's state be monitored?

Monitor Publisher Callback Arguments

Name Type Description
publisher [object Publisher] The publisher instance
reason string The reason for the monitor event
description string A more detailed description of the reason for the monitor event

Monitor Publisher Callback Reasons

Status Description
client-side-failure A failure occurred on the client
default Any other monitor event reason

Subscribe to a Stream

pcast.subscribe(
  streamToken,
  function subscribeCallback(pcast, status, mediaStream) {
    // status="ok" with "mediaStream" object to control the stream

mediaStream.setStreamEndedCallback(
      function streamEndedCallback(mediaStream, reason, reasonDescription) {
        // Called when the stream has ended
      }
    );

// To stop later
    mediaStream.stop('I-am-done-watching');
  },
  subscriberOptions
);

Subscribe Parameters

Name Type Description
streamToken (required) string The publish token generated using the Phenix EdgeAuth library
subscribeCallback (required) function Called upon completion of the operation
subscriberOptions (optional) [Object SubscriberOptions] The options to subscribe with

Subscribe Callback Arguments

Name Type Description
pcast [object PCast] The pcast instance
status string The status of the operation
mediaStream [object MediaStream] The media stream if the operation succeeded

Subscribe Callback Status Codes

Status Description
ok The operation succeeded
failed The operation failed
stream-ended The stream has ended
capacity The system is currently experiencing heavy load and is adding new resources - Please try again shortly

[object MediaStream]

Name Signature Returns Description
setStreamEndedCallback (function streamEndedCallback(mediaStream, reason, reasonDescription)) void Sets the callback for stream ended notifications
stop (string reason) void Ends the stream with the provided reason
createRenderer () [object Renderer] Creates a renderer that can be used to show the stream on screen
monitor (options, monitorCallback) void Enables monitoring of media stream status Monitor a Media Stream
select (trackSelectCallback) [object MediaStream] Returns a new media stream with all tracks that match conditions in callback. See Selecting a Subset of Media Tracks

Stream Ended Callback Arguments

Name Type Description
mediaStream [object MediaStream] The media stream instance the notification belongs to
reason string The reason of the why the stream ended
reasonDescription string Custom message passed to stop() or a more detailed message

Stream Ended Reason

Monitor A Media Stream

currentMediaStream.monitor({}, function (mediaStream, reason, description) {
  if (currentMediaStream === mediaStream) {
    switch (reason) {
      case 'client-side-failure':
        // handle failure event, redo stream
        break;
      default:
        // no failure has occurred, handle monitor event
        break;
    }
  }
});

Monitor Media Stream Parameters

Name Type Description
options (required) [object Options] Options for the media stream monitor event.
monitorCallback (required) function (mediaStream, reason, description) Called upon every monitor event until media stream ends.

[object Options]

Monitor Media Stream Callback Arguments

Name Type Description
mediaStream [object MediaStream] The media stream instance
reason string The reason for the monitor event
description string A more detailed description of the reason for the monitor event

Monitor Media Stream Callback Reasons

Status Description
client-side-failure A failure occurred on the client
default Any other monitor event reason

Selecting A Subset Of Media Tracks

Enables you to select a subset of tracks from a single media stream returned from a subscribe event. Use this to get separate media streams for specific tracks and attach those media streams to different browser elements. Only supported with real-time streams.

var childMediaStream = mediaStream.select(function (track, index) {
  return track.kind === 'video';
});

Track Select Parameters

Name Type Description
trackSelectCallback (required) function (currentTrack, index) Function to execute for each track. Should return a boolean.

Track Select Callback Arguments

Name Type Description
currentTrack [object Track] The current track instance.
index int Current index of track. Derived from collection of tracks mediaStream.getTracks()

View a Stream

// Media stream acquired with pcast.subscribe(...)
var renderer = mediaStream.createRenderer();
var elementToAttachTo = document.getElementById('<ELEMENT_ID>');

renderer.start(elementToAttachTo);

// To stop later
renderer.stop();

View Stream Parameters

Name Type Description
elementToAttachTo (required) DOM <video /> element The DOM <video /> element used to render the stream

[object Renderer]

Name Signature Returns Description
start ([<video />] elementToAttachTo) void Start rending the stream in a DOM <video /> element. The element must be already inserted in the DOM at the time when start() is called
getStats () [object RendererStats] Receive the most recent video stats
stop () void Stop rendering the stream

Renderer Events

Name Arguments Description
ended reason The rendered has ended. The reason provides more detail.
error origin, exception An unhandled error occurred.
autoMuted reason The stream was automatically muted. A user-triggered action is required to unmute the video.
failedToPlay reason The stream failed to play. A user-triggered action is required to start playback.
Renderer Event autoMuted

The event is triggered with reason retry-play-muted when the player was automatically muted in order to facilitate auto play. The user is required to manually unmute the video.

Renderer Event failedToPlay

The event is triggered with reason failed-to-play if the playback is blocked by the browser, e.g., low battery mode.

The event is triggered with reason failed-to-play-unmuted if the playback is blocked by the browser and the auto mute retry features is disabled.

The event is triggered with reason paused-by-background if the playback is blocked after the page resumed from background.

[object RendererStats]

Name Type Unit of Measure Default Value Description
lag int seconds 0 The runtime end-to-end latency from the source to the destination.
width int pixels 0 The current video width
height int pixels 0 The current video height
currentTime int seconds 0 The amount of time the stream has been active
networkState int NA See networkState

Handling Dimension Changes

Cameras may be switched at runtime and devices may be rotated. Register a handler to receive a notification whenever the video dimension changes.

var renderer = ...
renderer.start(...);

// subscribe to dimension changed event
renderer.setVideoDisplayDimensionsChangedCallback(function (renderer, displayDimensions) {
    // Can get called multiple times while rendering a stream
    // Values in displayDimensions.width, displayDimensions.height
}, options);

Dimension Change Parameters

Name Type Description
dimensionsChangedCallback (required) function (thisRenderer, newVideoDimensions) Function to execute for each display (video) dimension change.
options (optional) [object Options] Options for monitoring of display dimension changes

[object Options]

Name Type Default Value Description
pollFrequency int 500 The frequency in milliseconds of how often the video dimensions are checked. The minimum allowed value is 15. If a value of less than 15 is specified, then the poll frequency is set to 15.

Get the Runtime Latency of a Stream from [object RendererStats]

Programmatically determine the end-to-end latency of a stream. The end-to-end latency for real-time streams is typically 300 milliseconds or lesser. DASH and HLS technologies vary greatly in terms of their end-to-end latency.

var renderer = ...
renderer.start(...);

var stats = renderer.getStats();

console.log(stats.lag);