pcast.start(authToken,functionauthenticationCallback(pcast,status,sessionId){// Upon success, called with status="ok" and a valid "sessionId"// At any time when authentication is required with status="unauthorized"},functiononlineCallback(pcast){// Called when connected to the streaming platform},functionofflineCallback(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
varoptions={audio:true,video:true};pcast.getUserMedia(options,functionuserMediaCallback(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.
varoptions={};// Options suitable to share a high resolution stream of the user's desktopif(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}};}elseif(rtc.browser==='Chrome'){options.screen={mandatory:{maxHeight:screen.height,maxWidth:screen.width,maxFrameRate:3}};}pcast.getUserMedia(options,functionuserMediaCallback(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.
varpcast=newsdk.PCast({screenSharingExtensionId:''});// Pass your screen sharing extension Id
Publish a Stream
vartags=['my-tag'];pcast.publish(streamToken,userMediaStream,functionpublishCallback(pcast,status,publisher){// status="ok" with "publisher" object to control the stream// The "streamId" of the publishervarstreamId=publisher.getStreamId();if(publisher.hasEnded()){// Checks if the publisher has ended}publisher.setPublisherEndedCallback(functionpublisherEndedCallback(publisher,reason,reasonDescription){// Called when the stream has ended});// To stop laterpublisher.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
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 streambreak;default:// no failure has occurred, handle monitor eventbreak;}}});
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,functionsubscribeCallback(pcast,status,mediaStream){// status="ok" with "mediaStream" object to control the streammediaStream.setStreamEndedCallback(functionstreamEndedCallback(mediaStream,reason,reasonDescription){// Called when the stream has ended});// To stop latermediaStream.stop('I-am-done-watching');},subscriberOptions);
Parameters
Name
Type
Description
streamToken (required)
string
The publish token is generated using the Admin API
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 streambreak;default:// no failure has occurred, handle monitor eventbreak;}}});
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.
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(...)varrenderer=mediaStream.createRenderer();varelementToAttachTo=document.getElementById('<ELEMENT_ID>');renderer.start(elementToAttachTo);// To stop laterrenderer.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.
Cameras may be switched at runtime and devices may be rotated. Register a handler to receive a notification whenever the video dimension changes.
varrenderer=...renderer.start(...);// subscribe to dimension changed eventrenderer.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.
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.
Set up a room and manage members, streams, and chat. Some typical uses for rooms include:
Broadcast video chats between multiple people - few to many
Large-scale video chat
Conference calls with integrated video chat
Real-time web channels for hosting media content. See View a Channel with the Express API
Town hall meetings
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.
varroomService=newsdk.RoomService(pcast);
Parameters
Name
Type
Description
pcast (required)
[object PCast]
Instantiated PCast object. Must already be authenticated
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.
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.
varself=roomService.getSelf();self.getObservableScreenName.setValue('My New Screen Name');// Commit changes to self if already in a roomself.commitChanges(functioncommitChangesCallback(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.
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,functioncreateRoomCallback(error,response){if(error){// Handle error}if(response.status==='already-exists'){// No action required}if(response.status!=='ok'){// Handle error}// Successfully created roomif(response.status==='ok'&&response.room){// Do something with room}});
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,functionenterRoomCallback(error,response){if(error){// Handle error}if(response.status==='not-found'){// Handle room not found - createRoom}if(response.status!=='ok'){// Handle error}// Successfully entered roomif(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 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.
varobservableActiveRoom=roomService.getObservableActiveRoom();varactiveRoom=observableActiveRoom.getValue();varmembersObservable=activeRoom.getObservableMembers();varpcastStreamURIPrefix='pcast://phenixp2p.com/';membersObservable.subscribe(function(members){members.forEach(function(member){varmemberStreams=member.getObservableStreams().getValue();memberStreams.forEach(function(stream){// Subscribe if its a PCast streamif(stream.uri.indexOf(pcastStreamURIPrefix)===0){varstreamId=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.
varroom=roomService.getObservableActiveRoom().getValue();room.getObservableDescription.setValue('My New Room Description');// Commit changes to self if already in a roomroom.commitChanges(functioncommitChangesCallback(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(functionleaveRoomCallback(error,response){// No action required});
Setting isForceLeaveRoom to false will delay the response to the callback until the backend confirms that the client has left the room.
constdoNotForcefullyLeaveRoom=false;roomService.leaveRoom(functionleaveRoomCallback(error,response){if(error){// Handle error}if(response.status==='not-in-room'){// Do nothing}if(response.status!=='ok'){// Handle error}// Successfully left roomif(response.status==='ok'){// No action required}},doNotForcefullyLeaveRoom);
Parameters
Name
Type
Description
leaveRoomCallback (required)
Function
Callback with the status of the request
isForceLeaveRoom (optional)
Boolean
Indicates whether to skip waiting for confirmation. If isForceLeaveRoom is true then the leave request is sent and no response from backend is waited upon. By default isForceLeaveRoom is true.
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.
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)
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.
varchatService=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.
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.
varchatService=newroomService.getChatService();varchatMessageObservable=chatService.getObservableChatMessages();varbatchSize=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.
varchatService=newroomService.getChatService();chatService.start(batchSize);chatService.sendMessageToRoom('My First Message',functionsendMessageCallback(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.
Receive a notification every time the observable value changes.
varsubscription=observable.subscribe(function(newValue){// Do something with newValue},options);setTimeout(function(){// Stop listening to notifications after 1 secondsubscription.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