Welcome to Phenix PCast™ API Documentation. Here you will find documentation about:
Workflow: Workflow sections walks you through the typical steps you would take in your backend and frontend for publishing and viewing streams. Read More
Admin APIs: Admin APIs are used by your backend to enable publishing and viewing of a stream. They are RESTful HTTP APIs with JSON responses. Read More
Web and Native SDKs: SDKs help you build web and native apps for publishing and viewing streams. We provide following SDKs:
Our workflow is designed to restrict access to your streams to only the clients that you explicitly authorize. It is the responsibility of your application to authorize your clients accordingly and provide them with PCast™ access tokens generated through our Admin API.
There are two types of tokens - one for authorization and one for accessing streams. They allow your application to effectively control access to the PCast™ streaming platform.
Clients can interact with our platform in any number of ways. However, there are two essential workflows that capture the essence of how your clients and backend interact with the PCast™ streaming platform.
The admin APIs are exposed as simple REST services. You can use any REST library indigenous to your backend technology stack.
All requests are made to our secure backend at https://pcast.phenixrts.com. We strongly encourage you to use the https endpoint. Phenix Inc. may stop supporting its less secure counterpart at any time.
Creating An Authentication Token
Request
Authentication tokens are generated using a POST request as shown.
Example request for creating an authentication token
Creates a wildcard authentication token that can be used by multiple clients.
Response
The stream platform will return a successful response that contains a “status” and an “authenticationToken” field. The HTTP status code is set according to the “status” field.
HTTP/1.1 200 OK
Response Headers
Field
Value
Content-Type
application/json; charset=utf-8
Content-Length
52
Example response for authentication token requests
The session ID of the client that you are generating this token for or the wildcard * enabling any authorized session to use the token
originStreamId (optional)
The stream ID of the published stream that you want to make available for viewing (omitted when creating a publish token)
capabilities (optional)
An array of capabilities for the new stream
Supported Stream Capabilities
Value
Token Type
Description
streaming
publish
In addition to real-time streaming, create a transcoded live stream using adaptive HLS and MPEG+DASH streaming. The live stream contains 4 quality options from audio-only to highest video quality.
on-demand
publish
Persist the transcoded live stream for on-demand playback. The stream features the same capabilities as the adaptive multi-bit rate live stream and can be accessed time delayed.
low-latency
publish
Use low latency settings for the adaptive multi-bit rate live stream. This will trade bandwidth efficiency for lower latency.
archive
publish
Archive the stream to a WebM file for one time download. This is mutually exclusive with “streaming” and “on-demand”. Streams with webm archive enabled are limited to a duration of 12 hours. Please use “on-demand” for streams with unlimited duration and/or multiple access.
archive-audio-only
publish
Archive the audio of the stream to a WebM file for one time download. This is mutually exclusive with “streaming” and “on-demand”. Streams with webm archive enabled are limited to a duration of 12 hours. Please use “on-demand” for streams with unlimited duration and/or multiple access.
high-fidelity
publish
Use high fidelity audio bitrate configuration for high-quality reproduction of sound.
channel
publish
The stream will be made available in the channel identified by one of the tags channelId: or channelAlias:. The channel must be owned by the same application as the stream.
real-time
subscribe
Use real-time streaming with typically less than 300 milliseconds delivery latency. This is the default.
broadcast
subscribe
Use broadcast real-time streaming with about 1 second delivery latency. This can be used for users with bad WiFi networks with high jitter and/or interference.
streaming
subscribe
Use adaptive live streaming using HLS or MPEG+DASH with about 15-25 seconds delivery latency. This can be used for broadcasts to clients with network connections with limited bandwidth or highly fluctuating bandwidth. It requires the stream to be published with the “streaming” capability.
on-demand
subscribe
Use adaptive on-demand streaming using HLS or MPEG+DASH. This can be used to access the stream after it was recorded. It requires the stream to be published with the “on-demand” capability.
Supported Quality Capabilities
Value
Token Type
Description
uld
publish
Ultra low definition - 80kbps
vld
publish
Very low definition - 350kbps
ld
publish
Low definition - 520kbps
sd
publish
Standard definition - 830kbps - default
hd
publish
High definition - 1600kbps
fhd
publish
Full high definition - 3000kbps
xhd
publish
Extended high definition - 5500kbps
uhd
publish
Ultra high definition - 5500kbps
Response
The stream platform will return a successful response that contains a “status” and a “streamToken” field. The HTTP status code is set according to the “status” field.
Successful request, “streamToken” is valid and ready to use
400 Bad Request
<varies>
never
Indicates an issue with the request itself
401 Unauthorized
unauthorized
never
The streaming platform was not able to authorize the provided credentials
404 Not Found
not-found or origin-not-found
never
The stream specified in the “originStreamId” is not known to the platform
410 Gone
origin-ended
never
The stream specified in the “originStreamId” has ended
4XX
<varies>
never
Indicates an issue with the request itself
503 Service Unavailable
capacity
once
The system is temporarily overloaded. Please try again later
5XX
<varies>
once immediately, then exponential backoff
A transient server error
Terminating A Stream
Request
You can terminate any of your streams using a DELETE request. Typically, a stream will be terminated through the client API and this REST API may be used to censor streams.
The streaming platform was not able to authorize the provided credentials
404 Not Found
not-found
never
The specified stream is not known to the platform
409 Conflict
not-ended
after terminating the stream
Stream has not ended. On-demand streams can not be deleted until the stream has terminated. To forcefully terminate a stream, see Terminating A Stream.
410 Gone
already-deleted
never
The specified stream has already been deleted
410 Gone
resource-unavailable
never
The resources that hosted the specified stream are unavailable
4XX
<varies>
never
Indicates an issue with the request itself
503 Service Unavailable
capacity
once
The system is temporarily overloaded. Please try again later
5XX
<varies>
once immediately, then exponential backoff
A transient server error
Get Playlist Information
This API allows to get information for all the playlists of a live or on-demand stream.
Request
You can send a PUT request to the /pcast/stream/playlist endpoint as shown:
bit rate of track(s) in the playlist. This is null when the bitrate is unknown or when there are tracks with different bitrates.
height
height of the track(s) in the playlist. This is null when the height is unknown or when there are tracks with different height.
framesPerSecond
frames per second (fps) of the track(s) in the playlist. This is null when the framesPerSecond value is unknown or when there are tracks with different frames per second.
The type is “ended” indicating that the stream ended
data
The notification payload
data.streamId
The ID of the stream that started
data.reason
The reason the stream ended which may be an empty string or a custom reason
sessionId
The session ID of the client this stream belongs to
Live Available Notification
Reach devices with adaptive multi-bitrate live streaming capabilities. Currently HLS and MPEG-DASH playlists in adaptive multi-bitrate and various quality levels are supported.
This also makes the stream available inside all our SDKs using the streaming capability when subscribing.
Type “live” indicates a live playlist is available
data
The notification payload
data.streamId
The ID of the stream that started
data.uri
The URI of the playlist. File extensions: HLS -> .m3u8, MPEG-DASH -> .mpd
sessionId
The session ID of the client this stream belongs to
On-demand Available Notification
Provide adaptive multi-bitrate on-demand streaming capabilities. Currently HLS and MPEG-DASH playlists as adaptive multi-bitrate and specific quality levels are supported.
This also makes the stream available inside all our SDKs using the “on-demand” capability when subscribing.
The type is “archive” indicating that the archived stream is available for download
data
The notification payload
data.streamId
The ID of the stream that started
data.startTime
The start time of the recording as an ISO 8601 timestamp
data.uri
The URI where the stream archive can be downloaded from - The archive will be automatically deleted after 60 minutes.
sessionId
The session ID of the client this stream belongs to
Backend Setup - node.js Example
We have setup an express node.js example that you can use for setting up your own Backend-Server.
First step is to setup an express node.js backend server as shown.
Backend-Server (./../server/api.js)
varexpress=require('express');varrouter=express.Router();varrequest=require('request');varurl=require('url');varbackoff=require('backoff');varvalidCredentials={'demo-username':'demo-password'};varadminURI=url.resolve('https://pcast.phenixrts.com','/pcast/');vardata={length:256,applicationId:process.env.PHENIX_APPLICATION_ID,// We provide you with an Application Idsecret:process.env.PHENIX_SECRET,// We provide you with a Secret};router.post('/auth',function(req,res){constname=req.body.name;constpassword=req.body.password;if(validCredentials[name]!==password){console.log('\tinvalid credentials: '+Object.keys(req.body));res.sendStatus(403);}else{requestWithBackoff(adminAuth,req,res);}});router.post('/stream',function(req,res){requestWithBackoff(adminStream,req,res);});functionadminAuth(req,res){request({url:adminURI+'auth',method:'POST',json:{applicationId:data.applicationId,secret:data.secret,length:data.length,},},makeHandler(res));}functionadminStream(req,res){constbody=req.body;constjson={applicationId:data.applicationId,sessionId:body.sessionId,secret:data.secret,};if(body.originStreamId){json.originStreamId=body.originStreamId;}if(body.capabilities){json.capabilities=body.capabilities;}if(body.reason){json.reason=body.reason;}request({url:adminURI+'stream',method:'POST',json:json,},makeHandler(res));}functionrequestWithBackoff(requester,req,res){constcall=backoff.call(requester,req,res,function(err,res){console.log('Num retries: '+call.getNumRetries());if(err){res.sendStatus(err.status);}else{console.log('Status: '+res.statusCode);}});call.retryIf(function(err){returnerr.status>=500&&err.status!==503;});call.setStrategy(newbackoff.FibonacciStrategy({initialDelay:1000}));call.failAfter(3);call.start();}functionmakeHandler(res){consthandler=(function(){constresponseToSend=res;returnfunction(error,response,body){if(!error&&response.statusCode===200){console.log('\tsuccess');responseToSend.send(body);}elseif(response===undefined){console.log('\tno response from server');responseToSend.sendStatus(500);}else{console.log('\tfail:'+response.statusCode);responseToSend.sendStatus(response.statusCode);}};})();returnhandler;}module.exports=router;
Then consume the Express Router in your Express App as shown.
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');});
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
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
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
[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){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}});
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.
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 away
Offline
Member has left the room
[object Stream]
The stream object may be used to represent any value 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.getRoomChatService();
[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.getRoomChatService();varchatMessageObservable=chatService.getObservableChatMessages();varbatchSize=10;chatMessageObservable.subscribe(function(mostRecentChatMessages){// Do something with chat messages});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.getRoomChatService();chatService.start(batchSize);chatService.sendMessage('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
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 backend uri (may happen multiple times depending on the lifetime of the session).
Publishing Local Media
Publish local user media:
Camera
Microphone
Screen (on supported devices)
pcastExpress.publish(options,functioncallback(error,response){if(error){// Handle error}if(response.status!=='ok'){// Handle error}// Successfully publishedif(response.status==='ok'&&response.publisher){// Do something with publisher}});
The publish 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.
userMediaStream (optional)
Object
alternative to getUserMediaOptions - you can pass user media stream returned from getUserMedia.
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.
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.
pcastExpress.publishRemote(options,functioncallback(error,response){if(error){// Handle error}if(response.status!=='ok'){// Handle error}// Successfully publishedif(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 (required)
Array
The list of all capabilities to publish with.
streamUri (required)
String
Link to remote media (mp4, rtmp, etc.)
streamToken (optional)
String
The publish 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.
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.
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.
pcastExpress.publishScreen(options,functioncallback(error,response){if(error){// Handle error}if(response.status!=='ok'){// Handle error}// Successfully publishedif(response.status==='ok'&&response.publisher){// Do something with publisher}});
The publish 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.
userMediaStream (optional)
Object
alternative to getUserMediaOptions - you can pass user media stream returned from getUserMedia.
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.
Subscribe to streams published with the Phenix platform
pcastExpress.subscribe(options,functioncallback(error,response){if(error){// Handle error}if(response.status!=='ok'){// Handle error}// Successfully subscribedif(response.status==='ok'&&response.mediaStream){// Do something with mediaStreamif(response.renderer){// Returned if videoElement option passed in - Do something with renderer}}});
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 (required)
Array
The list of all capabilities to subscribe with.
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
Sample Monitor Options
varmonitorOptions={options:{// Optional: Additional options for monitoring a streamconditionCountForNotificationThreshold:4// Number of conditions before triggering callback - default 4},callback:functionmonitorCallback(error,response){// Optional: Handle monitor eventif(error){// Handle error}if(response.retry){response.retry();// Re-connects publisher or subscriber stream}}}
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.
pcastExpress.subscribe(options,functioncallback(error,response){if(error){// Handle error}if(response.status!=='ok'){// Handle error}// Successfully subscribedif(response.status==='ok'&&response.mediaStream){// Do something with mediaStreamif(response.renderer){// Returned if videoElement option passed in - Do something with renderer}}});
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 (required)
Array
The list of all capabilities to subscribe with.
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.
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)
pcastExpress.getUserMedia(options,functioncallback(error,response){if(error){// Handle error}if(response.status!=='ok'){// Handle error}// Successfully got user mediaif(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
Resolution to request video media with
frameRate (optional)
number
15
Frame rate to request video media with
aspectRatio (optional)
string
16x9
Aspect ratio to request vieo media with
onResolveMedia (optional)
function
Returns the options that were used to successfully get user media
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 exausted we will attempt to resolve the highest resolution requested at the next lowest aspect ratio.
Aspect Ratio
Resolution (Height)
Width
Description
16x9
2160
3840
4K (UHD)
1080
1920
1080p (FHD)
768
1366
720
1280
720p (HD)
576
1024
480
853
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.
varpcast=pcastExpress.getPCast();
Clean up
Dispose of all active connections and clean up all handlers.
varpcastExpress=pcastExpress.dispose();
Room Express
Single-step configuration based API for setting up a room or channel. The Room Express extends the Room Service to provide easy solutions to:
Url to your backend. We send a request here to authenticate and get streaming tokens.
authenticationData (required)
Object
Your authentication data for the user. On every initialization, 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 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.
View a Channel
Join a channel (room) and automatically view the most recent content published to that channel.
roomExpress.joinChannel(options,functionjoinChannelCallback(error,response){if(error){// Handle error}if(response.status==='room-not-found'){// Handle room not found - Create a Channel Or Publish to a Channel}elseif(response.status!=='ok'){// Handle error}// Successfully joined channelif(response.status==='ok'&&response.roomService){// Do something with roomService}},functionsubscriberCallback(error,response){if(error){// Handle error}if(response.status==='no-stream-playing'){// Handle no stream playing in channel - Wait for one to start}elseif(response.status!=='ok'){// Handle error}// Successfully subscribed to most recent channel presenterif(response.status==='ok'&&response.mediaStream){// Do something with mediaStream}});
roomExpress.publishToChannel(options,functioncallback(error,response){if(error){// Handle error}if(response.status!=='ok'){// Handle error}// Successfully published to channelif(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
roomExpress.createChannel(options,functioncallback(error,response){if(error){// Handle error}if(response.status==='already-exists'){// Channel already exists// Do something with roomService}elseif(response.status!=='ok'){// Handle error}// Successfully created channelif(response.status==='ok'&&response.roomService){// Do something with roomService}});
Join a room and automatically subscribe to member changes.
roomExpress.joinRoom(options,functionjoinRoomCallback(error,response){if(error){// Handle error}if(response.status==='room-not-found'){// Handle room not found - Create a Channel Or Publish to a Channel}elseif(response.status!=='ok'){// Handle error}// Successfully joined roomif(response.status==='ok'&&response.roomService){// Do something with roomService}},functionmembersChangedCallback(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.
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.
roomExpress.publishToRoom(options,functioncallback(error,response){if(error){// Handle error}if(response.status!=='ok'){// Handle error}// Successfully published to roomif(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
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.
roomExpress.publishScreenToRoom(options,functioncallback(error,response){if(error){// Handle error}if(response.status!=='ok'){// Handle error}// Successfully published to roomif(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
roomExpress.createRoom(options,functioncallback(error,response){if(error){// Handle error}if(response.status==='already-exists'){// Room already exists// Do something with roomService}elseif(response.status!=='ok'){// Handle error}// Successfully created roomif(response.status==='ok'&&response.room){// Do something with room}});
Controls if process termination signal handling is enabled or not
Connect and Authenticate
Please follow the self explanatory example for connecting and authenticating to PCast.
importandroid.util.Log;importcom.phenixp2p.pcast.PCast;importcom.phenixp2p.pcast.RequestStatus;// Obtained via Admin APIStringauthenticationToken=...;// Previously initializedPCastpcast=...;pcast.start(authenticationToken,newPCast.AuthenticationCallback(){@OverridepublicvoidonEvent(PCastpcast,RequestStatusrequestStatus,StringsessionId){if(requestStatus==RequestStatus.OK){Log.i("Phenix SDK Example","PCast started...");}else{Log.e("Phenix SDK Example","Failed to start PCast...");}}},newPCast.OnlineCallback(){@OverridepublicvoidonEvent(PCastpcast){Log.i("Phenix SDK Example","We are online...");}},newPCast.OfflineCallback(){@OverridepublicvoidonEvent(PCastpcast){Log.i("Phenix SDK Example","We are offline...");}});
Parameters
Name
Type
Description
authenticationToken (required)
string
The authentication token generated using the Admin API
authenticationCallback (required)
PCast.AuthenticationCallback
Called upon successful authentication or when authentication failed or has to be redone. Upon successful authentication, the authenticationCallback will be called with status=RequestStatus.OK. If at any time a new authenticationToken is required, then the authenticationCallback is called with status=RequestStatus.UNAUTHORIZED to indicate that we are no longer authenticated.
onlineCallback (required)
PCast.OnlineCallback
Called when the client is connected to the streaming platform
offlineCallback (required)
PCast.OfflineCallback
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
RequestStatus.OK
sessionId
Authentication succeeded, the sessionId is populated
RequestStatus.UNAUTHORIZED
<none>
Authentication failed or re-authentication required
<varies>
<none>
Authentication failed for other reasons
Disconnect
Please follow the self explanatory example for disconnecting from PCast.
importcom.phenixp2p.pcast.PCast;importcom.phenixp2p.pcast.RequestStatus;// Previously initialized and startedPCastpcast=...;RequestStatusstopStatus=pcast.stop();// Once you are done using PCast (e.g. exiting the app)pcast.shutdown();
Get Local User Media
Please follow the self explanatory example for getting local user media.
importcom.phenixp2p.pcast.FacingMode;importcom.phenixp2p.pcast.PCast;importcom.phenixp2p.pcast.UserMediaOptions;importcom.phenixp2p.pcast.UserMediaStream;importcom.phenixp2p.pcast.android.AndroidPCastFactory;// Previously initialized and startedPCastpcast=...;UserMediaOptionsgumOptions=newUserMediaOptions();// Customize options if desiredgumOptions.getVideoOptions().capabilityConstraints.put(DeviceCapability.FACING_MODE,Arrays.asList(newDeviceConstraint(FacingMode.USER)));gumOptions.getAudioOptions().enabled=false;pcast.getUserMedia(gumOptions,newPCast.UserMediaCallback(){@OverridepublicvoidonEvent(PCastpcast,RequestStatusstatus,UserMediaStreamuserMediaStream){// Check status and store 'userMediaStream'}});
Parameters
Name
Type
Description
options (required)
UserMediaOptions
The options defining the requested user media stream
userMediaCallback (required)
PCast.UserMediaCallback
Upon acquiring of the user media stream, the userMediaCallback will be called with status=RequestStatus.OK. If the user media is currently used by another application, then you may receive a code status=RequestStatus.CONFLICT . If the operation fails with status=RequestStatus.FAILED then please check the logs for more information
Hard constraint: Capability must have at least the specified value
ConstraintType.MAX
Hard constraint: Capability must have at most the specified value
ConstraintType.EXACT
Hard constraint: Capability must have exactly the specified value
ConstraintType.IDEAL
Soft constraint: Capability should have specified value, but other values are acceptable (default)
Facing Mode
Name
Description
FacingMode.AUTOMATIC
Select a facing mode automatically (default)
FacingMode.ENVIRONMENT
Facing the surrounding environment (e.g., back camera)
FacingMode.USER
Facing the user (e.g., front camera)
Flash Mode
Only applicable to video devices
Name
Description
FlashMode.AUTOMATIC
Flash is turned on automatically when needed (default)
FlashMode.ALWAYS_ON
Flash is on (if available)
FlashMode.ALWAYS_OFF
Flash is off
Device Location
Name
Description
Location.AUTOMATIC
Select any device (default)
Location.UPPER
Mounted on top of phone/tablet
Location.LOWER
Mounted at bottom of phone/tablet
Polar Pattern
Only applicable to audio devices
Name
Description
PolarPattern.AUTOMATIC
Automatically select pattern (default)
PolarPattern.OMNIDIRECTIONAL
Equally sensitive to sound from any direction
PolarPattern.CARDIOID
Most sensitive to sound from the direction in which the data source points and is (nearly) insensitive to sound from the opposite direction
PolarPattern.SUBCARDIOID
Most sensitive to sound from the direction in which the data source points and is less sensitive to sound from the opposite direction
Audio Echo Cancelation Mode
Only applicable to audio devices
Name
Description
AudioEchoCancelationMode.AUTOMATIC
Automatically select AEC (default)
AudioEchoCancelationMode.ON
Enable AEC if available
AudioEchoCancelationMode.OFF
Disabled AEC
Updating Options
Sometimes you find it useful to change the camera while a stream is running or just would like to turn on the flash light temporarily.
importcom.phenixp2p.pcast.UserMediaOptions;importcom.phenixp2p.pcast.UserMediaStream;// Previously obtained via 'getUserMedia'UserMediaStreamuserMediaStream=...;// Previously initialized and used with 'getUserMedia'UserMediaOptionsgumOptions=newUserMediaOptions();gumOptions.getVideoOptions().capabilityConstraints.put(DeviceCapability.FACING_MODE,Arrays.asList(newDeviceConstraint(FacingMode.ENVIRONMENT)));gumOptions.getVideoOptions().capabilityConstraints.put(DeviceCapability.FLASH_MODE,Arrays.asList(newDeviceConstraint(FlashMode.ALWAYS_ON)));gumOptions.getVideoOptions().capabilityConstraints.put(DeviceCapability.HEIGHT,Arrays.asList(newDeviceConstraint(720,ConstraintType.EXACT)));gumOptions.getVideoOptions().capabilityConstraints.put(DeviceCapability.WIDTH,Arrays.asList(newDeviceConstraint(800,ConstraintType.MIN),newDeviceConstraint(1500,ConstraintType.MAX)));userMediaStream.applyOptions(gumOptions);
Enumerating Source Devices
You can get a list of available source devices.
importandroid.util.Log;importcom.phenixp2p.pcast.MediaType;importcom.phenixp2p.pcast.PCast;importcom.phenixp2p.pcast.SourceDeviceInfo;// Previously initialized and startedPCastpcast=...;pcast.enumerateSourceDevices(MediaType.VIDEO,newPCast.EnumerateSourceDevicesCallback(){@OverridepublicvoidonEvent(PCastpcast,SourceDeviceInfo[]devices){// Store devices as needed}});
Parameters
Name
Type
Description
mediaType (required)
MediaType
The media type for which to enumerate source devices
SourceDeviceInfo fields
Name
Type
Description
id
String
Source device ID
name
String
Source device Name
mediaType
MediaType
Source device media type
deviceType
SourceDeviceType
Source device type
facingMode
FacingMode
Source device facing mode
Media Type
Name
Description
MediaType.VIDEO
Video
MediaType.AUDIO
Audio
Source Device Type
Name
Description
SourceDeviceType.NULL
Null device (e.g. blank screen or silence)
SourceDeviceType.PHYSICAL
Physical device (e.g. camera or microphone)
SourceDeviceType.SYSTEM_OUTPUT
System output capture (screencast)
Screencasting android 5.0 or later
You can also stream the screen of your phone.
In order to do this, you must first enumerate the available source devices to find the screencast device ID.
Find the screencast device ID
importandroid.util.Log;importcom.phenixp2p.pcast.MediaType;importcom.phenixp2p.pcast.PCast;importcom.phenixp2p.pcast.SourceDeviceInfo;importcom.phenixp2p.pcast.SourceDeviceType;// Previously initialized and startedPCastpcast=...;pcast.enumerateSourceDevices(MediaType.VIDEO,newPCast.EnumerateSourceDevicesCallback(){@OverridepublicvoidonEvent(PCastpcast,SourceDeviceInfo[]devices){for(SourceDeviceInfoinfo:devices){if(info.sourceDeviceType==SourceDeviceType.SYSTEM_OUTPUT){Log.i("Phenix SDK Example","Screencasting is available");StringscreenCaptureDeviceId=info.id;// Store screenCaptureDeviceId}}}});pcast.enumerateSourceDevices();
The screen capture device requires a valid android.media.projection.MediaProjection object to be passed to the SDK before it can be used. The MediaProjection must stay valid for the duration of the screencast.
Next, pass a valid android.media.projection.MediaProjection object
importandroid.media.projection.MediaProjection;importcom.phenixp2p.pcast.android.AndroidPCastFactory;// Previously obtained by calling// android.media.projection.MediaProjectionManager.getMediaProjection(),// see Android API reference.MediaProjectionmediaProjection=...;AndroidPCastFactory.setMediaProjection(mediaProjection);
Finally, pass the screen capture device ID
Next, pass the screen capture device ID to getUserMedia() in the user media options.
importcom.phenixp2p.pcast.FacingMode;importcom.phenixp2p.pcast.PCast;importcom.phenixp2p.pcast.UserMediaOptions;importcom.phenixp2p.pcast.UserMediaStream;// Previously initialized and startedPCastpcast=...;// Found by calling enumerateSourceDevices() as described aboveStringscreenCaptureDeviceId=...;UserMediaOptionsgumOptions=newUserMediaOptions();gumOptions.getVideoOptions().capabilityConstraints.put(DeviceCapability.DEVICE_ID,Arrays.asList(newDeviceConstraint(screenCaptureDeviceId)));pcast.getUserMedia(gumOptions,newPCast.UserMediaCallback(){@OverridepublicvoidonEvent(PCastpcast,RequestStatusstatus,UserMediaStreamuserMediaStream){// Check status and store 'userMediaStream'}});
Please follow the self explanatory code snippets for understanding above steps.
Publish a Stream
importandroid.util.Log;importcom.phenixp2p.pcast.MediaStream;importcom.phenixp2p.pcast.PCast;importcom.phenixp2p.pcast.Publisher;importcom.phenixp2p.pcast.RequestStatus;importcom.phenixp2p.pcast.StreamEndedReason;importcom.phenixp2p.pcast.UserMediaOptions;importcom.phenixp2p.pcast.UserMediaStream;// Previously initialized and startedPCastpcast=...;// Previously obtained via Admin APIStringstreamToken=...;// Previously obtained via either PCast.subscribe()// or UserMediaStream.getMediaStream()MediaStreammediaStream=...;String[]tags={"my-tag"};pcast.publish(streamToken,mediaStream,newPCast.PublishCallback(){@OverridepublicvoidonEvent(PCastpcast,RequestStatusrequestStatus,Publisherpublisher){// Check status and store 'publisher'// The "streamId" of the publisherStringstreamId=publisher.getStreamId();if(publisher.hasEnded()){// Checks if the publisher has ended}// Attach publisher ended callbackpublisher.setPublisherEndedCallback(newPublisher.PublisherEndedCallback(){@OverridepublicvoidonEvent(Publisherpublisher,StreamEndedReasonreason,StringreasonDescription){// Called when the stream has endedLog.i("Phenix SDK Example","Publish stream ended with reason ["+reasonDescription+"]");}});// 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
mediaStream (required)
MediaStream
The user media stream acquired through PCast.subscribe(…) or locally with UserMediaStream.getMediaStream()
publishCallback (required)
PCast.PublishCallback
Called upon completion of the operation
tags (optional)
String[]
Tags that will be provided with the stream notifications to your backend callback endpoint
StreamEndedReason
Reason
Description
StreamEndedReason.ENDED
The stream ended normally
StreamEndedReason.FAILED
The stream failed
StreamEndedReason.CENSORED
The stream was censored
StreamEndedReason.MAINTENANCE
A maintenance event caused this stream to be terminated
StreamEndedReason.CAPACITY
The stream was terminated due to capacity limitations
StreamEndedReason.APP_BACKGROUND
The stream was terminated due to the mobile app entering into the background
StreamEndedReason.CUSTOM
A custom termination reason is provided in the “reasonDescription” field
Subscribe to a Stream
importandroid.util.Log;importcom.phenixp2p.pcast.MediaStream;importcom.phenixp2p.pcast.PCast;importcom.phenixp2p.pcast.RequestStatus;importcom.phenixp2p.pcast.StreamEndedReason;// Previously initialized and startedPCastpcast=...;// Previously obtained via Admin APIStringstreamToken=...;pcast.subscribe(streamToken,newPCast.SubscribeCallback(){@OverridepublicvoidonEvent(PCastpcast,RequestStatusrequestStatus,MediaStreammediaStream){// Check status and store 'mediaStream'// Attach stream ended callbackmediaStream.setStreamEndedCallback(newMediaStream.StreamEndedCallback(){@OverridepublicvoidonEvent(MediaStreammediaStream,StreamEndedReasonreason,StringreasonDescription){Log.i("Phenix SDK Example","Subscriber stream ended with reason ["+reasonDescription+"]");}}});// To stop latermediaStream.stop();}});
Parameters
Name
Type
Description
streamToken (required)
String
The publish token is generated using the Admin API
subscribeCallback (required)
PCast.SubsribeCallback
Called upon completion of the operation
View a Stream
In order to view a stream you have to supply a Surface for the Renderer to draw on.
importcom.phenixp2p.pcast.MediaStream;importcom.phenixp2p.pcast.Renderer;importcom.phenixp2p.pcast.RendererStartStatus;importcom.phenixp2p.pcast.android.AndroidVideoRenderSurface;// Previously obtained via either PCast.subscribe// or PhenixUserMediaStream.mediaStreamMediaStreammediaStream=...;// Previously obtained, e.g., from a SurfaceViewSurfacerenderSurface=...;Rendererrenderer=mediaStream.createRenderer();RendererStartStatusstatus=renderer.start(newAndroidVideoRenderSurface(renderSurface));if(status==RendererStartStatus.OK){Log.i("Phenix SDK Example","Renderer started successfully");}else{Log.e("Phenix SDK Example","Renderer start failed");}// To stop laterrenderer.stop();
Preview Local User Media
importcom.phenixp2p.pcast.Renderer;importcom.phenixp2p.pcast.UserMediaStream;// Previously obtained via 'getUserMedia'UserMediaStreamuserMediaStream=...;Rendererrenderer=userMediaStream.getMediaStream().createRenderer();
Muting and Unmuting of Audio
importcom.phenixp2p.pcast.Renderer;// Previously obtained from media streamRendererrenderer=...;booleanisMuted=renderer.isAudioMuted();renderer.muteAudio();renderer.unmuteAudio();
Taking a Screenshot
If you would like to show a preview, you can take a still image from a renderer.
importcom.phenixp2p.pcast.Renderer;importcom.phenixp2p.android.AndroidLastFrameRenderedCallback;// Previously obtained from media stream and startedRendererrenderer=...;renderer.setLastVideoFrameRenderedReceivedCallback(newAndroidLastFrameRenderedCallback(){@overridepublicvoidonEvent(Rendererrenderer,BitmapvideoFrame){// Process the frame as needed}});renderer.requestLastVideoFrameRendered();
You can also take a still image from a local stream.
importcom.phenixp2p.pcast.UserMediaStream;importcom.phenixp2p.android.AndroidLastFrameCapturedCallback;// Previously obtained via 'getUserMedia'UserMediaStreamuserMediaStream=...;userMediaStream.setLastVideoFrameCapturedReceivedCallback(newAndroidLastFrameCapturedCallback(){@overridepublicvoidonEvent(Rendererrenderer,BitmapvideoFrame){// Process the frame as needed}});userMediaStream.requestLastVideoFrameCaptured();
Data Quality Feedback
If you like to show the user feedback about how their internet connectivity affects the stream quality, you can listen for data quality notifications.
importcom.phenixp2p.pcast.DataQualityReason;importcom.phenixp2p.pcast.DataQualityStatus;importcom.phenixp2p.pcast.Publisher;importcom.phenixp2p.pcast.Renderer;// Previously obtained from media stream and startedRendererrenderer=...;renderer.setDataQualityChangedCallback(newRenderer.DataQualityChangedCallback(){@OverridepublicvoidonEvent(Rendererrenderer,DataQualityStatusquality,DataQualityReasonreason){// Inform user, take action based on status and reason}});// Previously obtained via PCast.publishPublisherpublisher=...;publisher.setDataQualityChangedCallback(newPublisher.DataQualityChangedCallback(){@OverridepublicvoidonEvent(Publisherpublisher,DataQualityStatusquality,DataQualityReasonreason){// Inform user, take action based on status and reason}});
Data Quality Status for Publishers
Status
Reason
Description
DataQualityStatus.NO_DATA
DataQualityReason.NONE
The publisher has a bad internet connection and no data is being streamed.
DataQualityStatus.NO_DATA
DataQualityReason.UPLOAD_LIMITED
The publisher has a bad internet connection and no data is being streamed.
DataQualityStatus.ALL
DataQualityReason.NONE
Good internet connection and no quality reduction in effect.
DataQualityStatus.ALL
DataQualityReason.UPLOAD_LIMITED
The publisher has a slow internet connection and the quality of the stream is reduced.
DataQualityStatus.ALL
DataQualityReason.NETWORK_LIMITED
Subscribers have bad internet connections and the quality of the stream is reduced.
DataQualityStatus.AUDIO_ONLY
DataQualityReason.UPLOAD_LIMITED
The publisher has a bad internet connection and only audio is streamed.
DataQualityStatus.AUDIO_ONLY
DataQualityReason.NETWORK_LIMITED
Subscribers have bad internet connections and only audio is streamed.
Data Quality Status for Viewers
Status
Reason
Description
DataQualityStatus.NO_DATA
DataQualityReason.NONE
The subscriber has a bad internet connection and no data is being received.
DataQualityStatus.NO_DATA
DataQualityReason.DOWNLOAD_LIMITED
The subscriber has a bad internet connection and no data is being received.
DataQualityStatus.NO_DATA
DataQualityReason.PUBLISHER_LIMITED
The publisher has a bad internet connection and no data is being received.
DataQualityStatus.NO_DATA
DataQualityReason.NETWORK_LIMITED
The network is limiting the quality of the stream and no data is being received.
DataQualityStatus.ALL
DataQualityReason.NONE
Good internet connection and no quality reduction in effect.
DataQualityStatus.ALL
DataQualityReason.DOWNLOAD_LIMITED
The subscriber has a bad internet connection and the quality of the stream is reduced.
DataQualityStatus.ALL
DataQualityReason.PUBLISHER_LIMITED
The publisher has a bad internet connection and the quality of the stream is reduced.
DataQualityStatus.ALL
DataQualityReason.NETWORK_LIMITED
Other subscribers have bad internet connections and the quality of the stream is reduced.
DataQualityStatus.AUDIO_ONLY
DataQualityReason.NONE
Audio only stream, good internet connection and no quality reduction in effect.
DataQualityStatus.AUDIO_ONLY
DataQualityReason.DOWNLOAD_LIMITED
The subscriber has a bad internet connection and is only receiving audio.
DataQualityStatus.AUDIO_ONLY
DataQualityReason.PUBLISHER_LIMITED
The publisher has a bad internet connection and the subscriber is only receiving audio.
DataQualityStatus.AUDIO_ONLY
DataQualityReason.NETWORK_LIMITED
The network is limiting the quality of the stream and the subscriber is only receiving audio.
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.
importcom.phenixp2p.pcast.Dimensions;importcom.phenixp2p.pcast.Renderer;// Previously obtained from media streamRendererrenderer=...;renderer.setVideoDisplayDimensionsChangedCallback(newRenderer.VideoDisplayDimensionsChangedCallback(){@OverridepublicvoidonEvent(Rendererrenderer,DimensionsdisplayDimensions){// Can get called multiple times while rendering a stream// Values in displayDimensions.width, displayDimensions.height}});
iOS SDK
Initializing
Before using a PCast object, you need to initialize it.
Controls if process termination signal handling is enabled or not
Connect And Authenticate
#import "PCast/PhenixPCast.h"
#import "PCast/PhenixRequestStatus.h"
// Obtained via Admin API
NSString*authenticationToken=...;// Previously initialized
id<PhenixPCast>pcast=...;[pcaststart:authenticationToken:^(id<PhenixPCast>pcast,PhenixRequestStatusstatus,NSString*sessionId){if(status==PhenixRequestStatusOk){NSLog(@"PCast started...");}else{NSLog(@"Failed to start PCast...");}}:^(id<PhenixPCast>pcast){NSLog(@"We are online...");}:^(id<PhenixPCast>pcast){NSLog(@"We are offline...");}];
Parameters
Name
Type
Description
authenticationToken (required)
string
The authentication token generated using the Admin API
authenticationCallback (required)
lambda (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=PhenixRequestStatusOk. If at any time a new authenticationToken is required, then the authenticationCallback is called with status=PhenixRequestStatusUnauthorized to indicate that we are no longer authenticated.
onlineCallback (required)
lambda (pcast)
Called when the client is connected to the streaming platform
offlineCallback (required)
lambda (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
PhenixRequestStatusOk
sessionId
Authentication succeeded, the sessionId is populated
PhenixRequestStatusUnauthorized
<none>
Authentication failed or re-authentication required
<varies>
<none>
Authentication failed for other reasons
Disconnect
#import "PCast/PhenixPCast.h"
#import "PCast/PhenixRequestStatus.h"
// Previously initialized and started
id<PhenixPCast>pcast=...;PhenixRequestStatusstopStatus=[pcaststop];// Once you are done using PCast (e.g. exiting the app)
[pcastshutdown];
Get Local User Media
#import "PCast/PhenixPCast.h"
#import "PCast/PhenixPCastFactory.h"
#import "PCast/PhenixUserMediaOptions.h"
#import "PCast/PhenixUserMediaStream.h"
// Previously initialized and started
id<PhenixPCast>pcast=...;PhenixUserMediaOptions*gumOptions=[PhenixUserMediaOptionsnew]// Customize options if desired
gumOptions.video.capabilityConstraints[[NSNumbernumberWithInteger:PhenixDeviceCapabilityFacingMode]]=@[[PhenixDeviceConstraintinitWithFacingMode:PhenixFacingModeUser]];gumOptions.video.capabilityConstraints[[NSNumbernumberWithInteger:PhenixDeviceCapabilityFlashMode]]=@[[PhenixDeviceConstraintinitWithFlashMode:PhenixFlashModeAlwaysOff]];gumOptions.video.capabilityConstraints[[NSNumbernumberWithInteger:PhenixDeviceCapabilityHeight]]=@[[PhenixDeviceConstraintinitWithDouble:720:PhenixConstraintTypeExact]];gumOptions.video.capabilityConstraints[[NSNumbernumberWithInteger:PhenixDeviceCapabilityWidth]]=@[[PhenixDeviceConstraintinitWithDouble:800:PhenixConstraintTypeMin],[PhenixDeviceConstraintinitWithDouble:1500:PhenixConstraintTypeMax]];gumOptions.audio.enabled=NO;[pcastgetUserMedia:gumOptions:^(id<PhenixPCast>pcast,PhenixRequestStatusstatus,id<PhenixUserMediaStream>userMediaStream){// Check status and store 'userMediaStream'
}];
Parameters
Name
Type
Description
options (required)
PhenixUserMediaOptions
The options defining the requested user media stream
userMediaCallback (required)
lambda (pcast, status, userMediaStream)
Upon acquiring of the user media stream, the userMediaCallback will be called with status=PhenixRequestStatusOk. If the user media is currently used by another application, then you may receive a code status=PhenixRequestStatusConflict . If the operation fails with status=PhenixRequestStatusFailed then please check the logs for more information
Hard constraint: Capability must have at least the specified value
PhenixConstraintTypeMax
Hard constraint: Capability must have at most the specified value
PhenixConstraintTypeExact
Hard constraint: Capability must have exactly the specified value
PhenixConstraintTypeIdeal
Soft constraint: Capability should have specified value, but other values are acceptable (default)
Facing Mode
Name
Description
PhenixFacingModeAutomatic
Select a facing mode automatically (default)
PhenixFacingModeEnvironment
Facing the surrounding environment (e.g., back camera)
PhenixFacingModeUser
Facing the user (e.g., front camera)
Flash Mode
Only applicable to video devices
Name
Description
PhenixFlashModeAutomatic
Flash is turned on automatically when needed (default)
PhenixFlashModeAlwaysOn
Flash is on (if available)
PhenixFlashModeAlwaysOff
Flash is off
Device Location
Name
Description
PhenixLocationAutomatic
Select any device (default)
PhenixLocationUpper
Mounted on top of phone/tablet
PhenixLocationLower
Mounted at bottom of phone/tablet
Polar Pattern
Only applicable to audio devices
Name
Description
PhenixPolarPatternAutomatic
Automatically select pattern (default)
PhenixPolarPatternOmnidirectional
Equally sensitive to sound from any direction
PhenixPolarPatternCardioid
Most sensitive to sound from the direction in which the data source points and is (nearly) insensitive to sound from the opposite direction
PhenixPolarPatternSubcardioid
Most sensitive to sound from the direction in which the data source points and is less sensitive to sound from the opposite direction
Audio Echo Cancelation Mode
Only applicable to audio devices
Name
Description
PhenixAudioEchoCancelationModeAutomatic
Automatically select AEC (default)
PhenixAudioEchoCancelationModeOn
Enable AEC if available
PhenixAudioEchoCancelationModeOff
Disabled AEC
Updating Options
Sometimes you find it useful to change the camera while a stream is running or just would like to turn on the flash light temporarily.
#import "PCast/PhenixUserMediaOptions.h"
#import "PCast/PhenixUserMediaStream.h"
// Previously obtained via 'getUserMedia'
id<PhenixUserMediaStream>userMediaStream=...;// Previously initialized and used with 'getUserMedia'
PhenixUserMediaOptions*gumOptions;[gumOptions.video.capabilityConstraints[[NSNumbernumberWithInteger:PhenixDeviceCapabilityFacingMode]][0]updateFacingMode:PhenixFacingModeEnvironment];gumOptions.video.capabilityConstraints[[NSNumbernumberWithInteger:PhenixDeviceCapabilityFlashMode]][0]updateFlashMode:PhenixFlashModeAlwaysOn];[userMediaStreamapplyOptions:gumOptions];
Enumerating Source Devices
You can get a list of available source devices.
#import "PCast/PhenixPCast.h"
// Previously initialized and started
id<PhenixPCast>pcast=...;[pcastenumerateSourceDevices:^(id<PhenixPCast>pcast,NSArray<PhenixSourceDeviceInfo*>*devices){// Store devices as needed
}:PhenixMediaTypeVideo];
Parameters
Name
Type
Description
mediaType (required)
PhenixMediaType
The media type for which to enumerate source devices
PhenixSourceDeviceInfo fields
Name
Type
Description
id
NSString
Source device ID
name
NSString
Source device Name
mediaType
PhenixMediaType
Source device media type
deviceType
PhenixSourceDeviceType
Source device type
facingMode
PhenixFacingMode
Source device facing mode
Media Type
Name
Description
PhenixMediaTypeVideo
Video
PhenixMediaTypeAudio
Audio
Source Device Type
Name
Description
PhenixSourceDeviceTypeNull
Null device (e.g. blank screen or silence)
PhenixSourceDeviceTypePhysical
Physical device (e.g. camera or microphone)
PhenixSourceDeviceTypeSystemOutput
System output capture (screencast)
PhenixSourceDeviceTypeSynthetic
Synthetic source, used for testing
PhenixSourceDeviceTypeUri
Uri source, used to stream from uri
Publish a Stream
#import "PCast/PhenixMediaStream.h"
#import "PCast/PhenixPCast.h"
#import "PCast/PhenixPublisher.h"
#import "PCast/PhenixRequestStatus.h"
#import "PCast/PhenixStreamEndedReason.h"
// Previously initialized and started
id<PhenixPCast>pcast=...;// Previously obtained via Admin API
NSString*streamToken=...;// Previously obtained via either PCast.subscribe or PhenixUserMediaStream.mediaStream
id<PhenixMediaStream>mediaStream=...;NSArray*tags=@[@"my-tag"];[pcastpublish:streamToken:mediaStream:^(id<PhenixPCast>pcast,PhenixRequestStatusstatus,id<PhenixPublisher>publisher){// Check status and store 'publisher'
// The "streamId" of the publisher
NSString*streamId=publisher.streamId;if(publisher.hasEnded==YES){// Checks if the publisher has ended
}// Attach publisher ended callback
[publishersetPublisherEndedCallback:^(id<PhenixPublisher>publisher,PhenixStreamEndedReasonreason,NSString*reasonDescription){// Called when the stream has ended
NSLog(@"Publish stream ended with reason [%@]",reasonDescription);}];// To stop later
[publisherstop:@"I-am-done-publishing"];}:tags];
Parameters
Name
Type
Description
streamToken (required)
string
The publish token is generated using the Admin API
mediaStream (required)
PhenixMediaStream
The user media stream acquired through PCast.subscribe(…) or locally with PhenixUserMediaStream.mediaStream
publishCallback (required)
lambda
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
PhenixStreamEndedReason
Reason
Description
PhenixStreamEndedReasonEnded
The stream ended normally
PhenixStreamEndedReasonFailed
The stream failed
PhenixStreamEndedReasonCensored
The stream was censored
PhenixStreamEndedReasonMaintenance
A maintenance event caused this stream to be terminated
PhenixStreamEndedReasonCapacity
The stream was terminated due to capacity limitations
PhenixStreamEndedReasonAppBackground
The stream was terminated due to the mobile app entering into the background
PhenixStreamEndedReasonCustom
A custom termination reason is provided in the “reasonDescription” field
Process Raw Frames
The frame-ready API allows for pre-processing of raw audio and video frames before they are encoded and transmitted.
Any processing needs keep up with the incoming frame rate; otherwise some of the incoming frames will be dropped to compensate.
#import "PCast/PhenixUserMediaStream.h"
// Previously obtained via PhenixPCast.getUserMedia
id<PhenixUserMediaStream>userMediaStream=...;NSArray<id<PhenixMediaStreamTrack>>*videoTracks=[userMediaStreamgetVideoTracks];for(id<PhenixMediaStreamTrack>videoTrackinvideoTracks){[userMediaStreamsetFrameReadyCallback:videoTrack:^(id<PhenixFrameNotification>frameNotification){[frameNotificationread:^(CMSampleBufferRefframe){constCVPixelBufferRefpixelBuffer=CMSampleBufferGetImageBuffer(frame);constsize_tdisplayHeightInPixels=CVPixelBufferGetHeight(pixelBuffer);constsize_tdisplayWidthInPixels=CVPixelBufferGetWidth(pixelBuffer);// Manipulate sample buffer as needed
...// Write back sample buffer
[frameNotificationwrite:frame];}];}];}NSArray<id<PhenixMediaStreamTrack>>*audioTracks=[userMediaStreamgetAudioTracks];for(id<PhenixMediaStreamTrack>audioTrackinaudioTracks){[userMediaStreamsetFrameReadyCallback:audioTrack:^(id<PhenixFrameNotification>frameNotification){[frameNotificationread:^(CMSampleBufferRefframe){constCMBlockBufferRefblockBuffer=CMSampleBufferGetDataBuffer(frame);constCMFormatDescriptionRefformatDescription=CMSampleBufferGetFormatDescription(frame);constAudioStreamBasicDescription*constaudioStreamBasicDescription=CMAudioFormatDescriptionGetStreamBasicDescription(formatDescription);constsize_tbufferSize=CMBlockBufferGetDataLength(blockBuffer);char*rawAudioData;size_tlengthAtOffset;size_ttotalLength;if(CMBlockBufferGetDataPointer(blockBuffer,0,&lengthAtOffset,&totalLength,&rawAudioData)!=noErr||lengthAtOffset!=bufferSize){return;}// Attenuate audio:
if((audioStreamBasicDescription->mFormatFlags&kAudioFormatFlagIsSignedInteger)&&(audioStreamBasicDescription->mBitsPerChannel==16)){int16_t*s16AudioData=(int16_t*)rawAudioData;for(size_tsampleIndex=0;sampleIndex<bufferSize/sizeof(int16_t);++sampleIndex){s16AudioData[sampleIndex]=0.1*s16AudioData[sampleIndex];}}// Write back sample buffer
[frameNotificationwrite:frame];}];}];}
Frame Notification API
Name
Argument
Description
read
ReadFrameCallback
Retrieves current raw frame in form of a CMSampleBufferRef
write
CMSampleBufferRef
Writes back a processed or newly generated frame. The frame can have a different resolution and timestamps (the buffer attributes are expected to be set correctly)
drop
(none)
Instructs stream to drop the current frame
Subscribe to a Stream
#import "PCast/PhenixMediaStream.h"
#import "PCast/PhenixPCast.h"
#import "PCast/PhenixRequestStatus.h"
#import "PCast/PhenixStreamEndedReason.h"
// Previously initialized and started
id<PhenixPCast>pcast=...;// Previously obtained via Admin API
NSString*streamToken=...;[pcastsubscribe:streamToken:^(id<PhenixPCast>pcast,PhenixRequestStatusstatus,id<PhenixMediaStream>mediaStream){// Check status and store 'mediaStream'
// Attach stream ended callback
[mediaStreamsetStreamEndedCallback:^(id<PhenixMediaStream>mediaStream,PhenixStreamEndedReasonreason,NSString*reasonDescription){NSLog(@"Subscriber stream ended with reason [%@]",reasonDescription);}];// To stop later
[mediaStreamstop];}];
Parameters
Name
Type
Description
streamToken (required)
string
The publish token is generated using the Admin API
subscribeCallback (required)
lambda
Called upon completion of the operation
View a Stream
In order to view a stream you have to attach it to a render surface.
#import "PCast/PhenixMediaStream.h"
#import "PCast/PhenixRenderer.h"
#import "PCast/PhenixRendererStartStatus.h"
// Previously obtained via either PCast.subscribe or PhenixUserMediaStream.mediaStream
id<PhenixMediaStream>mediaStream=...;id<PhenixRenderer>renderer=[mediaStreamcreateRenderer];[renderersetRenderSurfaceReadyCallback:^(id<PhenixRenderer>renderer,CALayer*renderSurface){// Attach layer to UI and set fill options and/or resize as needed
// NOTE: This may be called more than once (e.g. after interruptions)
}];PhenixRendererStartStatusstatus=[rendererstart];// To stop later
[rendererstop];
Preview Local User Media
#import "PCast/PhenixRenderer.h"
#import "PCast/PhenixUserMediaStream.h"
// Previously obtained via 'getUserMedia'
id<PhenixUserMediaStream>userMediaStream=...;id<PhenixRenderer>renderer=[userMediaStream.mediaStreamcreateRenderer];
Muting and Unmuting of Audio
#import "PCast/PhenixRenderer.h"
// Previously obtained from media stream
id<PhenixRenderer>renderer=...;BOOLisMuted=renderer.audioMuted;[renderermuteAudio];[rendererunmuteAudio];
Taking a Screenshot
If you like to show a preview, you can take a still image from a renderer.
#import "PCast/PhenixRenderer.h"
// Previously obtained from media stream and started
id<PhenixRenderer>renderer=...;[renderersetLastVideoFrameRenderedReceivedCallback:^(id<PhenixRenderer>pcast,CVPixelBufferRefnativeVideoFrame){// NOTE: If frame is dispatched to another thread, ensure its reference
// is kept alive by using CVPixelBufferRetain/CVPixelBufferRelease
}];[rendererrequestLastVideoFrameRendered];
Data Quality Feedback
If you like to show the user feedback about how their internet connectivity affects the stream quality, you can listen for data quality notifications.
#import "PCast/PhenixDataQualityReason.h"
#import "PCast/PhenixDataQualityStatus.h"
#import "PCast/PhenixPublisher.h"
#import "PCast/PhenixRenderer.h"
// Previously obtained from media stream and started
id<PhenixRenderer>renderer=...;[renderersetDataQualityChangedCallback:^(id<PhenixRenderer>renderer,PhenixDataQualityStatusstatus,PhenixDataQualityReasonreason){// Inform user, take action based on status and reason
}];// Previously obtained via PCast.publish
id<PhenixPublisher>publisher=...;[publishersetDataQualityChangedCallback:^(id<PhenixPublisher>publisher,PhenixDataQualityStatusstatus,PhenixDataQualityReasonreason){// Inform user, take action based on status and reason
}];
Data Quality Status For Publishers
Status
Reason
Description
PhenixDataQualityStatusNoData
PhenixDataQualityReasonNone
The publisher has a bad internet connection and no data is being streamed.
PhenixDataQualityStatusNoData
PhenixDataQualityReasonUploadLimited
The publisher has a bad internet connection and no data is being streamed.
PhenixDataQualityStatusAll
PhenixDataQualityReasonNone
Good internet connection and no quality reduction in effect.
PhenixDataQualityStatusAll
PhenixDataQualityReasonUploadLimited
The publisher has a slow internet connection and the quality of the stream is reduced.
PhenixDataQualityStatusAll
PhenixDataQualityReasonNetworkLimited
Subscribers have bad internet connections and the quality of the stream is reduced.
PhenixDataQualityStatusAudioOnly
PhenixDataQualityReasonUploadLimited
The publisher has a bad internet connection and only audio is streamed.
PhenixDataQualityStatusAudioOnly
PhenixDataQualityReasonNetworkLimited
Subscribers have bad internet connections and only audio is streamed.
Data Quality Status For Viewers
Status
Reason
Description
PhenixDataQualityStatusNoData
PhenixDataQualityReasonNone
The subscriber has a bad internet connection and no data is being received.
PhenixDataQualityStatusNoData
PhenixDataQualityReasonDownloadLimited
The subscriber has a bad internet connection and no data is being received.
PhenixDataQualityStatusNoData
PhenixDataQualityReasonPublisherLimited
The publisher has a bad internet connection and no data is being received.
PhenixDataQualityStatusNoData
PhenixDataQualityReasonNetworkLimited
The network is limiting the quality of the stream and no data is being received.
PhenixDataQualityStatusAll
PhenixDataQualityReasonNone
Good internet connection and no quality reduction in effect.
PhenixDataQualityStatusAll
PhenixDataQualityReasonDownloadLimited
The subscriber has a bad internet connection and the quality of the stream is reduced.
PhenixDataQualityStatusAll
PhenixDataQualityReasonPublisherLimited
The publisher has a bad internet connection and the quality of the stream is reduced.
PhenixDataQualityStatusAll
PhenixDataQualityReasonNetworkLimited
Other subscribers have bad internet connections and the quality of the stream is reduced.
PhenixDataQualityStatusAudioOnly
PhenixDataQualityReasonNone
Audio only stream, good internet connection and no quality reduction in effect.
PhenixDataQualityStatusAudioOnly
PhenixDataQualityReasonDownloadLimited
The subscriber has a bad internet connection and is only receiving audio.
PhenixDataQualityStatusAudioOnly
PhenixDataQualityReasonPublisherLimited
The publisher has a bad internet connection and the subscriber is only receiving audio.
PhenixDataQualityStatusAudioOnly
PhenixDataQualityReasonNetworkLimited
The network is limiting the quality of the stream and the subscriber is only receiving audio.
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.
#import "PCast/PhenixDimensions.h"
#import "PCast/PhenixRenderer.h"
// Previously obtained from media stream
id<PhenixRenderer>renderer=...;[renderersetVideoDisplayDimensionsChangedCallback:^(id<PhenixRenderer>renderer,conststructPhenixDimensions*displayDimensions){// displayDimensions->width, displayDimensions->height
// Can get called multiple times while rendering a stream
}];