NAV Navbar
Phenix logo
Version 2020.0.22
JavaScript

Web SDK - Low Level APIs

The following low level APIs are provided in the web sdk:

PCast API

Create

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

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
});

Parameters

Name Type Description
authToken (required) string The authentication token generated using the Admin API
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 experience 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
});

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 can not 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

Screen Sharing

Share your screen, tab, or application window. We support screen sharing on Chrome and Firefox. Https is required. Firefox works out of the box for versions 52+ and we provide a browser extension for Chrome. Browser extensions are limited to pre-specified domains. Please contact support if you need any assistance with this process.

var options = {};

// Options suitable to share a high resolution stream of the user's desktop

if (rtc.browser === 'Firefox' && rtc.browserVersion >= 52) {
    options.screen = {
        height: {min: 360, ideal: screen.height, max: screen.height},
        width: {min: 640, ideal: screen.width, max: screen.width},
        frameRate: {ideal: 3, max: 3}
    };
} else if (rtc.browser === 'Chrome') {
    options.screen = {
        mandatory: {
            maxHeight: screen.height,
            maxWidth: screen.width,
            maxFrameRate: 3
        }
    };
}

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

Use Your Own Extension

Pass your screen sharing extension ID when instantiating the PCast model. The format of your Extension must match the Phenix Extension.

var pcast = new sdk.PCast({screenSharingExtensionId: ''}); // Pass your screen sharing extension Id

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);

Parameters

Name Type Description
streamToken (required) string The publish token is generated using the Admin API
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 experience 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;
        }
    }
});

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?

Publish 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

Publish 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);

Parameters

Name Type Description
streamToken (required) string The publish token is generated using the Admin API
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 experience 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

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 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;
        }
    }
});

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]

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 media stream 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 media stream’s state be monitored?

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';
});

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();

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);

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]

Programtaically 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);

Room Service

Set up a room and manage members, streams, and chat. Some typical uses for rooms include:

To get started, create a room of the type associated with your need.

Initializing

First you will need to initialize a room service object. This object is used for creating, joining, and leaving a room. As well, use this object for managing the room you enter (active room), members, and the model of your Self.

var roomService = new sdk.RoomService(pcast);

Parameters

Name Type Description
pcast (required) [object PCast] Instantiated PCast object. Must already be authenticated

[object RoomService]

Name Signature Returns Description
start (role, screenName) void See Instantiate Self Member Model
getRoomInfo (roomId, alias, getRoomInfoCallback) [object Room] See Get Room Info
createRoom (room, createRoomCallback) [object Room] See Create a Room
enterRoom (roomId, alias, enterRoomCallback) [object Room] See Join a Room
leaveRoom (leaveRoomCallback) void See Leave a Room
getRoomChatService () [object ChatService] Returns instantiated chat service associated with active room
getSelf () Observable(of [object Member]) Observable of self member
getObservableActiveRoom () Observable(of [object Room]) Observable of the active room

Instantiate Self Member Model

Before entering a room the [object RoomService] must have a model of the member you would like to join as, or Self. The Self member model may be updated at any time by changing observable values and calling commitChanges. See Updating Self Model.

roomService.start(role, screenName);

Parameters

Name Type Description
role (required) String Self member role - see Member Roles
screenName (required) String Self member screen name

Update Self Model

Broadcast local changes of the Self model to all the members in the room. These changes are sent to our server which forwards the changes to all members in the room.

var self = roomService.getSelf();

self.getObservableScreenName.setValue('My New Screen Name');

// Commit changes to self if already in a room
self.commitChanges(function commitChangesCallback(error, response) {
    if (error) {
        // Handle error
    }

    if (response.status !== 'ok' && response.status !== 'not-in-room') {
        // Handle error
    }

    if (response.status === 'not-in-room') {
        // Changes not committed. Enter a room and the self model will automatically be committed.
    }

    if (response.status === 'ok') {
        // Successfully updated self
    }
});

Update Self Callback Arguments

Name Type Description
status String The status of the operation

Update Self Callback Status Codes

Status Description
ok Update self succeeded
not-in-room Update self failed. Not currently in a room - Join a room and changes will automatically be committed
<varies> Update self failed for other reasons

Set Self Streams

The self model must have at least one stream when joining the room as any member role besides Audience.

var self = roomService.getSelf();
var selfStream = {
    uri: publisher.getStreamId(),
    type: 'User',
    audioState: 'TrackEnabled',
    videoState: 'TrackEnabled'
};

self.setStreams([selfStream]);

Parameters

Name Type Description
uri (required) String Unique identifier for stream.
type (required) String Type of stream - see Stream Types
audioState (required) String State of the audio track - see Stream Track States
videoState (required) String State of the video track - see Stream Track States

Get Room Info

Get room info with the provided room details without joining the room.

roomService.getRoomInfo(roomId, alias, function getRoomInfoCallback(error, response) {
    if (error) {
        // Handle error
    }

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

    // Successfully got room info
    if (response.status === 'ok' && response.room) {
        // Do something with room
    }
});

Parameters

Name Type Description
roomId (required) String ID of the room
alias (optional) String Alternative to roomId - alias of the room
getRoomInfoCallback (required) Function Callback with the status of the request and the room model

Get Room Info Callback Arguments

Name Type Description
status String The status of the operation
room [object Room] Immutable room object

Get Room Info Callback Status Codes

Status Description
ok Get room info succeeded
not-found Get room info failed. Room does not exist - verify room data or create the room
<varies> Get room info failed for other reasons

Create a Room

Create a room with the provided details

roomService.createRoom(room, function createRoomCallback(error, response) {
    if (error) {
        // Handle error
    }

    if (response.status === 'already-exists') {
        // No action required
    }

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

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

Parameters

Name Type Description
room (required) Object Values of the room to create - See Room Options
getRoomInfoCallback (required) Function Callback with the status of the request and the room model

Room Options

Name Type Description
name (required) String Room Name
type (required) String Room Type
alias (Optional) String Room Alias. If not passed in, it will be generated for you
description (Optional) String Description of the Room

Create Room Callback Arguments

Name Type Description
status String The status of the operation
room [object Room] Immutable room object

Create Room Callback Status Codes

Status Description
ok Create room succeeded
already-exists Create room failed. Room already exists - verify room data and either join or create a different room
<varies> Create room failed for other reasons

Join a Room

Join a room with the Self model. After successfully joining a room that room becomes the active room and can be returned via the getObservableActiveRoom method.

roomService.enterRoom(roomId, alias, function enterRoomCallback(error, response) {
    if (error) {
        // Handle error
    }

    if (response.status === 'not-found') {
        // Handle room not found - createRoom
    }

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

    // Successfully entered room
    if (response.status === 'ok' && response.room) {
        // Do something with room model - now the active room
    }
});

Parameters

Name Type Description
roomId (required) String ID of the room
alias (optional) String Alternative to roomId - alias of the room
enterRoomCallback (required) Function Callback with the status of the request and the room model

Join Room Callback Arguments

Name Type Description
status String The status of the operation
room [object Room] Mutable room object

Join Room Callback Status Codes

Status Description
ok Join room succeeded
not-found Join room failed. Room does not exist - create room first
<varies> Join room failed for other reasons

Subscribe to Room Member Streams

After entering a room you may use the active room to get the observable members and associated metadata. Here we provide an example for parsing the stream ID associated with the member stream’s uri.

var observableActiveRoom = roomService.getObservableActiveRoom();
var activeRoom = observableActiveRoom.getValue();
var membersObservable = activeRoom.getObservableMembers();
var pcastStreamURIPrefix = 'pcast://phenixp2p.com/';

membersObservable.subscribe(function(members) {
    members.forEach(function(member) {
        var memberStreams = member.getObservableStreams().getValue();

        memberStreams.forEach(function (stream) {
            // Subscribe if its a PCast stream
            if (stream.uri.indexOf(pcastStreamURIPrefix) === 0) {
                var streamId = stream.uri.substring(pcastStreamURIPrefix.length, stream.uri.length);

                // subscribe with pcast.subscribe
            }
        })
    });
});

Update Room Model

Broadcast local changes of the Room model to all the members in the room. These changes are sent to our server which forwards the changes to all members in the room.

var room = roomService.getObservableActiveRoom().getValue();

room.getObservableDescription.setValue('My New Room Description');

// Commit changes to self if already in a room
room.commitChanges(function commitChangesCallback(error, response) {
    if (error) {
        // Handle error
    }

    if (response.status !== 'ok' && response.status !== 'not-in-room') {
        // Handle error
    }

    if (response.status === 'not-in-room') {
        // Changes not committed. Enter the room and then re-submit
    }

    if (response.status === 'ok') {
        // Successfully updated room
    }
});

Parameters

Name Type Description
commitChangesCallback (required) Function Callback with the status of the request

Update Room Callback Arguments

Name Type Description
status String The status of the operation

Update Room Callback Status Codes

Status Description
ok Update room succeeded
not-in-room Update room failed. Not currently in a room - Join a room first
<varies> Update room failed for other reasons

Leave a Room

Leave the current active room. Self is not modified.

roomService.leaveRoom(function leaveRoomCallback(error, response) {
    if (error) {
        // Handle error
    }

    if (response.status === 'not-in-room') {
        // Do nothing
    }

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

    // Successfully left room
    if (response.status === 'ok') {
        // No action required
    }
});

Parameters

Name Type Description
leaveRoomCallback (required) Function Callback with the status of the request

Leave Room Callback Arguments

Name Type Description
status String The status of the operation

Update Room Callback Status Codes

Status Description
ok Leave room succeeded
not-in-room Leave room failed. Not currently in a room. Do nothing
<varies> Leave room failed for other reasons

Room Model

The following details technical specifications for the Room, Members, and Streams.

[object Room]

Name Signature Returns Description
getRoomId () string The room ID
getObservableAlias () Observable(of string) Observable of room alias
getObservableName () Observable(of string) Observable of room name
getObservableDescription () Observable(of string) Observable of room description
getObservableType () Observable(of string) Observable of room type
getObservableMembers () Observable(of array) Observable of array of visible members in the room
getObservableBridgeId () Observable(of string) Observable of room bridgeId
getObservablePin () Observable(of string) Observable of room pin
toJson () object Returns room object with current observable values
commitChanges () void Attempts to update server room model with any changes made locally
reload () void Reverts all local changes to the server room model

Room Types

Type Description
DirectChat One to one chat
MultiPartyChat Many to many or few to many chat
ModeratedChat Moderated chat with integrated SIP Bridge for conferencing abilities (join by phone).
TownHall Chat with a few active participants or presenters and many audience or inactive participants
Channel View only room with a single active member at a time. Broadcast content to many viewers.

[object Member]

Name Signature Returns Description
getSessionId () string The session ID of the member in the room
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
setStreams (streams) void Set member streams. To be used only on self member model
toJson () object Returns member object with current observable values
commitChanges () void Attempts to update server member model with any changes made locally
reload () void Reverts all local changes to the server member model

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 that will be shared between all members. The simplest configuration would be to use a PCast StreamId as the streamUri. This associates streams published locally to the member and enables other room members to subscribe to that stream. See Subscribe to Room Member Streams.

Name Signature Returns Description
getUri () string The stream uri (may or may not be associated with phenix stream ID)
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
User General purpose stream
Presentation Presentation stream
Audio Audio-only stream

Stream Track States

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

Chat Service

The Chat Service provides the ability to:

All room members that are subscribed to the chat will receive the text messages. You must first enter the room before you may send and receive messages.

Initializing

First, instantiate the chat service. The Room Service exposes a method to get the chat associated with the active room.

var chatService = roomService.getChatService();

[object ChatService]

Name Signature Returns Description
start (batchSize) void Start receiving messages and store the most recent of size batchSize
stop () void Stop receiving messages
getObservableChatMessages () Observable(of Array) Get the observable of the most recent chat messages. This is a buffer of the most recent N messages up to a max of 100. See Listen for Chat Messages
getObservableChatEnabled () Observable(of Boolean) Get the observable of the enabled status of the chat service. Use this to disable or enable the chat.
sendMessageToRoom (message, callback) void Send a message to room.
getMessages (batchSize, afterMessageId, beforeMessageId, callback) Array(of [object ChatMessage]) Get chat message history

[object ChatMessage]

Name Type Description
messageId String Unique ID of message
timestamp Number Server UTC timestamp of message
from [object ChatMessageMember] Information on the member that sent the message
message String Chat message

[object ChatMessageMember]

Name Type Description
sessionId String Member’s session ID
screenName Number Screen name of the member
role String Member’s role. See Member Roles
lastUpdate Number Last time member was updated as UTC timestamp

Listen for Chat Messages in the Active Room

The chat service exposes an observable of the most recent N (batchSize) messages in the active room up to a max of 100 messages. To view older messages you will need to use the getMessages method.

var chatService = new roomService.getChatService();
var chatMessageObservable = chatService.getObservableChatMessages();
var batchSize = 10;

chatMessageObservable.subscribe(function(mostRecentChatMessages) {
    // Do something with chat messages
    // mostRecentChatMessages is an array of messages
    // The messages in the array are not guaranteed to be in order, and may contain duplicates
});

chatService.start(batchSize);

Send a Message to the Active Room

Send a single message to the active room. If the message is successfully sent the chatMessageObservable will trigger notifications on all subscribers with the new chat message.

var chatService = new roomService.getChatService();

chatService.start(batchSize);

chatService.sendMessageToRoom('My First Message', function sendMessageCallback(error, response) {
    if (error) {
        // handle error - send message again
    }

    if (response.status !== 'ok') {
        // handle error - send message again
    }

    if (response.status === 'ok') {
        // Successfully sent message
    }
});

Parameters

Name Type Description
message (required) String Message to send to the room
sendMessageCallback (required) Function Callback with the status of the request

Send Message Callback Arguments

Name Type Description
status String The status of the operation

Send Message Callback Status Codes

Status Description
ok Send message succeeded
<varies>

Chat Message History

Get messages older than the most recent N buffered in the chatMessageObservable.

Get the 10 most recent messages after a message:

var batchSize = 10;
var afterMessageId = 'MessageId1';
var beforeMessageId = null;

chatService.getMessages(batchSize, afterMessageId, beforeMessageId, function getMessagesCallback(error, response) {
    if (error) {
        // handle error - request messages again
    }

    if (response.status !== 'ok') {
        // handle error - request messages again
    }

    if (response.status === 'ok' && response.chatMessages) {
        // Successfully got chat messages
    }
});

Get all messages between two messages:

var batchSize = null;
var afterMessageId = 'MessageId1';
var beforeMessageId = 'MessageId2';

chatService.getMessages(batchSize, afterMessageId, beforeMessageId, function getMessagesCallback(error, response) {
    if (error) {
        // handle error - request messages again
    }

    if (response.status !== 'ok') {
        // handle error - request messages again
    }

    if (response.status === 'ok' && response.chatMessages) {
        // Successfully got chat messages
    }
});

Parameters

Name Type Description
batchSize (optional) Number Limit of messages to receive. Used if either afterMessageId or beforeMessageId are provided
afterMessageId (optional) String The messageId to return after. The N messages after message with ID of afterMessageId but before beforeMessageId
beforeMessageId (optional) String The messageId to return before. The N messages before message with ID of beforeMessageId
getMessagesCallback (required) Function Callback with the status of the request

Get Messages Callback Arguments

Name Type Description
status String The status of the operation
chatMessages [array ChatMessage] Array of chat messages matching search criteria

Get Messages Callback Status Codes

Status Description
ok Get messages succeeded
<varies>

Observable

Observe value changes. Similar to the RxJS Behavior Subject

[object Observable]

Name Signature Returns Description
subscribe (callback, options) [object Subscription] See Subscribe to an Observable
getValue () any See Get Observable Value
setValue (value) void See Set Observable Value

Subscribe to an Observable

Receive a notification every time the observable value changes.

var subscription = observable.subscribe(function(newValue) {
    // Do something with newValue
}, options);

setTimeout(function() {
    // Stop listening to notifications after 1 second
    subscription.dispose();
}, 1000)

Parameters

Name Type Description
callback (required) Function Function to call when value changes
options (optional) Object Options for subscription.

Options

Name Type Default Value Description
initial (optional) String What to do when the subscription starts. Pass in ‘notify’ to be notified of initial value

[object Subscription]

Name Signature Returns Description
dispose () void Stop listening to notifications

Get Observable Value

Value may be of any supported javascript type

observable.getValue(value);

Set Observable Value

Change the observable value. This will trigger notifications on all subscribers.

observable.setValue(value);