iOS PCast™ SDK - PhenixRTS Docs

PCast™ SDK

Initializing

Before using a PCast™ object, you need to initialize it.

@import PhenixSdk;

id<PhenixPCast> pcast = [PhenixPCastFactory createPCast];

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

// OR

// #2 Custom initialization options
PhenixPCastInitializeOptions* initOptions = [PhenixPCastInitializeOptions new];
initOptions.enableProcessTerminationSignalHandling = NO;

[pcast initialize:initOptions];

Initialize Options

Name Description
enableProcessTerminationSignalHandling Controls if process termination signal handling is enabled or not
configureLogging Control if phenix logging is enabled
streamingSourceMapping Allows partial override of streaming source URIs

Stream Source Mapping

Optional field that can be provided with PhenixPCastInitializeOptions. It only has an effect on the subscriber side, and only for streams with the "streaming" capability (on both publisher and subscriber side). The property allows you to redirect requests from the SDKs player to your own CDN.

@import PhenixSdk;

id<PhenixPCastInitializeOptions> initOptions = [PhenixPCastInitializeOptions new];
initOptions.streamingSourceMapping = [PhenixStreamingSourceMapping new];

initOptions.streamingSourceMapping.patternToReplace = @"https:\/\/phenixrts\.com\/video";
initOptions.streamingSourceMapping.replacement = @"https://myown.cdn.com";
Name Description
patternToReplace A regular expression indicating with part of the incoming streaming source URI to replace
replacement The replacement string to insert into the streaming source URI

Note: The regular expression has to be properly escaped to work correctly.

Connect And Authenticate

@import PhenixSdk;

// Generated via EdgeAuth library
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...");\
    }];

Authentication Parameters

Name Type Description
authenticationToken (required) string The authentication token generated using the Phenix EdgeAuth library
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

Disconnecting

@import PhenixSdk;

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

[pcast stop];

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

Get Local User Media

@import PhenixSdk;

// 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'\
    }];

Get Local User Media 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

Note: iPhone models earlier than the iPhone 6 will be limited to publishing at 720p due to hardware limitations.

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
PhenixDeviceCapabilityAudioEchoCancellationMode Audio echo cancellation mode
PhenixDeviceCapabilityVideoSourceRotationMode Video source rotation mode
PhenixDeviceCapabilityAutoFocusMode Auto-focus mode
PhenixDeviceCapabilityAutoFocusTarget Auto-focus target

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 Cancellation Mode

Only applicable to audio devices

Name Description
PhenixAudioEchoCancellationModeAutomatic Automatically select AEC (default)
PhenixAudioEchoCancellationModeOn Enable AEC if available
PhenixAudioEchoCancellationModeOff Disabled AEC

Video source rotation mode

Only applicable to video devices. Determines how to orient captured video frames.

Follow device rotation will ensure that video frames match the orientation in which the user is holding the device, regardless of how the app UI may be oriented. This is generally the behavior expected by a user, i.e. if the user is holding the device sideways, then video should be in landscape mode.

Following UI rotation allows your app to keep the video orientation locked to the UI rotation, regardless of how the user is holding the device. This makes it possible for instance to lock your UI in portrait mode, and have portrait video output even if the user is holding the device sideways.

Name Description
PhenixVideoSourceRotationModeAutomatic Automatically select rotation mode (default)
PhenixVideoSourceRotationModeFollowDeviceRotation Video frames oriented according to how device is held
PhenixVideoSourceRotationModeFollowUiRotation Video frames oriented according to UI orientation

Auto-focus mode

Only applicable to video devices. Configures the auto-focus mode of the camera.

Name Description
PhenixAutoFocusModeAutomatic Automatically select auto-focus mode (default).
PhenixAutoFocusModeLocked Focus is locked by the device. The focus distance cannot be configured.
PhenixAutoFocusModeAutoThenLocked Focus is adjusted to a desired distance once and stays at this distance until changed.
PhenixAutoFocusModeContinuous Focus is monitored and adjusted continuously by the device. The focus distance can be configured.

Auto-focus target

The position of the captured image to focus on, only applicable to video devices.

The value must be coordinates as a CGPoint object where [0;0] is the top left of the image, and [1;1] the bottom right.

See Set Camera Focus Position for more information.

Updating Options

Sometimes you find it useful to change the camera while a stream is running or just would like to turn on the flashlight temporarily.

@import PhenixSdk;

// 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 PhenixSdk;

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

[pcast enumerateSourceDevices:^(id<PhenixPCast> pcast, NSArray<PhenixSourceDeviceInfo*>* devices) {\
    // Store devices as needed\
}:PhenixMediaTypeVideo];

Enumerating Source Devices 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 PhenixSdk;

// Previously initialized and started
id<PhenixPCast> pcast = ...;
// Previously generated via EdgeAuth library
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];

Publish a Stream Parameters

Name Type Description
streamToken (required) string The publish token is generated using the Phenix EdgeAuth library
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

Subscribe to a Stream

@import PhenixSdk;

// Previously initialized and started
id<PhenixPCast> pcast = ...;
// Previously generated via EdgeAuth library
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];\
    }];

Subscribe to a Stream Parameters

Name Type Description
streamToken (required) string The publish token is generated using the Phenix EdgeAuth library
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 PhenixSdk;

// 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];

Renderer options

It is possible to pass additional options when creating a renderer.

@import PhenixSdk;

// Previously obtained via either PCast.subscribe or PhenixUserMediaStream.mediaStream
id<PhenixMediaStream> mediaStream = ...;

PhenixRendererOptions* options = [PhenixRendererOptions new];
options.aspectRatioMode = PhenixAspectRatioModeFill;
options.useNullVideoDevice = false;
options.useNullAudioDevice = true;

id<PhenixRenderer> renderer = [mediaStream createRenderer:options];

Properties

Name Type Default Description
aspectRatioMode (optional) PhenixAspectRatioMode PhenixAspectRatioModeFill How to fill available video render surface
useNullAudioDevice (optional) BOOL false Audio will not be routed to a physical renderer device if true
useNullVideoDevice (optional) BOOL false Video will not be routed to a physical renderer device if true.
hardwareAcceleratedDecodingMode (optional) PhenixHardwareAcceleratedDecodingMode PhenixHardwareAcceleratedDecodingModeAutomatic Hardware accelerated decoding mode

When using null devices you can still use the frame-ready API to receive the raw audio and/or video frames.

Aspect Ratio Mode

Name Description
PhenixAspectRatioModeAutomatic Defaults to fill
PhenixAspectRatioModeFill Fill entire render area. Video may be truncated
PhenixAspectRatioModeLetterbox Black bars are added on sides or top/bottom of render area, video will not be truncated

Hardware Accelerated Decoding Mode

Name Description
PhenixHardwareAcceleratedDecodingModeAutomatic Use hardware decoding on certified devices
PhenixHardwareAcceleratedDecodingModeOn Always use hardware decoding
PhenixHardwareAcceleratedDecodingModeOff Always use software decoding

Preview Local User Media

@import PhenixSdk;

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

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

Muting and Unmuting of Audio

@import PhenixSdk;

// 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 PhenixSdk;

// 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 PhenixSdk;

// 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 PhenixSdk;

// 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\
    }];