# PlayerAPI Protocol

    public protocol PlayerAPI : InterceptableAPI, ViewBasedAPI

Control and manage the video player instance.

- `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 }

- `onMediaServicesReset`

  Triggered when system media services reset. The SDK user is responsible for re-enabling the AVAudioSession in this case.

  #### Declaration

  Swift

      var onMediaServicesReset: (() -> 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 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(config:)` Default implementation

  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`).

  #### Default Implementation

  #### Declaration

  Swift

      func open(config: PlayerConfiguration)

  #### Parameters

  `config` | Player configuration to open.

- `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`.

- `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`)

  Remark

  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

      @available(*, deprecated, message: "Will be removed in 4.2.0. Use `resizeMode` instead.")
      var videoGravity: AVLayerVideoGravity { get set }

- `resizeMode` Default implementation

  Determines how the video content is scaled within the player bounds.

  This is a higher-level convenience over `videoGravity`: setting `resizeMode` updates `videoGravity` and vice-versa. Unlike `videoGravity`, `resizeMode` is applied consistently across every engine (Apple/HLS, VT/DASH, GStreamer).

  Remark

  Default value is `.fit`.

  See also

  `ResizeMode`

  #### Default Implementation

  Default implementation that bridges `resizeMode` onto `videoGravity` so every conformer (players, wrappers and view controllers) shares one code path.

  #### Declaration

  Swift

      var resizeMode: ResizeMode { get set }

- `avPlayerInstance`

  Returns underlying `AVPlayer` instance.

  Remark

  Works only with `PlayerEngine.apple`.

  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 }

- `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 }