NAV Navbar
Logo
http curl

Introduction

Welcome to Phenix PCast™ API Documentation. Here you will find documentation about:

  1. Workflow: Workflow sections walks you through the typical steps you would take in your backend and frontend for publishing and viewing streams. Read More
  2. 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
  3. Web and Native SDKs: SDKs help you build web and native apps for publishing and viewing streams. We provide following SDKs:

Workflow

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.

  1. Publishing a stream

  2. Viewing a stream

Here is an interactive demonstration of these workflows - PCast™ Workflow. An application ID and secret is required for using this demo.

Publishing a stream

Publishing

To make a stream available for other users to watch, a client follows the Publish Workflow:

  1. Acquire an authentication token using the Admin API POST /pcast/auth

  2. Pass the authentication token from backend to client

  3. Connect to the streaming platform and authenticate PCast::Start(authenticationToken, ...)

  4. Get the local user media (e.g. camera and microphone) PCast::GetUserMedia(options, ...)

  5. Pass the client’s session ID provided by PCast::Start(...) to your backend

  6. Acquire a publish token using the Admin API POST /pcast/stream

  7. Pass the publish token from backend to client

  8. Publish the user media stream PCast::Publish(streamToken, userMediaStream, ...)

Viewing a stream

Viewing

To consume an existing stream, a client follows the View Workflow:

  1. Acquire an authentication token using the Admin API POST /pcast/auth

  2. Pass the authentication token from backend to client

  3. Connect to the streaming platform and authenticate PCast::Start(authenticationToken, ...)

  4. Pass the client’s session ID provided by PCast::Start(...) to your backend

  5. Acquire a view token using the Admin API POST /pcast/stream

  6. Pass the view token from backend to client

  7. Client subscribes to the stream PCast::Subscribe(streamToken, ...)

  8. Render stream MediaStream::CreateRenderer()::Start(display)

Admin API

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

POST /pcast/auth HTTP/1.1
Host: pcast.phenixrts.com
Accept: application/json
Content-Type: application/json
Content-Length: 59

{
    "applicationId": "<applicationId>",
    "secret": "<secret>"
}
$ curl https://pcast.phenixrts.com/pcast/auth \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Content-Length: 59" \
-X POST \
-d '{
        "applicationId": "<applicationId>",
        "secret": "<secret>"
        "capabilities": ["<capability>"]
    }'

Request Headers:

Field Value
Accept application/json
Content-Type application/json
Content-Length 59

Request Payload:

Field Description
applicationId Your application ID
secret Your application secret
capabilities (optional) An array of capabilities for the token

Supported Authentication Capabilities

Value Description
wildcard 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

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 52

{"status":"ok","authenticationToken":"us-east#VaTd"}
{
    "status":"ok",
    "authenticationToken":"us-east#VaTd"
}

Response Fields

Field Description
status The status of the request
authenticationToken The authentication token to use by your client

Status Codes

HTTP Status Retry Description
200 OK ok never Successful request, “authenticationToken” is valid and ready to use
400 Bad Request <not provided> never Indicates an issue with the request itself
401 Unauthorized unauthorized never The streaming platform was not able to authorize the provided credentials
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

Creating A Stream Token

Request

Stream tokens are generated sending a POST request as shown.

If you provide an “originStreamId”, a view token is generated. Otherwise, a publish token is generated.

Example request for creating a stream token

POST /pcast/stream HTTP/1.1
Host: pcast.phenixrts.com
Accept: application/json
Content-Type: application/json
Content-Length: 138

{
    "applicationId": "<applicationId>",
    "secret": "<secret>",
    "sessionId": "<sessionId>",
    "originStreamId": "<originStreamId>",
    "capabilities": [
        "<capability>"
    ]
}
$ curl https://pcast.phenixrts.com/pcast/stream \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Content-Length: 138" \
-X POST \
-d '{
        "applicationId": "<applicationId>",
        "secret": "<secret>",
        "sessionId": "<sessionId>",
        "originStreamId": "<originStreamId>",
        "capabilities": ["<capability>"]
    }'

Request Headers:

Field Value
Accept application/json
Content-Type application/json
Content-Length 138

Request fields

Field Description
applicationId (required) Your application ID
secret (required) Your application secret
sessionId (required) 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.

Response Headers

Field Value
Content-Type application/json; charset=utf-8
Content-Length 44

Example response for stream token requests

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 44

{"status":"ok","streamToken":"us-east#C1Nl"}
{
    "status":"ok",
    "streamToken":"us-east#C1Nl"
}

Response Fields

Field Description
status The status of the request
streamToken The stream token to use by your client

Status Codes

HTTP Status Retry Description
200 OK ok never 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.

Terminating a stream by streamId

DELETE /pcast/stream HTTP/1.1
Host: pcast.phenixrts.com
Accept: application/json
Content-Type: application/json
Content-Length: 94

{
    "applicationId": "<applicationId>",
    "secret": "<secret>",
    "streamId": "<streamId>",
    "reason": "<reason>"
}
$ curl https://pcast.phenixrts.com/pcast/stream \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Content-Length: 138" \
-X DELETE \
-d '{
        "applicationId": "<applicationId>",
        "secret": "<secret>",
        "streamId": "<streamId>",
        "reason": "<reason>",
    }'

Terminating a stream by streamToken

DELETE /pcast/stream HTTP/1.1
Host: pcast.phenixrts.com
Accept: application/json
Content-Type: application/json
Content-Length: 94

{
    "applicationId": "<applicationId>",
    "secret": "<secret>",
    "streamToken": "<streamToken>",
    "reason": "<reason>"
}
$ curl https://pcast.phenixrts.com/pcast/stream \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Content-Length: 94" \
-X DELETE \
-d '{
        "applicationId": "<applicationId>",
        "secret": "<secret>",
        "streamToken": "<streamToken>",
        "reason": "<reason>",
    }'

Request fields for terminating a stream

Field Description
applicationId (required) Your application ID
secret (required) Your application secret
streamId (required) The stream ID of the stream that you want to terminate
reason (required) The reason of the termination

Reasons String

Value Description
<empty> The stream ended normally
ended The stream ended normally
censored The stream was censored
<custom> A custom reason will be passed to your client

Response

The stream platform will return a successful response that contains a “status” field. The HTTP status code is set according to the “status” field.

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 15

{"status":"ok"}
{
    "status":"ok"
}

Status Codes for terminating a stream

HTTP Status Retry Description
200 OK ok never Stream was successfully terminated
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 never The specified stream is not known to the platform
410 Gone already-ended never The specified stream has already ended
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

Deleting On-Demand Stream

This API lets you delete an on-demand stream.

Request

You can delete an on-demand stream by using a DELETE request.

Deleting an on-demand stream by streamId

DELETE /pcast/stream/archive HTTP/1.1
Host: pcast.phenixrts.com
Accept: application/json
Content-Type: application/json
Content-Length: 94

{
    "applicationId": "<applicationId>",
    "secret": "<secret>",
    "streamId": "<streamId>",
    "reason": "<reason>"
}
$ curl https://pcast.phenixrts.com/pcast/stream/archive \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Content-Length: 138" \
-X DELETE \
-d '{
        "applicationId": "<applicationId>",
        "secret": "<secret>",
        "streamId": "<streamId>",
        "reason": "<reason>",
    }'

Deleting an on-demand stream by streamToken

DELETE /pcast/stream/archive HTTP/1.1
Host: pcast.phenixrts.com
Accept: application/json
Content-Type: application/json
Content-Length: 94

{
    "applicationId": "<applicationId>",
    "secret": "<secret>",
    "streamToken": "<streamToken>",
    "reason": "<reason>"
}
$ curl https://pcast.phenixrts.com/pcast/stream/archive \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Content-Length: 94" \
-X DELETE \
-d '{
        "applicationId": "<applicationId>",
        "secret": "<secret>",
        "streamToken": "<streamToken>",
        "reason": "<reason>",
    }'

Request fields

Field Description
applicationId (required) Your application ID
secret (required) Your application secret
streamId (required) The stream ID of the on-demand stream that you want to delete
reason (required) A reason for why the stream is deleted for your records.

Response

The stream platform will return a successful response that contains a “status” field. The HTTP status code is set according to the “status” field.

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 15

{"status":"ok"}
{
    "status":"ok"
}

Status Codes

HTTP Status Retry Description
200 OK ok never Stream was successfully terminated
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 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:

PUT /pcast/stream/playlist HTTP/1.1
Host: pcast.phenixrts.com
Accept: application/json
Content-Type: application/json
Content-Length: 50

{
    "applicationId": "<applicationId>",
    "secret": "<secret>",
    "streamId": "<streamId>"
}
$ curl https://pcast.phenixrts.com/pcast/stream/playlist \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Content-Length: 50" \
-X PUT \
-d '{
        "applicationId": "<applicationId>",
        "secret": "<secret>",
        "streamId": "<streamId>"
    }'

Request fields

Field Description
applicationId (required) Your application ID
secret (required) Your application secret
streamId (required) The stream ID of the stream whose playlist URIs are requested

Response

The stream platform will return a successful response that contains a “status” field. The HTTP status code is set according to the “status” field.

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 1500

{"status":"ok","playlists":[{"name":"live-720.mpd","type":"Dash","uri":"https://pcast.phenixrts.com/video/application-id/us-central#us-central1-c.YfMSNkZM.20171121.9VuaQSac/live-720.mpd","isVariant":false,"isProtected":false,"info":{"bitrate":null,"height":720,"framesPerSecond":null}},{"name":"live.mpd","type":"Dash","uri":"https://pcast.phenixrts.com/video/application-id/us-central#us-central1-c.YfMSNkZM.20171121.9VuaQSac/live.mpd","isVariant":true,"isProtected":false,"info":{"bitrate":null,"height":null,"framesPerSecond":null}},...],"streamInfo":{"startTime":"2017-11-21T20:53:43.529000000Z","endTime":"2017-11-21T20:53:40.955000000Z"}}
{
   "status" : "ok",
   "playlists" : [
      {
         "name" : "live-720.mpd",
         "type" : "Dash",
         "uri" : "https://pcast.phenixrts.com/video/application-id/us-central#us-central1-c.YfMSNkZM.20171121.9VuaQSac/live-720.mpd",
         "isVariant" : false,
         "isProtected" : false,
         "info" : {
            "bitrate" : null,
            "height" : 720,
            "framesPerSecond" : null
         }
      },
      {
         "name" : "live.mpd",
         "type" : "Dash",
         "uri" : "https://pcast.phenixrts.com/video/application-id/us-central#us-central1-c.YfMSNkZM.20171121.9VuaQSac/live.mpd",
         "isProtected" : false,
         "isVariant" : true
         "info" : {
            "bitrate" : null
            "height" : null,
            "framesPerSecond" : null,
         }
      },
      ...
   ],
   "streamInfo" : {
      "startTime" : "2017-11-21T20:53:43.529000000Z",
      "endTime" : "2017-11-21T20:53:40.955000000Z"
   }
}

Playlist API Status Codes

HTTP Status Retry Description
200 OK ok never Playlists were successfully retrieved
400 Bad Request <varies> never Indicates an issue with the request
401 Unauthorized unauthorized never The streaming platform was not able to authorize the provided credentials
4XX <varies> never Indicates an issue with the request
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

Playlist API Response fields

Field Description
status See Status Codes
playlists Array of playlists. See Playlist fields.
streamInfo Metadata about the stream. See Stream Metadata fields.

Playlist fields

Field Description
name Name of the playlist
type type of playlist - HLS or DASH
uri URI of the playlist
isVariant Whether this is a variant playlist
isProtected Whether this playlist if DRM protected
info Metadata about the playlist. See Playlist metadata.

Playlist metadata

Field Description
bitrate 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.

Stream Metadata fields

Field Description
startTime RFC 3339 compliant start time of the stream
endTime RFC 3339 compliant end time of the stream. This is null if the stream has not ended.

Notifications

The PCast™ streaming platform can notify your backend when streams start and stop, or when archived content becomes available for download.

Request

You can set the callback endpoint for your application using a PUT request.

PUT /pcast/app/callback HTTP/1.1
Host: pcast.phenixrts.com
Accept: application/json
Content-Type: application/json
Content-Length: 162

{
    "applicationId": "<applicationId>",
    "secret": "<secret>",
    "callback": {
        "protocol": "<protocol>",
        "host": "<host>",
        "port": <port>,
        "method": "<method>",
        "path": "<path>"
    }
}
$ curl https://pcast.phenixrts.com/pcast/app/callback \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Content-Length: 162" \
-X PUT \
-d '{
        "applicationId": "<applicationId>",
        "secret": "<secret>",
        "callback": {
            "protocol": "<protocol>",
            "host": "<host>",
            "port": <port>,
            "method": "<method>",
            "path": "<path>"
        }
    }'

Request fields

Field Default Value Description
applicationId (required) Your application ID
secret (required) Your application secret
callback (required) The object defining the callback endpoint
callback.protocol (optional) “http” The protocol to use for notifications: “http” or “https”
callback.host (required) The host to use for notifications
callback.port (optional) 80 A numerical (not a string) value defining the port to use for notifications
callback.method (optional) “POST” The HTTP method to use for notifications: “GET”, “POST” or “PUT”
callback.path (optional) “/” The path to use for notifications

Response

The stream platform will return a successful response that contains a “status” field. The HTTP status code is set according to the status field.

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 15

{"status":"ok"}
{
    "status":"ok"
}

Status Codes

HTTP Status Retry Description
200 OK ok never Stream was successfully terminated
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
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

Notification Types

The streaming platform notifies the callback endpoint when certain platform events occur.

Event Name Description
Stream Started Triggers when a new stream is published
Stream Ended Triggers when a published stream ends
Live Available Triggers when a live playlist of a published stream is ready
On-Demand Available Triggers when a on-demand playlist of a published stream is ready
Archive Available Triggers when the archive of a published stream is ready for download

We will be using the callback.method of POST in the examples for each notification type below. However “GET”, “POST” or “PUT” are fully supported.

Stream Started Notification

POST <callback.path> HTTP/1.1
Host: <callback.host>:<callback.port>
Content-Type: application/json
Content-Length: 223

{
    "apiVersion": 0,
    "entity", "stream",
    "what", "started",
    "data": {
        "streamId": "<streamId>",
        "tags": [
            <tag>
        ]
    },
    "sessionId": "<sessionId>"
}
$ curl <callback.url> \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Content-Length: 223" \
-X POST \
-d '{
        "apiVersion": 0,
        "entity", "stream",
        "what", "started",
        "data": {
            "streamId": "<streamId>",
            "tags": [
                <tag>
            ]
        },
        "sessionId": "<sessionId>"
    }'

Request fields

Field Description
apiVersion The API version the message conforms to
entity Belongs to the “stream” entity
what The type is “started” indicating that the stream started
data The notification payload
data.streamId The ID of the stream that started
data.tags Array of string tags provided when calling the PCast::Publish(…, tags) API
sessionId The session ID of the client this stream belongs to

Stream Ended Notification

POST <callback.path> HTTP/1.1
Host: <callback.host>:<callback.port>
Content-Type: application/json
Content-Length: 223

{
    "apiVersion": 0,
    "entity", "stream",
    "what", "ended",
    "data": {
        "streamId": "<streamId>",
        "reason": "<reason>"
    },
    "sessionId": "<sessionId>"
}
$ curl <callback.url> \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Content-Length: 223" \
-X POST \
-d '{
        "apiVersion": 0,
        "entity", "stream",
        "what", "ended",
        "data": {
            "streamId": "<streamId>",
            "reason": "<reason>"
        },
        "sessionId": "<sessionId>"
    }'

Request fields

Field Description
apiVersion The API version the message conforms to
entity Belongs to the “stream” entity
what 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.

POST <callback.path> HTTP/1.1
Host: <callback.host>:<callback.port>
Content-Type: application/json
Content-Length: 223

{
    "apiVersion": 0,
    "entity", "stream",
    "what", "live",
    "data": {
        "streamId": "<streamId>",
        "uri": "<uri>"
    },
    "sessionId": "<sessionId>"
}
$ curl <callback.url> \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Content-Length: 223" \
-X POST \
-d '{
        "apiVersion": 0,
        "entity", "stream",
        "what", "live",
        "data": {
            "streamId": "<streamId>",
            "uri": "<uri>"
        },
        "sessionId": "<sessionId>"
    }'

Request fields

Field Description
apiVersion The API version the message conforms to
entity Belongs to the “stream” entity
what 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.

POST <callback.path> HTTP/1.1
Host: <callback.host>:<callback.port>
Content-Type: application/json
Content-Length: 223

{
    "apiVersion": 0,
    "entity", "stream",
    "what", "on-demand",
    "data": {
        "streamId": "<streamId>",
        "uri": "<uri>"
    },
    "sessionId": "<sessionId>"
}
$ curl <callback.url> \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Content-Length: 223" \
-X POST \
-d '{
        "apiVersion": 0,
        "entity", "stream",
        "what", "on-demand",
        "data": {
            "streamId": "<streamId>",
            "uri": "<uri>"
        },
        "sessionId": "<sessionId>"
    }'

Request fields

Field Description
apiVersion The API version the message conforms to
entity Belongs to the “stream” entity
what Type “on-demand” indicates a on-demand 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

Archive Available Notification BETA

Retain a recording of your streams in WebM (VP8/Vorbis) format.

POST <callback.path> HTTP/1.1
Host: <callback.host>:<callback.port>
Content-Type: application/json
Content-Length: 223

{
    "apiVersion": 0,
    "entity", "stream",
    "what", "archive",
    "data": {
        "streamId": "<streamId>",
        "startTime": "<startTime>",
        "uri": "<uri>"
    },
    "sessionId": "<sessionId>"
}
$ curl <callback.url> \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Content-Length: 223" \
-X POST \
-d '{
        "apiVersion": 0,
        "entity", "stream",
        "what", "archive",
        "data": {
            "streamId": "<streamId>",
            "startTime": "<startTime>",
            "uri": "<uri>"
        },
        "sessionId": "<sessionId>"
    }'

Request fields

Field Description
apiVersion The API version the message conforms to
entity Belongs to the “stream” entity
what 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)

var express = require('express');
var router = express.Router();
var request = require('request');
var url = require('url');
var backoff = require('backoff');
var validCredentials = {'demo-username': 'demo-password'};
var adminURI = url.resolve('https://pcast.phenixrts.com', '/pcast/');
var data = {
  length: 256,
  applicationId: process.env.PHENIX_APPLICATION_ID, // We provide you with an Application Id
  secret: process.env.PHENIX_SECRET,                // We provide you with a Secret
};

router.post('/auth', function(req, res) {
  const name = req.body.name;
  const password = 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);
});

function adminAuth(req, res) {
  request({
    url: adminURI + 'auth',
    method: 'POST',
    json: {
      applicationId: data.applicationId,
      secret: data.secret,
      length: data.length,
    },
  }, makeHandler(res));
}

function adminStream(req, res) {
  const body = req.body;
  const json = {
    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));
}

function requestWithBackoff(requester, req, res) {
  const call = 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) {
    return err.status >= 500 && err.status !== 503;
  });
  call.setStrategy(new backoff.FibonacciStrategy({initialDelay: 1000}));
  call.failAfter(3);
  call.start();
}

function makeHandler(res) {
  const handler = (function() {
    const responseToSend = res;
    return function(error, response, body) {
      if (!error && response.statusCode === 200) {
        console.log('\tsuccess');
        responseToSend.send(body);
      } else if (response === undefined) {
        console.log('\tno response from server');
        responseToSend.sendStatus(500);
      } else {
        console.log('\tfail:' + response.statusCode);
        responseToSend.sendStatus(response.statusCode);
      }
    };
  })();
  return handler;
}

module.exports = router;

Then consume the Express Router in your Express App as shown.

consume the Express Router

var express = require('express');
var api = require('./../server/api.js');
var app = express();

app.use('/pcast', api);

Finally in the browser use the backendUri of your backend server as a proxy to the PCast Platform.

Web SDK

The Web SDK is available on GitHub and can be installed as a pre-built universal module using several dependency management tools.

Bower

bower install -S phenix-web-sdk

NPM

npm install -S phenix-web-sdk

Bundles

The universal module is available uncompressed and minified and also in bundled versions.

phenix-web-sdk.js

phenix-web-sdk.min.js

phenix-web-sdk-bundled.js

phenix-web-sdk-bundled.min.js

Initializing

Basic initialization

requirejs(['phenix-web-sdk'], function (sdk) {
    var pcast = new sdk.PCast();
});

Initializing With Live Streaming Support

If you would like to support playback of live streams then you can inject Google’s Shaka Player when creating the PCast instance.

Initialization With Live Streaming Support

requirejs(['phenix-web-sdk', 'shaka'], function (sdk, shaka) {
    var pcast = new sdk.PCast({shaka: shaka});
});

Initializing With Ember.js

If you are using ember.js for your frontend, then you can add the Web SDK by generating a vendor shim:

ember generate vendor-shim phenix-web-sdk

Then modify ember-cli-build.js as shown:

Add the following imports in your ember-cli-build.js:

app.import({
  development: 'bower_components/phenix-web-sdk/dist/phenix-web-sdk-bundled.js',
  production: 'bower_components/phenix-web-sdk/dist/phenix-web-sdk-bundled.min.js'
});
app.import('vendor/shims/phenix-web-sdk.js');

After that you can use the Web SDK in your code:

import sdk from 'phenix-web-sdk';
let pcast = new sdk.PCast();

Connect and Authenticate

Connect and Authenticate example

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

Parameters

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

Authentication Callback Status Codes

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

Disconnecting

Disconnect example:

pcast.stop()

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

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

Getting Local User Media

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

Acquire the local user media stream

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

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

Parameters

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

[object Options]

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

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

User Media Callback Status Codes

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

Screen Sharing

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

var options = {};

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

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

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

Use Your Own Extension

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

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

Publish a Stream

var tags = [ 'my-tag' ];

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

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

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

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

Parameters

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

Publish Callback Arguments

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

Publish Callback Status Codes

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

[object Publisher]

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

Publisher Ended Callback Arguments

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

Stream Ended Reason

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

Monitor A Publisher

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

Parameters

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

[object Options]

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

Publish Callback Arguments

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

Publish Callback Reasons

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

Subscribe to a Stream

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

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

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

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

[object MediaStream]

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

Stream Ended Callback Arguments

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

Stream Ended Reason

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

Monitor A Media Stream

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

Parameters

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

[object Options]

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

Monitor Media Stream Callback Arguments

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

Monitor Media Stream Callback Reasons

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

Selecting A Subset Of Media Tracks

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

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

Parameters

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

Track Select Callback Arguments

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

View a Stream

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

renderer.start(elementToAttachTo);

// To stop later
renderer.stop();

Parameters

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

[object Renderer]

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

[object RendererStats]

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

Handling Dimension Changes

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

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

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

Parameters

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

[object Options]

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

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

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

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

var stats = renderer.getStats();

console.log(stats.lag);

Room Service

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

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

Initializing

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

var roomService = new sdk.RoomService(pcast);

Parameters

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

[object RoomService]

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

Instantiate Self Member Model

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

roomService.start(role, screenName);

Parameters

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

Update Self Model

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

var self = roomService.getSelf();

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

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

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

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

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

Update Self Callback Arguments

Name Type Description
status String The status of the operation

Update Self Callback Status Codes

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

Set Self Streams

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

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

self.setStreams([selfStream]);

Parameters

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

Get Room Info

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

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

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

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

Parameters

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

Get Room Info Callback Arguments

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

Get Room Info Callback Status Codes

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

Create a Room

Create a room with the provided details

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

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

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

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

Parameters

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

Room Options

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

Create Room Callback Arguments

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

Create Room Callback Status Codes

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

Join a Room

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

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

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

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

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

Parameters

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

Join Room Callback Arguments

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

Join Room Callback Status Codes

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

Subscribe to Room Member Streams

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

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

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

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

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

Update Room Model

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

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

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

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

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

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

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

Parameters

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

Update Room Callback Arguments

Name Type Description
status String The status of the operation

Update Room Callback Status Codes

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

Leave a Room

Leave the current active room. Self is not modified.

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

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

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

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

Parameters

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

Leave Room Callback Arguments

Name Type Description
status String The status of the operation

Update Room Callback Status Codes

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

Room Model

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

[object Room]

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

Room Types

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

[object Member]

Name Signature Returns Description
getSessionId () string The session ID of the member in the room
getObservableRole () Observable(of string) Observable of member role
getObservableState () Observable(of string) Observable of member state
getObservableScreenName () Observable(of string) Observable of member screen name
getObservableStreams () Observable(of array) Observable of array of streams belonging to the member
getObservableLastUpdate () Observable(of number) Observable of utc timestamp
getLastUpdate () Number Current last update value of the member
setStreams (streams) void Set member streams. To be used only on self member model
toJson () object Returns member object with current observable values
commitChanges () void Attempts to update server member model with any changes made locally
reload () void Reverts all local changes to the server member model

Member Roles

Role Description
Participant Member with streams and is visible to all members
Audience Member with no streams and is not visible to other members
Presenter Presenter participant member
Moderator Privileged participant member

Member States

Role Description
Active Member is active
Passive Member is not active
HandRaised Member is requesting to become active
Inactive Member is not 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)
getType () string The stream type
getObservableAudioState () Observable(of string) Observable of stream video state
getObservableVideoState () Observable(of string) Observable of stream audio state

Stream Types

Type Description
User General purpose stream
Presentation Privileged stream
Audio Audio-only stream

Stream Track States

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

Chat Service

The Chat Service provides the ability to:

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

Initializing

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

var chatService = roomService.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.
sendMessageToRoom (message, callback) void Send a message to room.
getMessages (batchSize, afterMessageId, beforeMessageId, callback) Array(of [object ChatMessage]) Get chat message history

[object ChatMessage]

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

[object ChatMessageMember]

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

Listen for Chat Messages in the Active Room

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

var chatService = new roomService.getRoomChatService();
var chatMessageObservable = chatService.getObservableChatMessages();
var batchSize = 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.

var chatService = new roomService.getRoomChatService();

chatService.start(batchSize);

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

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

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

Parameters

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

Send Message Callback Arguments

Name Type Description
status String The status of the operation

Send Message Callback Status Codes

Status Description
ok Send message succeeded
<varies>

Chat Message History

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

Get the 10 most recent messages after a message:

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

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

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

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

Get all messages between two messages:

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

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

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

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

Parameters

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

Get Messages Callback Arguments

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

Get Messages Callback Status Codes

Status Description
ok Get messages succeeded
<varies>

Observable

Observe value changes. Similar to the RxJS Behavior Subject

[object Observable]

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

Subscribe to an Observable

Receive a notification every time the observable value changes.

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

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

Parameters

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

Options

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

[object Subscription]

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

Get Observable Value

Value may be of any supported javascript type

observable.getValue(value);

Set Observable Value

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

observable.setValue(value);

Web SDK - Express

Our Express APIs provide a simple, single-step API for the easiest integration into your website

PCast Express

The PCast Express extends the PCast api to provide a single-step configuration based API for:

Initializing

var pcastExpress = new sdk.express.PCastExpress(options);

Options

Name Type Description
backendUri (required) String Url to your backend. We send requests here to authenticate and get streaming tokens.
authenticationData (required) Object Your authentication data for the user. On every request, this will be sent to your backend through a HTTP POST request and all its attributes would be accessible on the request body.
onError (optional) Function Function to be called when authentication fails or a failure occurs that is unrecoverable.
authToken (optional) String The authentication token generated using the Admin API. If not passed one will be generated automatically by querying the provided backend uri (may happen multiple times depending on the lifetime of the session).

Publishing Local Media

Publish local user media:

pcastExpress.publish(options, function callback(error, response) {
    if (error) {
        // Handle error
    }

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

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

Parameters

Name Type Description
options (required) object Publish options
callback (required) function Callback for error/success handling

Publish options

Name Type Default Value Description
capabilities (required) Array The list of all capabilities to publish with.
…getUserMediaOptions (required) getUserMedia options Constraints to get the user media.
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.
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.
monitor (optional) Object Options for monitoring a publisher for failure.
connectOptions (optional) Array of Strings List of options for publishing from a remote source.
tags (optional) Array of Strings Tags for the stream

Callback Arguments

Name Type Description
status String The status of the operation. See Publish Callback Status Codes
publisher [object Publisher] Phenix publisher object

Publishing Remote Media (Ingest)

Publish from remote sources into the Phenix platform. This enables us to distribute your source media using the Phenix platform. After publishing users may subscribe to the stream using either pcast subscribe or express subscribe.

pcastExpress.publishRemote(options, function callback(error, response) {
    if (error) {
        // Handle error
    }

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

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

Parameters

Name Type Description
options (required) object Publish Remote options
callback (required) function Callback for error/success handling

Publish Remote Options

Name Type Default Value Description
capabilities (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.

Callback Arguments

Name Type Description
status String The status of the operation. See Publish Callback Status Codes
publisher [object Publisher] Phenix publisher object

Publish a Screen Share

Publish your screen, tab, or application window. This method optimizes the monitoring and delivery of the stream for the typical conditions for screen sharing. Supported on both Firefox and Chrome. See Screen Sharing for more information on support.

pcastExpress.publishScreen(options, function callback(error, response) {
    if (error) {
        // Handle error
    }

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

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

Parameters

Name Type Description
options (required) object Publish Screen options
callback (required) function Callback for error/success handling

Publish Screen Options

Name Type Default Value Description
capabilities (required) Array The list of all capabilities to publish with.
…getUserMediaOptions (optional) getUserMedia options mediaConstraints: {screen: true} Constraints to get the screen share media.
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.
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.
monitor (optional) Object {options: {monitorFrameRate: false, videoBitRateThreshold: 1000, conditionCountForNotificationThreshold: 8}} Options for monitoring a publisher for failure.
connectOptions (optional) Array of Strings List of options for publishing from a remote source.
tags (optional) Array of Strings Tags for the stream

Callback Arguments

Name Type Description
status String The status of the operation. See Publish Callback Status Codes
publisher [object Publisher] Phenix publisher object

Subscribing to Published Media

Subscribe to streams published with the Phenix platform

pcastExpress.subscribe(options, function callback(error, response) {
    if (error) {
        // Handle error
    }

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

    // Successfully subscribed
    if (response.status === 'ok' && response.mediaStream) {
        // Do something with mediaStream

        if (response.renderer) {
            // Returned if videoElement option passed in - Do something with renderer
        }
    }
});

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

var monitorOptions = {
    options: {
        // Optional: Additional options for monitoring a stream

        conditionCountForNotificationThreshold: 4
        // Number of conditions before triggering callback - default 4
    },

    callback: function monitorCallback(error, response) {
        // Optional: Handle monitor event

        if (error) {
          // Handle error
        }

        if (response.retry) {
          response.retry();
          // Re-connects publisher or subscriber stream
        }
    }
}

Monitor Options

Name Type Default Value Description
options (optional) Object Additional Monitoring options
callback (optional) Function call function for handling monitor event

Additional Monitoring options

Name Type Default Value Description
conditionCountForNotificationThreshold Number 4 Number of conditions before triggering callback

Express Subscribe Callback Arguments

Name Type Description
status String The status of the operation. See Subscribe Callback Status Codes
mediaStream [object MediaStream] Phenix media stream object
renderer [object Renderer] Optionally returns Phenix renderer if videoElement option is passed in
retry Function Optionally returns a function to retry subscription if unable to start stream

Subscribing to Screen Share

Subscribe to screen share streams published with the Phenix platform. This method optimizes the monitoring and delivery of the stream for the typical conditions for screen sharing.

pcastExpress.subscribe(options, function callback(error, response) {
    if (error) {
        // Handle error
    }

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

    // Successfully subscribed
    if (response.status === 'ok' && response.mediaStream) {
        // Do something with mediaStream

        if (response.renderer) {
            // Returned if videoElement option passed in - Do something with renderer
        }
    }
});

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.
monitor (optional) Object {options: {monitorFrameRate: false, videoBitRateThreshold: 1000, conditionCountForNotificationThreshold: 8}} Options for monitoring a publisher for failure.
connectOptions (optional) Array of Strings List of options for subscribing
tags (optional) Array of Strings Tags for the stream

Subscribe to Screen Share Callback Arguments

Name Type Description
status String The status of the operation. See Subscribe Callback Status Codes
mediaStream [object MediaStream] Phenix media stream object
renderer [object Renderer] Optionally returns Phenix renderer if videoElement option is passed in
retry Function Optionally returns a function to retry subscription if unable to start stream

Express Get User Media

Get local user media. Use for more granular control over requesting media and handling failure. We automatically resolve any constraint errors when getting the user media:

pcastExpress.getUserMedia(options, function callback(error, response) {
    if (error) {
        // Handle error
    }

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

    // Successfully got user media
    if (response.status === 'ok' && response.userMedia) {
        // Do something with userMedia
    }
});

Parameters

Name Type Description
options (required) object Publish options
callback (required) function Callback for error/success handling

Get User Media options

Name Type Default Value Description
mediaConstraints (required) Object Media constraints on the getting the user media. For example - {audio: true, video: true}
resolution (optional) number 720 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

Callback Arguments

Name Type Description
status String The status of the operation.
userMedia native MediaStream The browser’s native media stream object.

Supported Resolutions

Any resolution may be passed. If we are unable to get the user media at that resolution we will drop to the next closest resolution at that aspect ratio in the table below. We will continue dropping to the next closest resolution until we run out of options or the user media is successfully received. Similarly, when all resolution options at an aspect ratio are 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.

var pcast = pcastExpress.getPCast();

Clean up

Dispose of all active connections and clean up all handlers.

var pcastExpress = 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:

Initializing

var roomExpress = new sdk.express.RoomExpress(options);

Options

Name Type Description
backendUri (required) String 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.

View interactive and editable example on JSFiddle

View example on Github

roomExpress.joinChannel(options, function joinChannelCallback(error, response) {
    if (error) {
        // Handle error
    }

    if (response.status === 'room-not-found') {
        // Handle room not found - Create a Channel Or Publish to a Channel
    } else if (response.status !== 'ok') {
        // Handle error
    }

    // Successfully joined channel
    if (response.status === 'ok' && response.roomService) {
        // Do something with roomService
    }
}, function subscriberCallback(error, response) {
    if (error) {
        // Handle error
    }

    if (response.status === 'no-stream-playing') {
        // Handle no stream playing in channel - Wait for one to start
    } else if (response.status !== 'ok') {
        // Handle error
    }

    // Successfully subscribed to most recent channel presenter
    if (response.status === 'ok' && response.mediaStream) {
        // Do something with mediaStream
    }
});

Parameters

Name Type Description
options (required) Options Options to join channel with
joinChannelCallback (required) Function Function to call on success/failure of joining the channel. See Join Room Callback Arguments
subscriberCallback (required) Function Function to call on when the most recent presenter changes. See Express Subscribe Callback Arguments

Options

Name Type Default Value Description
streamSelectionStrategy (optional) String Most-Recent Stream Selection Strategy
capabilities (required) Array The list of all capabilities to subscribe with.
alias (required) String Alias of the channel to view
roomId (optional) String Alternative to alias - Id of the channel to view
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.

Stream Selection Strategy

Strategy Description
Most-Recent Select the most recent stream. Viewing stream changes any time a new stream starts in the room.
High-Availability Select streams for increased reliability and redundancy. Viewing stream will only change in the event of a failure.

View Channel Subscriber Callback Status Codes

Status Description
ok Successfully subscribed to most recent presenter
no-stream-playing No presenter in room to subscribe to. Wait for presenter to join.
<varies>

Publish to a Channel

Publish to a local or remote media to a channel. Users that are viewing the channel will see your media.

View interactive and editable example on JSFiddle

View example on Github

roomExpress.publishToChannel(options, function callback(error, response) {
    if (error) {
        // Handle error
    }

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

    // Successfully published to channel
    if (response.status === 'ok' && response.publisher) {
        // Do something with publisher
    }
});

Parameters

Name Type Description
options (required) Options Options to publish to channel with
callback (required) Function Function to call on success/failure of publishing to the channel

Options

Name Type Default Value Description
room (required) Object Channel Room Options
streamType (required) String Presenter Type of stream to publish. See Stream Types
memberRole (required) String Presentation Role of member to join room as (used if not already in room). See Member Roles
enableWildcardCapability (optional) bool true Generate wildcard stream tokens to be appended to member’s stream uri. Reduces time for subscribing to published stream.
…publishOptions (required) publish options Must include any additional options for publishing local media
…publishRemoteOptions (optional) publish remote options Alternative to publishOptions. Must include any additional options for publishing remote media

Channel Room Options

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

Publish To Channel Callback Arguments

Name Type Description
status String The status of the operation. See Publish Callback Status Codes
publisher [object Publisher] Phenix publisher object

Create a Channel

roomExpress.createChannel(options, function callback(error, response) {
    if (error) {
        // Handle error
    }

    if (response.status === 'already-exists') {
        // Channel already exists
        // Do something with roomService
    } else if (response.status !== 'ok') {
        // Handle error
    }

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

Parameters

Name Type Description
options (required) Options Options to create channel with
callback (required) Function Function to call on success/failure of creating to the channel. See Create Room Callback Arguments

Options

Name Type Default Value Description
room (required) Object Channel Room Options

Join a Room

Join a room and automatically subscribe to member changes.

roomExpress.joinRoom(options, function joinRoomCallback(error, response) {
    if (error) {
        // Handle error
    }

    if (response.status === 'room-not-found') {
        // Handle room not found - Create a Channel Or Publish to a Channel
    } else if (response.status !== 'ok') {
        // Handle error
    }

    // Successfully joined room
    if (response.status === 'ok' && response.roomService) {
        // Do something with roomService
    }
}, function membersChangedCallback(members) {
    // Successfully subscribed to observable members

    // Do something with members
});

Parameters

Name Type Description
options (required) Options Options to join room with
joinRoomCallback (required) Function Function to call on success/failure of joining the room
membersChangedCallback (required) Function Function to call on when the participant members in the room changes. Returns array of Members.

Options

Name Type Default Value Description
capabilities (required) Array The list of all capabilities to subscribe with.
role (required) String Member Role to join room as
alias (required) String Alias of the channel to view
roomId (optional) String Alternative to alias - Id of the channel to view
screenName (optional) String Member screen name to join room with
streams (optional) Array of Objects Streams to join room with

Express Join Room Callback Arguments

Name Type Description
status String The status of the operation. See Join Room Callback Status Codes
roomService [object RoomService] Phenix room service object
room [object Room] Immutable Phenix room object

Publish to a Room

Publish to a local or remote media to a room. The room will be created if a room corresponding to the Room Options passed does not exist. If you have not entered the room via joinRoom or publishToRoom methods then a model for Self will be created.

roomExpress.publishToRoom(options, function callback(error, response) {
    if (error) {
        // Handle error
    }

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

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

Parameters

Name Type Description
options (required) Options Options to publish to room with
callback (required) Function Function to call on success/failure of publishing to the room

Options

Name Type Default Value Description
room (required) Object Room Options
streamType (required) String Type of stream to publish. See Stream Types
memberRole (required) String Role of member to join room as (used if not already in room). See Member Roles
enableWildcardCapability (optional) bool true Generate wildcard stream tokens to be appended to member’s stream uri. Reduces time for subscribing to published stream.
…publishOptions (required) publish options Must include any additional options for publishing local media
…publishRemoteOptions (optional) publish remote options Alternative to publishOptions. Must include any additional options for publishing remote media

Publish To Channel Callback Arguments

Name Type Description
status String The status of the operation. See Publish Callback Status Codes
publisher [object Publisher] Phenix publisher object

Publish Screen to a 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, function callback(error, response) {
    if (error) {
        // Handle error
    }

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

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

Parameters

Name Type Description
options (required) Options Options to publish to room with
callback (required) Function Function to call on success/failure of publishing to the room

Options

Name Type Default Value Description
room (required) Object Room Options
streamType (required) String Type of stream to publish. See Stream Types
memberRole (required) String Role of member to join room as (used if not already in room). See Member Roles
enableWildcardCapability (optional) bool true Generate wildcard stream tokens to be appended to member’s stream uri. Reduces time for subscribing to published stream.
…publishScreenOptions (required) publish screen options Must include any additional options for publishing screen

Publish Screen To Channel Callback Arguments

Name Type Description
status String The status of the operation. See Publish Callback Status Codes
publisher [object Publisher] Phenix publisher object

Create a Room

Create a room of any type.

roomExpress.createRoom(options, function callback(error, response) {
    if (error) {
        // Handle error
    }

    if (response.status === 'already-exists') {
        // Room already exists
        // Do something with roomService
    } else if (response.status !== 'ok') {
        // Handle error
    }

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

Options

Name Type Default Value Description
room (required) Object Room Options

Express Create Room Callback Arguments

Name Type Description
status String The status of the operation. See Create Room Callback Status Codes
room [object Room] Immutable Phenix room object

Get PCast Express

Get the underlying instance of the PCast Express. This is preferred to creating another instance as this will introduce more overhead.

var pcastExpress = roomExpress.getPCastExpress();

Clean Up

Dispose of all connections and clean up handlers.

roomExpress.dispose();

Android SDK

Initializing

Before using a PCast object, it is required to be initialized as shown.

import com.phenixp2p.pcast.PCast;
import com.phenixp2p.pcast.PCastInitializeOptions;
import com.phenixp2p.pcast.android.AndroidPCastFactory;

PCast pcast = AndroidPCastFactory.createPCast(this);

// #1 Default initialization options
pcast.initialize();

// OR

// #2 Custom initialization options (initialized by constructor)
PCastInitializeOptions initOptions = new PCastInitializeOptions(false);

pcast.initialize(initOptions);

Initialize Options

Name Description
enableProcessTerminationSignalHandling 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.

import android.util.Log;
import com.phenixp2p.pcast.PCast;
import com.phenixp2p.pcast.RequestStatus;

// Obtained via Admin API
String authenticationToken = ...;
// Previously initialized
PCast pcast = ...;

pcast.start(
    authenticationToken,
    new PCast.AuthenticationCallback() {
        @Override
        public void onEvent(
            PCast pcast,
            RequestStatus requestStatus,
            String sessionId) {
                if (requestStatus == RequestStatus.OK) {
                    Log.i("Phenix SDK Example", "PCast started...");
                } else {
                    Log.e("Phenix SDK Example", "Failed to start PCast...");
                }
        }
    },
    new PCast.OnlineCallback() {
        @Override
        public void onEvent(PCast pcast) {
            Log.i("Phenix SDK Example", "We are online...");
        }
    },
    new PCast.OfflineCallback() {
        @Override
        public void onEvent(PCast pcast) {
            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.

import com.phenixp2p.pcast.PCast;
import com.phenixp2p.pcast.RequestStatus;

// Previously initialized and started
PCast pcast = ...;

RequestStatus stopStatus = 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.

import com.phenixp2p.pcast.FacingMode;
import com.phenixp2p.pcast.PCast;
import com.phenixp2p.pcast.UserMediaOptions;
import com.phenixp2p.pcast.UserMediaStream;
import com.phenixp2p.pcast.android.AndroidPCastFactory;

// Previously initialized and started
PCast pcast = ...;

UserMediaOptions gumOptions = new UserMediaOptions();

// Customize options if desired
gumOptions.getVideoOptions().capabilityConstraints.put(
    DeviceCapability.FACING_MODE, Arrays.asList(new DeviceConstraint(FacingMode.USER)));
gumOptions.getAudioOptions().enabled = false;

pcast.getUserMedia(
    gumOptions,
    new PCast.UserMediaCallback() {
        @Override
        public void onEvent(
            PCast pcast,
            RequestStatus status,
            UserMediaStream userMediaStream) {
                // 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

Device Capability

Name Description
DeviceCapability.WIDTH Width in pixels
DeviceCapability.HEIGHT Height in pixels
DeviceCapability.FRAME_RATE Number of frames per second
DeviceCapability.FACING_MODE Facing mode
DeviceCapability.FLASH_MODE Flash mode
DeviceCapability.DEVICE_ID Device ID string (obtain from here)
DeviceCapability.LOCATION Device Location
DeviceCapability.POLAR_PATTERN Polar pattern
DeviceCapability.AUDIO_ECHO_CANCELATION_MODE Audio echo cancelation mode

Constraint Type

Name Description
ConstraintType.MIN 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.

import com.phenixp2p.pcast.UserMediaOptions;
import com.phenixp2p.pcast.UserMediaStream;

// Previously obtained via 'getUserMedia'
UserMediaStream userMediaStream = ...;

// Previously initialized and used with 'getUserMedia'
UserMediaOptions gumOptions = new UserMediaOptions();

gumOptions.getVideoOptions().capabilityConstraints.put(
    DeviceCapability.FACING_MODE, Arrays.asList(new DeviceConstraint(FacingMode.ENVIRONMENT)));
gumOptions.getVideoOptions().capabilityConstraints.put(
    DeviceCapability.FLASH_MODE, Arrays.asList(new DeviceConstraint(FlashMode.ALWAYS_ON)));
gumOptions.getVideoOptions().capabilityConstraints.put(
    DeviceCapability.HEIGHT,
    Arrays.asList(new DeviceConstraint(720, ConstraintType.EXACT)));
gumOptions.getVideoOptions().capabilityConstraints.put(
    DeviceCapability.WIDTH,
    Arrays.asList(
        new DeviceConstraint(800, ConstraintType.MIN),
        new DeviceConstraint(1500, ConstraintType.MAX)));

userMediaStream.applyOptions(gumOptions);

Enumerating Source Devices

You can get a list of available source devices.

import android.util.Log;
import com.phenixp2p.pcast.MediaType;
import com.phenixp2p.pcast.PCast;
import com.phenixp2p.pcast.SourceDeviceInfo;

// Previously initialized and started
PCast pcast = ...;

pcast.enumerateSourceDevices(
    MediaType.VIDEO,
    new PCast.EnumerateSourceDevicesCallback() {
        @Override
        public void onEvent(PCast pcast, 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

import android.util.Log;
import com.phenixp2p.pcast.MediaType;
import com.phenixp2p.pcast.PCast;
import com.phenixp2p.pcast.SourceDeviceInfo;
import com.phenixp2p.pcast.SourceDeviceType;

// Previously initialized and started
PCast pcast = ...;

pcast.enumerateSourceDevices(
    MediaType.VIDEO,
    new PCast.EnumerateSourceDevicesCallback() {
        @Override
        public void onEvent(PCast pcast, SourceDeviceInfo[] devices) {
            for (SourceDeviceInfo info : devices) {
                if (info.sourceDeviceType == SourceDeviceType.SYSTEM_OUTPUT) {
                    Log.i("Phenix SDK Example", "Screencasting is available");
                    String screenCaptureDeviceId = 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

import android.media.projection.MediaProjection;
import com.phenixp2p.pcast.android.AndroidPCastFactory;

// Previously obtained by calling
// android.media.projection.MediaProjectionManager.getMediaProjection(),
// see Android API reference.
MediaProjection mediaProjection = ...;

AndroidPCastFactory.setMediaProjection(mediaProjection);

Finally, pass the screen capture device ID

Next, pass the screen capture device ID to getUserMedia() in the user media options.

import com.phenixp2p.pcast.FacingMode;
import com.phenixp2p.pcast.PCast;
import com.phenixp2p.pcast.UserMediaOptions;
import com.phenixp2p.pcast.UserMediaStream;

// Previously initialized and started
PCast pcast = ...;

// Found by calling enumerateSourceDevices() as described above
String screenCaptureDeviceId = ...;

UserMediaOptions gumOptions = new UserMediaOptions();

gumOptions.getVideoOptions().capabilityConstraints.put(
    DeviceCapability.DEVICE_ID, Arrays.asList(new DeviceConstraint(screenCaptureDeviceId)));

pcast.getUserMedia(
    gumOptions,
    new PCast.UserMediaCallback() {
        @Override
        public void onEvent(
            PCast pcast,
            RequestStatus status,
            UserMediaStream userMediaStream) {
                // Check status and store 'userMediaStream'
        }
    });

Please follow the self explanatory code snippets for understanding above steps.

Publish a Stream

import android.util.Log;
import com.phenixp2p.pcast.MediaStream;
import com.phenixp2p.pcast.PCast;
import com.phenixp2p.pcast.Publisher;
import com.phenixp2p.pcast.RequestStatus;
import com.phenixp2p.pcast.StreamEndedReason;
import com.phenixp2p.pcast.UserMediaOptions;
import com.phenixp2p.pcast.UserMediaStream;

// Previously initialized and started
PCast pcast = ...;
// Previously obtained via Admin API
String streamToken = ...;
// Previously obtained via either PCast.subscribe()
// or UserMediaStream.getMediaStream()
MediaStream mediaStream = ...;

String[] tags = { "my-tag" };

pcast.publish(
    streamToken,
    mediaStream,
    new PCast.PublishCallback() {
        @Override
        public void onEvent(
            PCast pcast,
            RequestStatus requestStatus,
            Publisher publisher) {
                // Check status and store 'publisher'

                // The "streamId" of the publisher
                String streamId = publisher.getStreamId();

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

                // Attach publisher ended callback
                publisher.setPublisherEndedCallback(
                    new Publisher.PublisherEndedCallback() {
                        @Override
                        public void onEvent(
                            Publisher publisher,
                            StreamEndedReason reason,
                            String reasonDescription) {
                                // Called when the stream has ended
                                Log.i("Phenix SDK Example",
                                    "Publish stream ended with reason ["
                                    + reasonDescription + "]");
                        }
                    });

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

Parameters

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

import android.util.Log;
import com.phenixp2p.pcast.MediaStream;
import com.phenixp2p.pcast.PCast;
import com.phenixp2p.pcast.RequestStatus;
import com.phenixp2p.pcast.StreamEndedReason;

// Previously initialized and started
PCast pcast = ...;
// Previously obtained via Admin API
String streamToken = ...;

pcast.subscribe(
    streamToken,
    new PCast.SubscribeCallback() {
        @Override
        public void onEvent(
            PCast pcast,
            RequestStatus requestStatus,
            MediaStream mediaStream) {
                // Check status and store 'mediaStream'

                // Attach stream ended callback
                mediaStream.setStreamEndedCallback(
                    new MediaStream.StreamEndedCallback() {
                        @Override
                        public void onEvent(
                            MediaStream mediaStream,
                            StreamEndedReason reason,
                            String reasonDescription) {
                                Log.i("Phenix SDK Example",
                                    "Subscriber stream ended with reason ["
                                    + reasonDescription + "]");
                        }
                    }
                });

                // To stop later
                mediaStream.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.

import com.phenixp2p.pcast.MediaStream;
import com.phenixp2p.pcast.Renderer;
import com.phenixp2p.pcast.RendererStartStatus;
import com.phenixp2p.pcast.android.AndroidVideoRenderSurface;

// Previously obtained via either PCast.subscribe
// or PhenixUserMediaStream.mediaStream
MediaStream mediaStream = ...;

// Previously obtained, e.g., from a SurfaceView
Surface renderSurface = ...;

Renderer renderer = mediaStream.createRenderer();

RendererStartStatus status =
    renderer.start(new AndroidVideoRenderSurface(renderSurface));

if (status == RendererStartStatus.OK) {
    Log.i("Phenix SDK Example", "Renderer started successfully");
} else {
    Log.e("Phenix SDK Example", "Renderer start failed");
}

// To stop later
renderer.stop();

Preview Local User Media

import com.phenixp2p.pcast.Renderer;
import com.phenixp2p.pcast.UserMediaStream;

// Previously obtained via 'getUserMedia'
UserMediaStream userMediaStream = ...;

Renderer renderer = userMediaStream.getMediaStream().createRenderer();

Muting and Unmuting of Audio

import com.phenixp2p.pcast.Renderer;

// Previously obtained from media stream
Renderer renderer = ...;

boolean isMuted = 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.

import com.phenixp2p.pcast.Renderer;
import com.phenixp2p.android.AndroidLastFrameRenderedCallback;

// Previously obtained from media stream and started
Renderer renderer = ...;

renderer.setLastVideoFrameRenderedReceivedCallback(
    new AndroidLastFrameRenderedCallback() {
        @override
        public void onEvent(Renderer renderer, Bitmap videoFrame) {
            // Process the frame as needed
        }
    });

renderer.requestLastVideoFrameRendered();

You can also take a still image from a local stream.

import com.phenixp2p.pcast.UserMediaStream;
import com.phenixp2p.android.AndroidLastFrameCapturedCallback;

// Previously obtained via 'getUserMedia'
UserMediaStream userMediaStream = ...;

userMediaStream.setLastVideoFrameCapturedReceivedCallback(
    new AndroidLastFrameCapturedCallback() {
        @override
        public void onEvent(Renderer renderer, Bitmap videoFrame) {
            // 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.

import com.phenixp2p.pcast.DataQualityReason;
import com.phenixp2p.pcast.DataQualityStatus;
import com.phenixp2p.pcast.Publisher;
import com.phenixp2p.pcast.Renderer;

// Previously obtained from media stream and started
Renderer renderer = ...;

renderer.setDataQualityChangedCallback(
    new Renderer.DataQualityChangedCallback() {
        @Override
        public void onEvent(
            Renderer renderer,
            DataQualityStatus quality,
            DataQualityReason reason) {
                // Inform user, take action based on status and reason
        }
    });

// Previously obtained via PCast.publish
Publisher publisher = ...;

publisher.setDataQualityChangedCallback(
    new Publisher.DataQualityChangedCallback() {
        @Override
        public void onEvent(
            Publisher publisher,
            DataQualityStatus quality,
            DataQualityReason reason) {
                // 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.

import com.phenixp2p.pcast.Dimensions;
import com.phenixp2p.pcast.Renderer;

// Previously obtained from media stream
Renderer renderer = ...;

renderer.setVideoDisplayDimensionsChangedCallback(
    new Renderer.VideoDisplayDimensionsChangedCallback() {
        @Override
        public void onEvent(
            Renderer renderer,
            Dimensions displayDimensions) {
                // 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.

#import "PCast/PhenixPCastFactory.h"
#import "PCast/PhenixPCastInitializeOptions.h"

id<PhenixPCast> pcast = [PhenixPCastFactory createPCast];

// #1 Default initialization options
[pcast initialize];

// OR

// #2 Custom initialization options
struct PhenixPCastInitializeOptions initOptions;
initOptions.enableProcessTerminationSignalHandling = NO;

[pcast initialize:&initOptions];

Initialize Options

Name Description
enableProcessTerminationSignalHandling 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 = ...;

[pcast start:
    authenticationToken:
    ^(id<PhenixPCast> pcast, PhenixRequestStatus status, 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 = ...;

PhenixRequestStatus stopStatus = [pcast stop];

// Once you are done using PCast (e.g. exiting the app)
[pcast shutdown];

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 = [PhenixUserMediaOptions new]

// Customize options if desired
gumOptions.video.capabilityConstraints
    [[NSNumber numberWithInteger:PhenixDeviceCapabilityFacingMode]] =
    @[ [PhenixDeviceConstraint initWithFacingMode:PhenixFacingModeUser] ];
gumOptions.video.capabilityConstraints
    [[NSNumber numberWithInteger: PhenixDeviceCapabilityFlashMode]] =
    @[ [PhenixDeviceConstraint initWithFlashMode:PhenixFlashModeAlwaysOff] ];
gumOptions.video.capabilityConstraints
    [[NSNumber numberWithInteger: PhenixDeviceCapabilityHeight]] =
    @[ [PhenixDeviceConstraint initWithDouble:720:PhenixConstraintTypeExact] ];
gumOptions.video.capabilityConstraints
    [[NSNumber numberWithInteger: PhenixDeviceCapabilityWidth]] =
    @[ [PhenixDeviceConstraint initWithDouble:800:PhenixConstraintTypeMin],
       [PhenixDeviceConstraint initWithDouble:1500:PhenixConstraintTypeMax] ];
gumOptions.audio.enabled = NO;

[pcast getUserMedia:
    gumOptions:
    ^(id<PhenixPCast> pcast,
      PhenixRequestStatus status,
      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

Device Capability

Name Description
PhenixDeviceCapabilityWidth Width in pixels
PhenixDeviceCapabilityHeight Height in pixels
PhenixDeviceCapabilityFrameRate Number of frames per second
PhenixDeviceCapabilityFacingMode Facing mode
PhenixDeviceCapabilityFlashMode Flash mode
PhenixDeviceCapabilityDeviceId Device ID string (obtain from here)
PhenixDeviceCapabilityLocation Device Location
PhenixDeviceCapabilityPolarPattern Polar pattern
PhenixDeviceCapabilityAudioEchoCancelationMode Audio echo cancelation mode

Constraint Type

Name Description
PhenixConstraintTypeMin 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
    [[NSNumber numberWithInteger:PhenixDeviceCapabilityFacingMode]][0]
        updateFacingMode:PhenixFacingModeEnvironment];
gumOptions.video.capabilityConstraints
    [[NSNumber numberWithInteger:PhenixDeviceCapabilityFlashMode]][0]
        updateFlashMode: PhenixFlashModeAlwaysOn];

[userMediaStream applyOptions:gumOptions];

Enumerating Source Devices

You can get a list of available source devices.

#import "PCast/PhenixPCast.h"

// Previously initialized and started
id<PhenixPCast> pcast = ...;

[pcast enumerateSourceDevices:^(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" ];

[pcast publish:
    streamToken:
    mediaStream:
    ^(id<PhenixPCast> pcast, PhenixRequestStatus status, 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
        [publisher setPublisherEndedCallback:
            ^(id<PhenixPublisher> publisher,
              PhenixStreamEndedReason reason,
              NSString* reasonDescription) {
                // Called when the stream has ended
                NSLog(@"Publish stream ended with reason [%@]", reasonDescription);
            }];

        // To stop later
        [publisher stop:@"I-am-done-publishing"];
    }:
    tags];

Parameters

Name Type Description
streamToken (required) string The publish token is generated using the Admin API
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 = [userMediaStream getVideoTracks];

for (id<PhenixMediaStreamTrack> videoTrack in videoTracks) {
    [userMediaStream setFrameReadyCallback:videoTrack:^(id<PhenixFrameNotification> frameNotification) {
        [frameNotification read:^(CMSampleBufferRef frame) {
            const CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(frame);
            const size_t displayHeightInPixels = CVPixelBufferGetHeight(pixelBuffer);
            const size_t displayWidthInPixels = CVPixelBufferGetWidth(pixelBuffer);

            // Manipulate sample buffer as needed
            ...

            // Write back sample buffer
            [frameNotification write:frame];
        }];
    }];
}

NSArray<id<PhenixMediaStreamTrack>>* audioTracks = [userMediaStream getAudioTracks];

for (id<PhenixMediaStreamTrack> audioTrack in audioTracks) {
    [userMediaStream setFrameReadyCallback:audioTrack:^(id<PhenixFrameNotification> frameNotification) {
        [frameNotification read:^(CMSampleBufferRef frame) {
            const CMBlockBufferRef blockBuffer = CMSampleBufferGetDataBuffer(frame);
            const CMFormatDescriptionRef formatDescription = CMSampleBufferGetFormatDescription(frame);

            const AudioStreamBasicDescription* const audioStreamBasicDescription =
                CMAudioFormatDescriptionGetStreamBasicDescription(formatDescription);

            const size_t bufferSize = CMBlockBufferGetDataLength(blockBuffer);

            char* rawAudioData;
            size_t lengthAtOffset;
            size_t totalLength;

            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_t sampleIndex = 0; sampleIndex < bufferSize / sizeof(int16_t); ++sampleIndex) {
                    s16AudioData[sampleIndex] = 0.1 * s16AudioData[sampleIndex];
                }
            }

            // Write back sample buffer
            [frameNotification write: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 = ...;

[pcast subscribe:
    streamToken:
    ^(id<PhenixPCast> pcast,
      PhenixRequestStatus status,
      id<PhenixMediaStream> mediaStream) {
        // Check status and store 'mediaStream'

        // Attach stream ended callback
        [mediaStream setStreamEndedCallback:
            ^(id<PhenixMediaStream> mediaStream,
              PhenixStreamEndedReason reason,
              NSString* reasonDescription) {
                NSLog(@"Subscriber stream ended with reason [%@]", reasonDescription);
        }];

        // To stop later
        [mediaStream stop];
    }];

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 = [mediaStream createRenderer];

[renderer setRenderSurfaceReadyCallback:
    ^(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)
    }];

PhenixRendererStartStatus status = [renderer start];

// To stop later
[renderer stop];

Preview Local User Media

#import "PCast/PhenixRenderer.h"
#import "PCast/PhenixUserMediaStream.h"

// Previously obtained via 'getUserMedia'
id<PhenixUserMediaStream> userMediaStream = ...;

id<PhenixRenderer> renderer = [userMediaStream.mediaStream createRenderer];

Muting and Unmuting of Audio

#import "PCast/PhenixRenderer.h"

// Previously obtained from media stream
id<PhenixRenderer> renderer = ...;

BOOL isMuted = renderer.audioMuted;
[renderer muteAudio];
[renderer unmuteAudio];

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 = ...;

[renderer setLastVideoFrameRenderedReceivedCallback:
    ^(id<PhenixRenderer> pcast, CVPixelBufferRef nativeVideoFrame) {
        // NOTE: If frame is dispatched to another thread, ensure its reference
        //       is kept alive by using CVPixelBufferRetain/CVPixelBufferRelease
    }];
[renderer requestLastVideoFrameRendered];

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 = ...;

[renderer setDataQualityChangedCallback:
    ^(id<PhenixRenderer> renderer,
      PhenixDataQualityStatus status,
      PhenixDataQualityReason reason) {
        // Inform user, take action based on status and reason
    }];

// Previously obtained via PCast.publish
id<PhenixPublisher> publisher = ...;

[publisher setDataQualityChangedCallback:
    ^(id<PhenixPublisher> publisher,
      PhenixDataQualityStatus status,
      PhenixDataQualityReason reason) {
        // 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 = ...;

[renderer setVideoDisplayDimensionsChangedCallback:
    ^(id<PhenixRenderer> renderer, const struct PhenixDimensions* displayDimensions) {
        // displayDimensions->width, displayDimensions->height
        // Can get called multiple times while rendering a stream
    }];