# PlayerViewControllerAPI Protocol

    public protocol PlayerViewControllerAPI : UIViewController, PlayerAPI

Control and manage the player view controller.

- `avPlayerInstance`

  Returns underlying `AVPlayer` instance.

  Remark

  Should be used for debugging purpose mainly. Using this object to modify the playback may lead to unexpected and conflicting behaviour with our API.

  #### Declaration

  Swift

      var avPlayerInstance: AVPlayer? { get }

- `playerDelegate`

  The delegate for handling player view controller events.

  #### Declaration

  Swift

      var playerDelegate: PlayerViewControllerProtocol? { get set }

### PlayerAPI surface (explicitly re-declared for parity)

- `sessionId`

  Unique identifier of this player instance session.

  #### Declaration

  Swift

      var sessionId: String { get }

- `engine`

  Returns the engine used by this player instance.

  #### Declaration

  Swift

      var engine: PlayerEngine? { get }

- `playbackState`

  Returns current stream playback state.

  Remark

  May be `nil` before player initialization is complete.

  #### Declaration

  Swift

      var playbackState: PlaybackState? { get }

- `position`

  Returns stream current position (seconds).

  Remark

  May be `nil` when no item is loaded yet.

  #### Declaration

  Swift

      var position: Double? { get }

- `onState`

  Triggered when playback state has changed.

  #### Declaration

  Swift

      var onState: ((_ previous: PlaybackState, _ state: PlaybackState) -> Void)? { get set }

- `onDuration`

  Triggered when duration is updated.

  #### Declaration

  Swift

      var onDuration: ((_ duration: Double) -> Void)? { get set }

- `onCurrentTime(rate:onChange:)`

  Set callback for current time changes at a desired rate. Rate is specified in seconds with milliseconds precision. `Min: 0.1`.

  #### Declaration

  Swift

      func onCurrentTime(rate: Double, onChange: @escaping ((Double) -> Void))

- `onStreamEventsChanged`

  Set callback for stream events.

  #### Declaration

  Swift

      var onStreamEventsChanged: (([StreamEvent], [StreamEvent]) -> Void)? { get set }

- `onStats`

  Set callback for playback stats.

  #### Declaration

  Swift

      var onStats: ((Stats) -> Void)? { get set }

- `getStats()`

  Get playback stats. If stats are not available the returned value is `nil`

  #### Declaration

  Swift

      func getStats() -> Stats?

- `getLiveStartTime()`

  Returns the live start time in seconds since the epoch or `nil` if unknown or not applicable.

  Remark

  Available when player is in state `PlaybackState.ready`.

  #### Declaration

  Swift

      func getLiveStartTime() -> Double?

- `onLiveStartTime`

  Called when live start time is available.

  #### Declaration

  Swift

      var onLiveStartTime: ((Double) -> Void)? { get set }

- `onTrackModel`

  Triggered on track model change.

  #### Declaration

  Swift

      var onTrackModel: (() -> Void)? { get set }

- `tracks`

  Returns the current track model.

  #### Declaration

  Swift

      var tracks: Tracks { get }

- `load(config:)`

  Load new player configuration.

  #### Declaration

  Swift

      @available(*, deprecated, message: "Will be removed in 4.2.0. Use open(config:﹚ instead.")
      func load(config: PlayerConfiguration)

  #### Parameters

  `config` | Player configuration.

- `getVideoTrack()`

  Return the currently selected video track or `nil` if no track is active and selected.

  #### Declaration

  Swift

      func getVideoTrack() -> VideoTrack?

- `getSelectedVideoRendition()`

  Return the rendition that is currently selected by ABR or manually.

  Remark

  This may return `nil` for streams played by `PlayerEngine.apple` due to a limitation of the underlying player.

  #### Declaration

  Swift

      func getSelectedVideoRendition() -> VideoRendition?

- `getRenderedVideoRendition()`

  Return the currently rendered rendition.

  #### Declaration

  Swift

      func getRenderedVideoRendition() -> VideoRendition?

- `getAudioTrack()`

  Return the currently selected audio track or `nil` if no track is selected.

  #### Declaration

  Swift

      func getAudioTrack() -> AudioTrack?

- `getSelectedAudioRendition()`

  Return the currently selected audio rendition or `nil` if no audio track/rendition is selected.

  Remark

  This may return nil for streams played by `PlayerEngine.apple` due to a limitation of the underlying player.

  #### Declaration

  Swift

      func getSelectedAudioRendition() -> AudioRendition?

- `getRenderedAudioRendition()`

  Return the currently rendered audio rendition or `nil` if no audio track/rendition is selected.

  #### Declaration

  Swift

      func getRenderedAudioRendition() -> AudioRendition?

- `getTextTrack()`

  Return the currently selected text track or `nil` if no track is selected.

  #### Declaration

  Swift

      func getTextTrack() -> TextTrack?

- `setVideoRendition(_:)`

  Selects the given rendition and disables ABR mode. If `nil` is passed, ABR becomes enabled.

  Remark

  Not available for `PlayerEngine.apple`.

  #### Declaration

  Swift

      func setVideoRendition(_ rendition: VideoRendition?)

  #### Parameters

  `rendition` | Video rendition.

- `setVideoTrack(_:)`

  Selects the given video track.

  #### Declaration

  Swift

      func setVideoTrack(_ track: VideoTrack)

  #### Parameters

  `track` | Video track.

- `setAudioTrack(_:)`

  Selects the given audio track.

  #### Declaration

  Swift

      func setAudioTrack(_ track: AudioTrack)

  #### Parameters

  `track` | Audio track.

- `setTextTrack(_:)`

  Selects the given subtitles track. Passing `nil` disables subtitles.

  #### Declaration

  Swift

      func setTextTrack(_ track: TextTrack?)

- `isAdaptationModeManual`

  Returns `true` is manual video rendition is enabled, `false` if ABR is enabled.

  #### Declaration

  Swift

      var isAdaptationModeManual: Bool { get }

- `bufferFullness`

  Buffered media duration in seconds, when exposed by current engine/stream type.

  Remark

  May be `nil` when metric is not available.

  #### Declaration

  Swift

      var bufferFullness: Float? { get }

- `bufferedPercentage`

  The percentage of buffered data relative to the total duration. Represents a value in the range [0, 100].

  #### Declaration

  Swift

      var bufferedPercentage: Float? { get }

- `getPictureInPictureController()`

  Initialise the `AVPictureInPictureController` and returns a reference of it.

  Remark

  Works only with `PlayerEngine.apple`. From our tests, the PiP playback becomes available on most devices when the player moves to `PlaybackState.playing`.

  #### Declaration

  Swift

      @available(tvOS 14.0, *)
      func getPictureInPictureController() -> AVPictureInPictureController?

  #### Return Value

  An initialised `AVPictureInPictureController` object.

- `continueAudioPlaybackInBackground`

  Indicates whether the player should continue the playback in the background. The default value is `false`.

  Besides setting this flag to `true` please add the UIBackgroundModes key in your app’s `Info.plist` file. Its value is an array that contains one or more strings that identify which background tasks your application supports. Specify the string value `audio`.

  Remark

  Must be called before state `.open`.

  #### Declaration

  Swift

      var continueAudioPlaybackInBackground: Bool { get set }

- `pausePlaybackOnReturnToForeground`

  Indicates whether playback should be paused when returning to the foreground. The default value is `false`.

  #### Declaration

  Swift

      var pausePlaybackOnReturnToForeground: Bool { get set }

- `playbackRate`

  A value of 1.0 (default) plays the current item at its natural rate. Setting to values lower than 1 slow down the playback; values higher than 1 speed it up.

  Remark

  Content played at `playbackRate` lower than `0.0` or higher than `2.0` will have audio muted.

  Remark

  Expects frame drops for high values.

  Remark

  Negative rates only work with `PlayerEngine.apple`. The player will use the I-Frame playlist if present; otherwise it attempts playback anyway (which usually results in choppy playback). In both cases audio is muted.

  #### Declaration

  Swift

      var playbackRate: Double { get set }

- `playbackVolume`

  The playback volume of the player instance, ranging from 0.0 through 1.0 on a linear scale. A value of 0.0 indicates silence; a value of 1.0 (the default) indicates full volume for the audio queue instance.

  Remark

  This value does not impact the device overall volume. Setting it at 1.0 (default) means: “play at the device current max volume”.

  Remark

  Must be called after the player transitions to `PlaybackState.ready`.

  Remark

  When used with `PlayerEngine.apple`, please consider this note from Apple: “Do not use this property to implement a volume slider for media playback. For that purpose, use MPVolumeView, which is customizable in appearance and provides standard media playback behaviors that users expect.

  This property is most useful on iOS to control the volume of the AVPlayer relative to other audio output, not for volume control by end users.

  #### Declaration

  Swift

      var playbackVolume: Double { get set }

- `open(autoplay:)`

  Starts loading the content. The player will transition to `PlaybackState.opening` until it has enough meta-data loaded to build up a track model and then transition to `PlaybackState.ready`.

  #### Declaration

  Swift

      @available(*, deprecated, message: "Will be removed in 4.2.0. Use open(config:﹚ instead.")
      func open(autoplay: Bool)

  #### Parameters

  `autoplay` | Whether the content shall start play automatically after the player reaches the `PlaybackState.ready`.

- `open(config:)`

  Starts loading the content with the provided configuration. The player will transition to `PlaybackState.opening` until it has enough meta-data loaded to build up a track model and then transition to `PlaybackState.ready`.

  The autoplay behavior is defined by `config.autoPlay` (defaults to `true` when `nil`).

  #### Declaration

  Swift

      func open(config: PlayerConfiguration)

  #### Parameters

  `config` | Player configuration to open.

- `play()`

  Start playback. The player will transition into `PlaybackState.play` and into `PlaybackState.playing` once the frames appear on screen. Calling this method when player is `PlaybackState.idle` is equivalent to `open(autoplay: true)`.

  #### Declaration

  Swift

      func play()

- `pause()`

  Pause playback. The player will transition into `PlaybackState.pausing` and then into `PlaybackState.paused` once the frames pause on screen.

  #### Declaration

  Swift

      func pause()

- `stop()`

  Stop playback. The player will transition into `PlaybackState.stopping` state and then into `PlaybackState.ended` once the playback stops.

  #### Declaration

  Swift

      func stop()

- `seek(_:)`

  Starts loading the content. The player will transition to `PlaybackState.seeking`. The player can either reach the new position in its buffer and will transition back to `PlaybackState.play` or `PlaybackState.pausing` depending on where it came from or it will first transition into `PlaybackState.buffering` if the requested position is not found in the current buffer.

  #### Declaration

  Swift

      @available(*, deprecated, message: "Will be removed in 4.2.0, use `seek(_ time: Double﹚` instead.")
      func seek(_ time: CMTime)

- `seek(_:)`

  Starts loading the content. The player will transition to `PlaybackState.seeking`. The player can either reach the new position in its buffer and will transition back to `PlaybackState.play` or `PlaybackState.pausing` depending on where it came from or it will first transition into `PlaybackState.buffering` if the requested position is not found in the current buffer.

  #### Declaration

  Swift

      func seek(_ time: Double)

  #### Parameters

  `time` | Seeking position in seconds.

- `triggerFatalError(_:)`

  Trigger fatal `.system` error with message and stop playback

  #### Declaration

  Swift

      func triggerFatalError(_ message: String)

- `seekableTimeRanges`

  A collection of time ranges that the player can seek to. The ranges provided might be discontinuous.

  #### Declaration

  Swift

      var seekableTimeRanges: [CMTimeRange] { get }

- `onSeekableTimeRanges`

  Set callback for seekable time ranges.

  #### Declaration

  Swift

      var onSeekableTimeRanges: (([CMTimeRange]) -> Void)? { get set }

- `minPrebufferTime`

  Minimum buffer required until playback begins (default: `6 seconds`)

  Remark

  Works only for DASH and SmoothStreaming streams.

  #### Declaration

  Swift

      var minPrebufferTime: Double { get set }

- `maxPrebufferTime`

  Maximum buffer size allowed (default: `60 seconds`). When filled to maximum, new downloads will be paused.

  Remark

  Works only for content played with player engine `.castlabs`.

  #### Declaration

  Swift

      var maxPrebufferTime: Double { get set }

- `minRebufferTime`

  Minimum buffer required after buffer underruns (default: `12 seconds`) Works only for content played with player engine `.castlabs`

  #### Declaration

  Swift

      var minRebufferTime: Double { get set }

- `isLive`

  Return `true` for live streams, `false` otherwise.

  #### Declaration

  Swift

      var isLive: Bool { get }

- `liveEdgeDelay`

  Initial live latency target - how many seconds before the live edge the playback should start (default: 10 seconds).

  Remark

  Works only when `engine` is `PlayerEngine.castlabs`.

  #### Declaration

  Swift

      var liveEdgeDelay: Double { get set }

- `chaseLiveEdge`

  Enable to make player attempt to move as closer to live edge as possible. Default is `.disabled`

  #### Declaration

  Swift

      var chaseLiveEdge: ChaseLiveEdge { get set }

- `chaseLiveEdgeCatchupThreshold`

  Maximum time to stay behind live edge, seconds Default is `10.0`

  #### Declaration

  Swift

      var chaseLiveEdgeCatchupThreshold: Double { get set }

- `chaseLiveEdgeCutoffThreshold`

  Nominal time to stay behind live edge, seconds Default is `5.0`

  #### Declaration

  Swift

      var chaseLiveEdgeCutoffThreshold: Double { get set }

- `chaseLiveEdgeHLSSegmentDuration`

  Duration of HLS segment in seconds Used when live edge chasing is set to `.skipFrames`. Default is `10.0`

  #### Declaration

  Swift

      var chaseLiveEdgeHLSSegmentDuration: Double { get set }

- `chaseLiveEdgeSpeedupRatio`

  Playback speed increase Used when live edge chasing is set to `.speedupPlayback` Default is `1.1`

  #### Declaration

  Swift

      var chaseLiveEdgeSpeedupRatio: Double { get set }

- `duration`

  Get stream duration in seconds.

  #### Declaration

  Swift

      var duration: Double { get }

- `drm`

  Returns the drm component in use by the player (if any).

  #### Declaration

  Swift

      var drm: DrmAPI? { get }

- `protectedWithoutDRM`

  Informs the player that this content is protected but without using DRM. When set to true the player enforces capture protection even in the absence of a DRM configuration, e.g. when the decryption key is obtained by other means. For example, this is useful when you play HLS content protected with standard transport (where default OS APIs are used to retrieve the key).

  - Default is `false`

  See

  See also: https://tools.ietf.org/html/draft-pantos-hls-rfc8216bis-05#section-4.4.2.4

  #### Declaration

  Swift

      var protectedWithoutDRM: Bool { get set }

- `videoGravity`

  Video gravity determines how the video content is scaled or stretched within the player bounds.

  Remark

  Default value is `AVLayerVideoGravityResizeAspect`.

  The player layer supports the following video gravity values:

  - `AVLayerVideoGravityResizeAspect`: Player should preserve the video’s aspect ratio and fit the video within the bounds.
  - `AVLayerVideoGravityResizeAspectFill`: Player should preserve the video’s aspect ratio and fill the bounds.
  - `AVLayerVideoGravityResize`: Video should be stretched to fill the bounds.

  #### Declaration

  Swift

      var videoGravity: AVLayerVideoGravity { get set }

- `error`

  Fatal error that put the player in `.error`state, if any.

  #### Declaration

  Swift

      var error: PRESTOerror? { get }

- `throwFatalErrorOnContentObscured`

  Called when AVPlayer reports obscured output due to insufficient external protection. Applies to `PlayerEngine.apple` for FairPlay-protected HLS playback.

  Remark

  If this callback is not set, the SDK uses default behavior and raises the playback error when `obscured == true`. Source: https://developer.apple.com/documentation/avfoundation/avplayer/1624254-outputobscuredduetoinsufficiente

  #### Declaration

  Swift

      var throwFatalErrorOnContentObscured: ((_ obscured: Bool) -> Bool)? { get set }

  #### Parameters

  `obscured` | `true` when output is obscured, `false` when output is restored.

  #### Return Value

  `true` to raise a playback error when obscured; `false` to avoid raising that error and wait for output conditions to improve.

- `isAnalyticsEnabled`

  Indicates whether the player allows gathering analytics data. Default value is `true`.

  #### Declaration

  Swift

      var isAnalyticsEnabled: Bool { get set }

- `allowsPictureInPicturePlayback`

  Determines whether the Picture in Picture feature is enabled.

  #### Declaration

  Swift

      var allowsPictureInPicturePlayback: Bool { get set }

- `closeWhenPlaybackEnd`

  Determines whether the player automatically closes when playback ends.

  #### Declaration

  Swift

      var closeWhenPlaybackEnd: Bool { get set }

- `requiresLinearPlayback`

  Determines whether the content can be skipped by the user.

  #### Declaration

  Swift

      var requiresLinearPlayback: Bool { get set }

- `getCurrentChannelIndex()`

  Returns the current channel index of the playlist.

  #### Declaration

  Swift

      func getCurrentChannelIndex() -> Int

- `disableChannelSkipInLiveStream`

  Prevent channel skipping in a live stream.

- `init(channels:analytics:loopChannels:)`

  Initialises an instance of the PlayerViewControllerAPI protocol.

  #### Declaration

  Swift

      init?(channels: [ChannelItem],
            analytics: [AnalyticsBackend?: AnalyticsMetadata]?,
            loopChannels: Bool)

  #### Parameters

  `channels` | A list of channels.
  `analytics` | A dictionary containing analytic backend type and metadata for the backend.
  `loopChannels` | Loop the channel list at the first or last channel. Only applicable if the number of channels is greater than 1.

- `replaceCurrentChannel(with:)`

  Replace the current channel item.

  #### Declaration

  Swift

      func replaceCurrentChannel(with channel: ChannelItem) -> Bool

  #### Parameters

  `channel` | The new channel item.

  #### Return Value

  A boolean indicating the success of the replacement.

- `close()`

  Close the player controller

  #### Declaration

  Swift

      func close()

- `setTransportBarActions(_:eventName:)`

  Add custom action controls to the transport bar.

- `setInfoTabActions(_:eventName:)`

  Add custom actions to the info tab.

- `setContextualActions(_:eventName:)`

  Show custom contextual actions.

- `setActionState(ofId:state:title:imageName:)`

  Update the state, title, and image of an action.

- `setChannelMetadata(_:)`

  Update the title, subtitle, description, and artwork image of the player item.

  #### Declaration

  Swift

      func setChannelMetadata(_ metadata: ChannelMetadata)

  #### Parameters

  `metadata` | Additional metadata for the item - title, subtitle, artwork image, and description.

- `setRate(_:)`

  Change the playback rate.

  #### Declaration

  Swift

      @available(*, deprecated, message: "Use `playbackRate` instead.")
      func setRate(_ rate: Double)

- `getCurrentTime()`

  Return the current playback position.

  #### Declaration

  Swift

      @available(*, deprecated, message: "Use `position` instead.")
      func getCurrentTime() -> CMTime