

# IVS Player SDK
<a name="player"></a>

To use Amazon Interactive Video Service (IVS), you must use the Amazon IVS Player. The Player is a cross-platform suite of SDKs for playback of Amazon IVS streams. It is designed to leverage the Amazon IVS architecture and optimized for Amazon IVS playback.

The only player whose performance we can guarantee is the Amazon IVS player. To achieve low latency, the Amazon IVS player is required.

Key features of the Amazon IVS player are:
+ **Low-latency streaming** — Low latency is a critical component in building good interactive user experiences that enrich the audience experience. Latency creeps in incrementally throughout the transmission path between broadcaster and viewer, eroding responsiveness.

  End-to-end latency is the delay from when a live stream is captured on camera to when it appears on a viewer’s screen. Amazon IVS is designed to deliver low end-to-end latency (under five seconds, depending on the broadcast location and broadcaster settings). *To achieve this low latency, the Amazon IVS player is required*.
+ **Cross-platform consistency** — Viewers watch broadcasts on a variety of platforms. From mobile devices to web browsers, the Amazon IVS Player gives all viewers a similar experience. This consistency is possible because every platform uses the same library of player functions. The player library is an integral component of the Amazon IVS architecture. Using one video stack ensures that all video-playback behaviors — including low-latency mode, timed metadata, analytics, error tracking, reporting, and logging — are available in a consistent way on all supported platforms.
+ **Adaptive bitrate streaming (ABR)** — The Amazon IVS Player uses ABR algorithms optimized for low-latency environments. The Player measures quality of service and bandwidth availability in real time and adapts video quality and buffer levels, to provide uninterrupted playback. When connection quality suffers, ABR switches to a lower bitrate; when connection quality improves, it switches to a higher bitrate.
+ **Timed metadata** — The Amazon IVS Player supports *timed metadata*, which can be used to build interactive elements such as polls and quizzes. Metadata is a set of data that describes and gives information about other data. With "timed" metadata, a timecode accompanies the piece of data about the stream. During playback, the timecode serves as a cue point to trigger action based on the data, such as:
  + Sending player statistics for a sports stream
  + Sending product details for a live shopping stream
  + Sending questions for a live quiz stream
+ **Robust error handling** — Handling transient errors well avoids interruptions in the viewing experience. The Amazon IVS Player’s robust error handling detects many potential streaming errors, automatically switching to an alternative rendition. Viewers continue watching the broadcast uninterrupted, without having to take any corrective action.
+ **Ease of integration** — The Amazon IVS Player API bridges the gap between Amazon IVS customers’ applications and the Player library. The API has bindings for all supported platforms, making it easy to integrate the Player into applications while using familiar coding environments and techniques. With full control over UI elements, customers can customize the branding and presentation aspects of their applications. 

The Amazon IVS player does not support casting with Airplay, but developers can implement Airplay by transitioning sessions to AVPlayer. However, latency on AVPlayer is higher than in the Amazon IVS player SDK, so the switch will not be seamless. An example of how to accomplish this transition is provided [here](https://github.com/aws-samples/sample-for-airplay-on-ivs).

Casting with Chromecast can be implemented outside the player using the default Chromecast receiver apps. However, latency in those apps is higher than in the Amazon IVS player SDK, so the switch will not be seamless. Also see our documentation on the Amazon IVS Broadcast SDK: for [Low-Latency Streaming](broadcast.md) and for [ Real-Time Streaming](https://docs.aws.amazon.com//ivs/latest/RealTimeUserGuide/broadcast.html).

## Browser & Platform Requirements
<a name="player-browser-platform-requirements"></a>

For details on the latest released versions of various browsers, see:
+ [Chrome Platform Status](https://chromestatus.com/roadmap)
+ [Firefox Releases](https://www.mozilla.org/en-US/firefox/releases/)
+ [Microsoft Edge Release Schedule](https://learn.microsoft.com/en-us/deployedge/microsoft-edge-release-schedule)
+ [Safari Release Notes](https://developer.apple.com/documentation/safari-release-notes)

While Amazon IVS may work with some older browsers, we do not fix bugs related to older browsers.

The IVS Player Web SDK (including the Video.js and Player JW integrations) is not supported in browser-like environments. This includes Native WebViews and “10-foot devices” (TVs, consoles, set-top boxes) which support web applications. Please contact IVS Support if you're unsure of specific browser support outside of the tables listed below.

### Desktop Browsers
<a name="player-browser-platform-requirements-desktop"></a>


| Desktop Browser | Supported Platforms | Supported Versions | 
| --- | --- | --- | 
| Chrome | Windows, macOS  | Two major versions (current and most recent prior version)  | 
| Firefox | Windows, macOS | Two major versions (current and most recent prior version) | 
| Edge | Windows 8.1 and later  | 44.0 and later (In auto-quality mode on [Microsoft Edge Legacy](https://support.microsoft.com/en-us/microsoft-edge/what-is-microsoft-edge-legacy-3e779e55-4c55-08e6-ecc8-2333768c0fb0), only normal-latency playback is supported, not low-latency playback. Auto-quality mode refers to whether ABR is enabled. For example, on the Web player, see `setAutoQualityMode`.  | 
| Safari | macOS | Two major versions (current and most recent prior version)(In auto-quality mode on Safari for macOS 14 and above, IVS Player 1.3.0 and above support low-latency playback. For earlier versions of Safari and IVS Player, only normal-latency playback is supported. See above for "auto-quality mode.") | 

### Mobile Browsers
<a name="player-browser-platform-requirements-mobile"></a>


| Mobile Browser | Supported Versions | 
| --- | --- | 
| Chrome for iOS, Safari for iOS | Two major versions (current and most recent prior version) (Low-latency playback is not supported. Normal latency playback is supported. This constraint applies to all browsers for iOS.) (Timed metadata is supported only in Player 1.3.0 and later.) | 
| Chrome for iPadOS, Safari for iPadOS | Two major versions (current and most recent prior version) (When "Request Mobile Website" is selected: [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/player.html)  | 
| Chrome for Android | Two major versions (current and most recent prior version) | 

### Native Platforms
<a name="player-browser-platform-requirements-native"></a>


| Platform | Supported Versions | Supported Devices | 
| --- | --- | --- | 
| Android | 6.0 and later | Phones and tablets | 
| iOS | 14\$1  | All | 

IVS supports a minimum of 4 major iOS versions and 6 major Android versions. Our current version support may extend beyond these minimums. Customers will be notified via SDK release notes at least 3 months in advance of a major version no longer being supported. 

## Reducing Latency in Third-Party Players
<a name="player-reducing-latency"></a>

**For Basic and Standard channel types**: For the lowest possible latency, you must use the Amazon IVS player. In third-party players (including iOS Safari), you can reduce latency to about 10 seconds by using the following configuration:
+ Set your encoder’s (e.g. OBS) keyframe interval to 2 seconds or below.
+ Add `?keyframeInterval=2` to the RTMP(S) URL. For example: `rtmps://a1b2c3d4e5f6.global-contribute.live-video.net:443/app/sk_us-west-2_abcd1234efgh5678ijkl?keyframeInterval=2`

**Note**: The keyframe interval specified as part of the RTMP URL must be greater than or equal to the value configured in the encoder; otherwise, you may have playback issues. You can set the value to any integer between 2 and 6 inclusive, but 2 enables the lowest latency.

**For Advanced channel types**: The above guidance does not apply. Advanced channel types generate keyframe intervals automatically for encoding efficiency, with at most 2 seconds between keyframes, regardless of the source encoding keyframe interval setting.

### iOS Safari
<a name="player-reducing-latency-ios-safari"></a>

In iOS Safari, you can reduce latency to approximately 6-8 seconds by using the IVS player and configuring it to use a service worker. See [Set Up Service Worker](https://docs.aws.amazon.com//ivs/latest/LowLatencyUserGuide/web-getting-started.html#web-service-worker) in the *Player SDK: Web Guide* for implementation details and a reference sample.

**Note**: Getting the lowest latency requires an IVS stream with the keyframe interval set to 2 seconds.

## Audio-Only Playback
<a name="player-audio-only-playback"></a>

All IVS channel types support audio-only renditions. This can be particularly valuable for mobile applications. For instance, in your mobile app, you can switch the player to the audio-only rendition when the user backgrounds the application to conserve bandwidth.

For ADVANCED-SD and ADVANCED-HD channels, the audio-only rendition is included automatically in the multivariant playlist. For BASIC and STANDARD channels, you must append the `?allow_audio_only=true` query parameter to the playback URL to enable inclusion of the audio-only rendition. 

Note: The IVS web player SDK supports audio-only playback only in versions 1.24.0 and later.

## Support
<a name="player-support"></a>

If you encounter a playback error or other playback issue with your stream, determine the unique playback session identifier via the player API. 


| For this Amazon IVS player: | Use this: | 
| --- | --- | 
| Android | `sessionId` function  | 
| iOS | `sessionId` property of `IVSPlayer`  | 
| Web | `getSessionId` function | 

Share this playback session identifier with AWS support. With it, they can get information to help troubleshoot your issue.

**Note:** The Player is continually improved. See [Amazon IVS Release Notes](release-notes.md) for available versions and fixed issues. If appropriate, before contacting support, update your version of the Player and see if that resolves your issue.

### Versioning
<a name="player-support-versioning"></a>

The Amazon IVS Player SDKs use [semantic versioning](https://semver.org/).

For this discussion, suppose:
+ The latest release is 4.1.3.
+ The latest release of the prior major version is 3.2.4.
+ The latest release of version 1.x is 1.5.6.

Backward-compatible new features are added as minor releases of the latest version. In this case, the next set of new features will be added as version 4.2.0.

Backward-compatible, minor bug fixes are added as patch releases of the latest version. Here, the next set of minor bug fixes will be added as version 4.1.4.

Backward-compatible, major bug fixes are handled differently; these are added to several versions:
+ Patch release of the latest version. Here, this is version 4.1.4.
+ Patch release of the prior minor version. Here, this is version 3.2.5.
+ Patch release of the latest version 1.x release. Here, this is version 1.5.7.

Major bug fixes are defined by the Amazon IVS product team. Typical examples are critical security updates and selected other fixes necessary for customers.

**Note:** In the examples above, released versions increment without skipping any numbers (e.g., from 4.1.3 to 4.1.4). In reality, one or more patch numbers may remain internal and not be released, so the released version could increment from 4.1.3 to, say, 4.1.6.

# IVS Player SDK: Web Guide
<a name="player-web"></a>

The Amazon Interactive Video Service (IVS) Web player SDK can be integrated with [player frameworks](#web-framework-integrations) like Video.js or used standalone on top of an HTML `<video>` element.

**Latest version of Web player:** 1.51.0 ([Release Notes](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/release-notes.html#apr16-26-player-web-ll))

**Reference documentation:** For information on the most important methods available in the Amazon IVS Web player, see the reference documentation at [https://aws.github.io/amazon-ivs-player-docs/1.51.0/web/](https://aws.github.io/amazon-ivs-player-docs/1.51.0/web/).

## Framework Integrations
<a name="web-framework-integrations"></a>

The Amazon IVS Web player SDK is designed to be easy to integrate with your framework of choice. We offer an official Video.js integration (“tech,” in Video.js jargon).

The following is a brief comparison of the Web players we offer:


| Player Type | Description | UI | Plugins | 
| --- | --- | --- | --- | 
| Amazon IVS Web player SDK | A lightweight and customizable option for developers who want more control. | No | No | 
|  [Amazon IVS Player Tech for Video.js](player-videojs.md)  | A full-featured option, which may be appropriate if you already use Video.js and want a turnkey solution. | Yes([Video.js Skins](https://videojs.com/guides/skins/)) | Yes([Video.js Plugins](https://videojs.com/plugins/)) | 
|  [Amazon IVS Player Provider for JW Player](player-jwplayer.md)  | A full-featured option, which may be appropriate if you already use JW Player and want a turnkey solution. | Yes | N/A | 

# Getting Started with the IVS Web Player SDK
<a name="web-getting-started"></a>

This document takes you through the steps involved in getting started with the Amazon IVS Web player SDK.

We provide support through a `script` tag as well as through an npm module. 

## Demos
<a name="web-demo"></a>

The following live demo shows how to use the Web player with a `script` tag from our Content Delivery Network: [Amazon IVS Player Sample](https://codepen.io/amazon-ivs/pen/QWbzORP/c3b13a2df34b60ada7756f3a2af8d2f0). The demo includes setting up event listeners.

Also see [https://github.com/aws-samples/amazon-ivs-player-web-sample](https://github.com/aws-samples/amazon-ivs-player-web-sample) for a selection of additional Web player demos.

## Setup With Script Tag
<a name="web-setup-script-tag"></a>

To set up the Amazon IVS player using the `script` tag:

1. Include the following tag (for the latest version of the player).

   ```
   <script src="https://player.live-video.net/1.51.0/amazon-ivs-player.min.js"></script>
   ```

1. Once `amazon-ivs-player.min.js` is loaded, it adds an `IVSPlayer` variable to the global context. This is the library you will use to create a player instance. First, check `isPlayerSupported` to determine if the browser supports the IVS player:

   ```
   if (IVSPlayer.isPlayerSupported) { ... }
   ```

   Then, to create a player instance, call the `create` function on the `IVSPlayer` object.

   ```
   const player = IVSPlayer.create();
   ```

   The Amazon IVS Web player SDK uses web workers to optimize video playback.

1. Load and play a stream using the `load` and `play` functions on the player instance:

   ```
   player.load("PLAYBACK_URL");
   player.play();
   ```

   where `PLAYBACK_URL` is the URL returned from the Amazon IVS API when a stream key is requested.

## Sample Code
<a name="web-sample-code"></a>

In this example, replace `PLAYBACK_URL` with the URL of the source stream you want to load. The example uses the latest version of the Amazon IVS player.

```
<script src="https://player.live-video.net/1.51.0/amazon-ivs-player.min.js"></script>
<video id="video-player" playsinline></video>
<script>
  if (IVSPlayer.isPlayerSupported) {
    const player = IVSPlayer.create();
    player.attachHTMLVideoElement(document.getElementById('video-player'));
    player.load("PLAYBACK_URL");
    player.play();
  }
</script>
```

In the `<video>` tag, `playsinline` is required for inline playback on iOS Safari. See [https://webkit.org/blog/6784/new-video-policies-for-ios/](https://webkit.org/blog/6784/new-video-policies-for-ios/).

## Setup With NPM
<a name="web-setup-npm"></a>

For guidance, including an example Webpack configuration file, see the following repository: [https://github.com/aws-samples/amazon-ivs-player-web-sample](https://github.com/aws-samples/amazon-ivs-player-web-sample).

**Note:** When hosting player static assets from your own domain, you must set the "Content-Type" response header for the WebAssembly binary (`amazon-ivs-wasmworker.min.wasm`) to "application/wasm." You also should gzip your assets to reduce bytes downloaded over the wire and improve the player’s time to start playback.

## TypeScript
<a name="web-typescript"></a>

If you’re using TypeScript, the npm package includes types you may want to import and use. For information on these types, see the [Amazon IVS Player SDK: Web Reference](https://aws.github.io/amazon-ivs-player-docs/1.51.0/web/).

## Set Up Service Worker
<a name="web-service-worker"></a>

To lower latency further when playing via browsers that only support native playback (primarily iOS Safari), a service worker can be set up and configured. For more context, see [Reducing Latency in Third-Party Players](player.md#player-reducing-latency).

To set up the Amazon IVS player to use a service worker:

1. Create a file to load the IVS service worker off the CDN. This is required as service workers must be hosted on the same domain as the page that pulls them in.

   Create a file named `amazon-ivs-service-worker-loader.js` or similar and add the following line:

   ```
   importScripts('https://player.live-video.net/1.51.0/amazon-ivs-service-worker.min.js');
   ```

1. When creating a player instance, pass in the following `serviceWorker` config referencing the `amazon-ivs-service-worker-loader.js` file:

   ```
   const player = IVSPlayerPackage.create({
      serviceWorker: {
         url: 'amazon-ivs-service-worker-loader.js'
      }
   });
   ```

1. On the video element, set the `crossOrigin` attribute to `anonymous`. This is required to allow the service worker to make changes to the manifest.

**Note**: To test the service worker locally, the page either needs to be served off *localhost* or *https*.

For a live demo, see the service worker example in the following repository:

[https://github.com/aws-samples/amazon-ivs-player-web-sample](https://github.com/aws-samples/amazon-ivs-player-web-sample)

## Audio-Only Playback
<a name="web-audio-only-playback"></a>

Audio-only quality must be manually selected with the `setQuality()` method. Note that the player does not support a `true` value for the second argument, `adaptive`, so by default, this argument is `false`.

To set the quality to audio-only before playback begins, call `setQuality()` inside the `READY` event:

```
player.addEventListener(PlayerState.READY, () => {
   const qualities = player.getQualities();
   const audioOnly = qualities.find(q => q.name === 'audio_only');
   if (audioOnly) {
      player.setQuality(audioOnly);
   }
});
```

Setting the quality within `READY` works for both autoplay and non-autoplay modes.

## Optimizing Background Playback
<a name="web-optimize-background-playback"></a>

Starting with SDK version 1.45.0, the client can be configured to optimize data usage while playing in a background tab. When this feature is enabled, then after the duration specified, the player selects the highest available SD video quality, with a maximum of 480p. The player always selects video; audio\$1only is not selected. This applies to both manual and auto modes. When the tab is foregrounded, the player automatically switches back to its prior setting.

To enable this feature:

```
const player = IVSPlayer.create({
   optimizeBackgroundPlayback: {
      enabled: true,
      switchDelayMs: 60 * 1000,   // Optional, defaults to 60s
   }
});
```

# Working With Content Security Policy
<a name="web-content-security-policy"></a>

The Amazon IVS Web player SDK is configured to work on pages that use Content Security Policy (CSP). A few key CSP directives must be in place. Here, we describe a minimal set of directives that are necessary. Additional directives and sources are likely necessary, depending on your specific setup.

The following directives are the minimum required for CSP: 

```
worker-src blob:;
media-src blob:;
connect-src *.live-video.net;
script-src 'wasm-unsafe-eval';
```

**Note:** Older versions of browsers may not recognize one or more of those above CSP rules (such as `wasm-unsafe-eval`) and instead could require a very lenient CSP policy (`unsafe-eval`). However, that works against the whole point of CSP to limit dangerous JavaScript from running on a page. Instead, as a workaround, we recommend that you host the library assets on the same origin as your page.

# Known Issues & Workarounds in the IVS Web Player SDK
<a name="web-issues"></a>

This document lists known issues that you might encounter when using the Amazon IVS Web player SDK and suggests potential workarounds.
+ When playing recorded content (also known as VOD) on an iOS mobile browser (e.g. Safari or Chrome), seeking backwards will mute the player.

  **Workaround:** Call `player.setMuted(false)` after seeking.
+ When playing recorded content on an iOS mobile browser, seeking backwards works intermittently when directly selecting the desired position.

  **Workaround:** Drag the seek bar to the desired position.
+ When playing recorded content on an iOS mobile browser, `player.seekTo()` calls do not consistently work.

  **Workaround:** Set `currentTime` on the video HTML element after the `loadeddata` event. For example:

  ```
  videoEl.addEventListener('loadeddata', () => {
  	videoEl.currentTime = 30; // seek 30s from the beginning
  });
  ```
+ When playing a live stream or recorded content on an iOS mobile browser, captions may not be rendered in different sizes and may be re-rendered multiple times.

  **Workaround:** None.
+ When playing a live stream or recorded content on an iOS mobile browser, `player.getQualities()` calls do not return the list of available qualities.

  **Workaround:** None. The player supports only auto-quality mode on iOS browsers.
+ When native HTML5 controls are enabled, calls to `setQuality()` are ignored.

  **Workaround:** Disable HTML5 controls before calling `player.setQuality()`.
+ When playing a muted live stream on an iOS mobile browser, player instability (e.g., black or frozen screen, buffering) may be seen when resuming an inactive player tab (e.g., tab switches or device lock/unlock).

  **Workaround:** Use the JavaScript [Page Visibility API](https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API) to detect page visibility changes and then take action on the player accordingly. For example:

  ```
  //if client platform is iOS
  if (!!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)) {
      document.addEventListener(“visibilitychange”, () => {
          if (document.visibilityState === “hidden” && player.isMuted()) {
              player.pause()
          if (document.visibilityState === “visible” &&
              player.getState() != PlayerState.PLAYING) {
              player.play()
          }
      })
  }
  ```
+ When using the Web player SDK on iOS Safari, playback authorization will not work without a service worker due to limited iOS support for Media Source Extensions (MSE).

  **Workaround:** Implement a service worker with the Player SDK. See [Set Up Service Worker](web-getting-started.md#web-service-worker) and this [demo](https://github.com/aws-samples/amazon-ivs-player-web-sample/blob/master/samples/service-worker/service-worker.ts).

# IVS Player SDK: Android Guide
<a name="player-android"></a>

The Amazon Interactive Video Service (IVS) Android player SDK provides the interfaces required to use the Amazon IVS player on Android.

We guarantee playback performance only for Android mobile devices (phones and tablets). We do not support Android TV, Fire TV, IoT devices, and emulators.

The `com.amazonaws.ivs.player` package implements the interface described in this document. The following operations are supported: 
+ Set up (initialize) a player. 
+ Manage playback. 
+ Manage quality. 
+ Receive events. 
+ Receive errors. 

**Latest version of Android player:** 1.51.0 ([Release Notes](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/release-notes.html#apr16-26-player-mobile-ll)) 

**Reference documentation:** For information on the most important methods available in the Amazon IVS Android player, see the reference documentation at [https://aws.github.io/amazon-ivs-player-docs/1.51.0/android/](https://aws.github.io/amazon-ivs-player-docs/1.51.0/android/).

**Sample code: **See the Android sample repository on GitHub: [https://github.com/aws-samples/amazon-ivs-player-android-sample](https://github.com/aws-samples/amazon-ivs-player-android-sample).

**Platform requirements:** Android 6.0\$1

A **React Native wrapper** for the Amazon IVS Player SDK is available. For the code and documentation, see [https://github.com/aws/amazon-ivs-react-native-player](https://github.com/aws/amazon-ivs-react-native-player).

# Getting Started with the IVS Android Player SDK
<a name="android-getting-started"></a>

This document takes you through the steps involved in getting started with the Amazon IVS Android player SDK.

## Install the Library
<a name="android-install"></a>

To add the Amazon IVS Android player library to your Android development environment, add the library to your module’s `build.gradle` file, as shown here (for the latest version of the Amazon IVS player).

```
repositories {
    mavenCentral()
}
 
dependencies {
     implementation 'com.amazonaws:ivs-player:1.51.0'
}
```

Alternately, to install the SDK manually, download the latest version from this location:
+ [https://search.maven.org/artifact/com.amazonaws/ivs-player](https://search.maven.org/artifact/com.amazonaws/ivs-player)

## Using the SDK with Debug Symbols
<a name="player-android-using-debug-symbols-ll"></a>

We also publish a version of the Android player SDK which includes debug symbols. You can use this version to improve the quality of debug reports (stack traces) in Firebase Crashlytics, if you run into crashes in the IVS player SDK; i.e., `libplayercore.so`. When you report these crashes to the IVS SDK team, the higher quality stack traces make it easier to fix the issues.

To use this version of the SDK, in your Gradle build files, replace this line:

```
implementation "com.amazonaws:ivs-player:$version@aar"
```

with this:

```
implementation "com.amazonaws:ivs-player:$version:unstripped@aar"
```

### Uploading Symbols to Firebase Crashlytics
<a name="player-android-debug-symbols-ll-firebase-crashlytics"></a>

Ensure that your Gradle build files are set up for Firebase Crashlytics. Follow Google’s instructions here:

[https://firebase.google.com/docs/crashlytics/ndk-reports](https://firebase.google.com/docs/crashlytics/ndk-reports)

Be sure to include `com.google.firebase:firebase-crashlytics-ndk` as a dependency.

When building your app for release, the Firebase Crashlytics plugin should upload symbols automatically. To upload symbols manually, run either of the following:

```
gradle uploadCrashlyticsSymbolFileRelease
```

```
./gradlew uploadCrashlyticsSymbolFileRelease
```

(It will not hurt if symbols are uploaded twice, both automatically and manually.)

### Preventing your Release .apk from Becoming Larger
<a name="player-android-debug-symbols-ll-sizing-apk"></a>

Before packaging the release `.apk` file, the Android Gradle Plugin automatically tries to strip debug information from shared libraries (including the IVS player SDK's `libplayercore.so` library). However, sometimes this does not happen. In that case, your `.apk` file could become larger and you could get a warning message from the Android Gradle Plugin that it’s unable to strip debug symbols and is packaging `.so` files as is. If this happens, do the following:
+ Install an Android NDK. Any recent version will work.
+ Add `ndkVersion <your_installed_ndk_version_number>` to your application’s `build.gradle` file. Do this even if your application itself does not contain native code.

For more information, see this [issue report](https://issuetracker.google.com/issues/353554169).

## Create the Player and Set Up Event Listener
<a name="android-create-player"></a>

The player interface is `com.amazonaws.ivs.player.Player`. Initialize it as shown below:

```
// Create a player instance
// <this> refers to the current Android Activity
player = Player.Factory.create(this);

// Set up to receive playback events and errors 
player.addListener(this);
```

Alternately, initialize by using `PlayerView`:

```
// Create a player instance
// <this> refers to the current Android Activity
PlayerView playerView = new PlayerView(this);
Player player = playerView.getPlayer();
// Set up to receive playback events and errors 
player.addListener(this);
```

**Note:** The listener callback methods are executed in the main thread of your Android application.

## Set the Surface View for Video
<a name="android-set-surface-view"></a>

If not using `PlayerView` add a `SurfaceView` to your Android UI layout for displaying a video. This `Surface` must be available before you can play any video streams. You can access the underlying surface through the `SurfaceHolder` interface, which is retrieved by calling `getHolder()`. (See [SurfaceView](https://developer.android.com/reference/android/view/SurfaceView.html) in the Android developer reference). Use the `SurfaceHolder.Callback` to receive events about surface changes (see [SurfaceHolder.Callback](https://developer.android.com/reference/android/view/SurfaceHolder.Callback)).

```
surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
surfaceView.getHolder().addCallback(this);

@Override
public void surfaceCreated(SurfaceHolder holder) {
   this.surface = holder.getSurface();
   if (player != null) {
       player.setSurface(this.surface);
   }
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
   this.surface = null;
   if (player != null) {
       player.setSurface(null);
   }
}
```

## Play a Stream
<a name="android-play-stream"></a>

Because the stream is loaded asynchronously, the player must be in a `READY` state before your application can call the `play` method to begin playback. Use the `Player.Listener` interface to determine when the player is in the correct state.

See the following sample code:

```
player.load(Uri.parse(url));

@Override
public void onStateChanged(Player.State state) {
    switch (state) {
        case BUFFERING:
            // player is buffering
            break;
        case READY:
            player.play();
            break;
        case IDLE:
            break;
        case PLAYING:
            // playback started
            break;
     }
}
```

## Release the Player
<a name="android-release-player"></a>

The `player.release()` method *must* be called when the player is no longer in use, to free the resources used by the library. Typically this is done in the `onDestroy` callback of the Activity or Fragment containing the player.

```
@Override
protected void onDestroy() {
    super.onDestroy();
    player.removeListener(this);
    player.release();
}
```

After the `player.release()` method is called the player can no longer be used.

## Permissions
<a name="android-permissions"></a>

The Android player SDK requires the following permission: 

```
<uses-permission android:name="android.permission.INTERNET" />
```

In addition, these optional permissions can improve the playback experience: 

```
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
```

## Thread Safety
<a name="android-thread-safety"></a>

The player API is not thread safe. All calls made to a player instance should be from the same thread.

## SDK Size
<a name="android-sdk-size"></a>

The Amazon IVS player SDKs are designed to be as lightweight as possible. For current information about SDK size, see the [Release Notes](release-notes.md).

**Important:** When evaluating size impact, the size of the AAB/APK produced by Android Studio is not representative of the size of your app downloaded to a user’s device. The Google Play Store performs optimizations to reduce the size of your app. We recommend that you use [Android App Bundles](https://developer.android.com/guide/app-bundle) to serve optimized apps for each device configuration.

# Known Issues & Workarounds in the IVS Android Player SDK
<a name="android-issues"></a>

This document lists known issues that you might encounter when using the Amazon IVS Android player SDK and suggests potential workarounds.
+ The Android player SDK has a runtime dependency on OkHttp version 4.x. Using OkHttp version 3.x may cause instability or crashes due to an API signature mismatch and OkHttp backwards compatibility issues. Specifically, the player depends on OkHttp version 4.2.2, but it should be compatible with any 4.x version.

  **Workaround:** Use a 4.x version of OkHttp or remove OkHttp from your application.
+ When using an Android 11 (API level 30) emulator, you may experience video-layout issues (specifically, zooming of the stream).

  **Workaround:** Play back on the real device instead.

# IVS Player SDK: iOS Guide
<a name="player-ios"></a>

The Amazon Interactive Video Service (IVS) iOS player provides the interfaces required to use the Amazon IVS player on iOS.

**Latest version of iOS player:** 1.51.0 ([Release Notes](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/release-notes.html#apr16-26-player-mobile-ll))

**Reference documentation:** For information on the most important methods available in the Amazon IVS iOS player, see the reference documentation at [https://aws.github.io/amazon-ivs-player-docs/1.51.0/ios/](https://aws.github.io/amazon-ivs-player-docs/1.51.0/ios/).

**Sample code:** See the iOS sample repository on GitHub: [https://github.com/aws-samples/amazon-ivs-player-ios-sample](https://github.com/aws-samples/amazon-ivs-player-ios-sample).

**Platform requirements:** iOS 14\$1

A **React Native wrapper** for the Amazon IVS Player SDK is available. For the code and documentation, see [https://github.com/aws/amazon-ivs-react-native-player](https://github.com/aws/amazon-ivs-react-native-player).

# Getting Started with the IVS iOS Player SDK
<a name="ios-getting-started"></a>

This document takes you through the steps involved in getting started with the Amazon IVS iOS player SDK.

We recommend that you integrate the player SDK via Swift Package Manager. (Alternately, you can manually add the framework to your project.)

## Recommended: Integrate the Player SDK (Swift Package Manager)
<a name="ios-integrate-sdk-swift"></a>

1. Download the Package.swift file from [https://player.live-video.net/1.51.0/Package.swift](https://player.live-video.net/1.51.0/Package.swift).

1. In your project, create a new directory named AmazonIVSPlayer and add it to version control.

1. Put the downloaded Package.swift file in the new directory.

1. In Xcode, go to **File > Add Package Dependencies** and select **Add Local...**

1. Navigate to and select the AmazonIVSPlayer directory that you created, and select **Add Package**.

1. When prompted to **Choose Package Products for AmazonIVSPlayer**, select **AmazonIVSPlayer** as your **Package Product** by setting your application target in the **Add to Target** section.

1. Select **Add Package**.

## Alternate Approach: Install the Framework Manually
<a name="ios-install-framework-manually"></a>

1. Download the latest version from [https://player.live-video.net/1.51.0/AmazonIVSPlayer.xcframework.zip](https://player.live-video.net/1.51.0/AmazonIVSPlayer.xcframework.zip).

1. Extract the contents of the archive. `AmazonIVSPlayer.xcframework` contains the SDK for both device and simulator.

1. Embed `AmazonIVSPlayer.xcframework` by dragging it into the **Frameworks, Libraries, and Embedded Content** section of the **General** tab for your application target:  
![\[The Frameworks, Libraries, and Embedded Content section of the General tab for your application target.\]](http://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/images/iOS_Player_SDK_Guide_xcframework.png)

## Create Player
<a name="ios-create-player"></a>

The player object is `IVSPlayer`. It can be initialized as shown below:

------
#### [ Swift ]

```
import AmazonIVSPlayer

let player = IVSPlayer()
```

------
#### [ Objective-C ]

```
#import <AmazonIVSPlayer/AmazonIVSPlayer.h>

IVSPlayer *player = [[IVSPlayer alloc] init];
```

------

## Set Up Delegate
<a name="ios-setup-delegate"></a>

Delegate callbacks provide information on playback state, events, and errors. All callbacks are invoked on the main queue.

------
#### [ Swift ]

```
// Self must conform to IVSPlayer.Delegate
player.delegate = self
```

------
#### [ Objective-C ]

```
// Self must conform to IVSPlayer.Delegate
player.delegate = self
```

------

## Display Video
<a name="ios-display-video"></a>

The player displays video in a custom layer, `IVSPlayerLayer`. The SDK also provides `IVSPlayerView`, a `UIView` subclass backed by this layer. Use whichever is more convenient for your application’s UI.

In both cases, display the video from a player instance by using the `player` property.

------
#### [ Swift ]

```
// When using IVSPlayerView:
playerView.player = player

// When using IVSPlayerLayer:
playerLayer.player = player
```

------
#### [ Objective-C ]

```
// When using IVSPlayerView:
playerView.player = player;

// When using IVSPlayerLayer:
playerLayer.player = player;
```

------

## Load a Stream
<a name="ios-load-stream"></a>

The player loads the stream asynchronously. Its state indicates when it is ready to play.

------
#### [ Swift ]

```
player.load(url)
```

------
#### [ Objective-C ]

```
[player load:url];
```

------

## Play a Stream
<a name="ios-play-stream"></a>

When the player is ready, use `play` to begin playback. Use the delegate interface or key-value observing on the `state` property to observe the state change. Here is an example of the delegate-based approach:

------
#### [ Swift ]

```
func player(_ player: IVSPlayer, didChangeState state: IVSPlayer.State) {
    if state == .ready {
        player.play()
    }
}
```

------
#### [ Objective-C ]

```
- (void)player:(IVSPlayer *)player didChangeState:(IVSPlayerState)state {
    if (state == IVSPlayerStateReady) {
        [player play];
    }
}
```

------

## Pause On App Backgrounding
<a name="ios-pause-on-app-backgrounding"></a>

The player does not support playback while the app is in the background, but it does not need to be fully torn down. Pausing is sufficient; see the examples below.

------
#### [ Swift ]

```
override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self,
        selector: #selector(applicationDidEnterBackground(_:)),
        name: UIApplication.didEnterBackgroundNotification,
        object: nil)
}

@objc func applicationDidEnterBackground(_ notification: NSNotification) {
    playerView?.player?.pause()
}
```

------
#### [ Objective-C ]

```
- (void)viewDidLoad {
    [super viewDidLoad];

    NSNotificationCenter *defaultCenter = NSNotificationCenter.defaultCenter;
    [defaultCenter addObserver:self
                      selector:@selector(applicationDidEnterBackground:)
                          name:UIApplicationDidEnterBackgroundNotification
                        object:nil];
}

- (void)applicationDidEnterBackground:(NSNotification *)notification {
    [playerView.player pause];
}
```

------

## Thread Safety
<a name="ios-thread-safety"></a>

The player API is not thread safe. You should create and use a player instance from the application main thread.

## SDK Size
<a name="ios-sdk-size"></a>

The Amazon IVS player SDKs are designed to be as lightweight as possible. For current information about SDK size, see the [Release Notes](release-notes.md).

**Important:** When evaluating size impact, the size of the IPA produced by Xcode is not representative of the size of your app downloaded to a user’s device. The App Store performs optimizations to reduce the size of your app.

## Putting It All Together
<a name="ios-putting-together"></a>

The following simple, view-controller snippet loads and plays a URL in a player view. Note that the `playerView` property is initialized from an XIB/Storyboard, and its class is set to `IVSPlayerView` in Interface Builder [using the Custom Class section of the Identity Inspector.](https://developer.apple.com/tutorials/SwiftUI)

------
#### [ Swift ]

```
import AmazonIVSPlayer

class MyViewController: UIViewController {
...
    // Connected in Interface Builder
    @IBOutlet var playerView: IVSPlayerView!

    override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(self,
            selector: #selector(applicationDidEnterBackground(_:)),
            name: UIApplication.didEnterBackgroundNotification,
            object: nil)
    }

    @objc func applicationDidEnterBackground(_ notification: NSNotification) {
        playerView?.player?.pause()
    }
...
    // Assumes this view controller is already loaded.
    // For example, this could be called by a button tap.
    func playVideo(url videoURL: URL) {
        let player = IVSPlayer()
        player.delegate = self
        playerView.player = player
        player.load(videoURL)
    }
}

extension MyViewController: IVSPlayer.Delegate {
    func player(_ player: IVSPlayer, didChangeState state: IVSPlayer.State) {
        if state == .ready {
            player.play()
        }
    }
}
```

------
#### [ Objective-C ]

```
// MyViewController.h

@class IVSPlayerView;

@interface MyViewController: UIViewController
...
// Connected in Interface Builder
@property (nonatomic) IBOutlet IVSPlayerView *playerView;
...
@end


// MyViewController.m

#import <AmazonIVSPlayer/AmazonIVSPlayer.h>

@implementation MyViewController <IVSPlayerDelegate>
...

- (void)viewDidLoad {
    [super viewDidLoad];

    NSNotificationCenter *defaultCenter = NSNotificationCenter.defaultCenter;
    [defaultCenter addObserver:self
                      selector:@selector(applicationDidEnterBackground:)
                          name:UIApplicationDidEnterBackgroundNotification
                        object:nil];
}

- (void)applicationDidEnterBackground:(NSNotification *)notification {
    [playerView.player pause];
}

// Assumes this view controller is already loaded.
// For example, this could be called by a button tap.
- (void)playVideoWithURL:(NSURL *)videoURL {
    IVSPlayer *player = [[IVSPlayer alloc] init];
    player.delegate = self;
    playerView.player = player;
    [player load:videoURL];
}

- (void)player:(IVSPlayer *)player didChangeState:(IVSPlayerState)state {
    if (state == IVSPlayerStateReady) {
        [player play];
    }
}

...
@end
```

------

# Known Issues & Workarounds in the IVS iOS Player SDK
<a name="ios-issues"></a>

This document lists known issues that you might encounter when using the Amazon IVS iOS player SDK and suggests potential workarounds.
+ The player may crash when testing against the arm64e architecture. This only applies when targeting arm64e specifically, and does not apply to App Store builds.

  **Workaround:** Do not use arm64e.

# IVS Player SDK: Video.js Integration
<a name="player-videojs"></a>

This document describes the most important functions available in the Amazon Interactive Video Service (IVS) Video.js player.

**Latest version of Video.js player integration:** 1.51.0 ([Release Notes](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/release-notes.html#apr16-26-player-web-ll))

## Getting Started
<a name="videojs-getting-started"></a>

Amazon IVS support for Video.js is implemented through a Video.js [tech](https://videojs.com/guides/tech/). We provide support through script tags as well as through an npm module. Amazon IVS supports Video.js versions 7.6.6 and later 7\$1, and 8\$1.

Note that when instantiating the player, the Video.js [sources option](https://videojs.com/guides/options/#sources) is not supported. Instead, instantiate the player normally and call the Video.js `src()` function. If autoplay is enabled, the stream will start playing; otherwise, use `play()` to start playback.

### Demo
<a name="videojs-demo"></a>

The following live demo shows how to use the Video.js integration with script tags from our Content Delivery Network: [Amazon IVS Player Video.js integration](https://codepen.io/amazon-ivs/pen/NWqewZo/bdc01e977102051eae5fb85482f88276).

### Setup With Script Tag
<a name="videojs-script-tag-setup"></a>

To set up the Amazon IVS tech using the `script` tag:

1. Include the following tag (for the latest version of the player integration).

   ```
   <script src="https://player.live-video.net/1.51.0/amazon-ivs-videojs-tech.min.js"></script>
   ```

1. Register the tech using the `registerIVSTech` function:

   ```
   registerIVSTech(videojs);
   ```

   where `videojs` is the object provided by Video.js.

1. When creating an instance of the player, add `AmazonIVS` as your first tech in the `techOrder` option.

When instantiating the player, the Video.js [sources option](https://videojs.com/guides/options/#sources) is not supported. Instead, to set the source, instantiate the player normally, then call the Video.js `src()` function on it. If autoplay is enabled, the stream will start playing; otherwise, use `play()` to start playback.

### Sample Code
<a name="videojs-sample-code"></a>

In this example, `PLAYBACK_URL` is the source stream you want to load. The example uses the latest version of the Amazon IVS Player.

```
<!doctype html>
<html lang="en">
<head>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/video.js/7.14.3/video-js.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/video.js/7.14.3/video.min.js"></script>
    <script src="https://player.live-video.net/1.51.0/amazon-ivs-videojs-tech.min.js"></script>
</head>

<body>
    <div class="video-container">
        <video id="amazon-ivs-videojs" class="video-js vjs-4-3 vjs-big-play-centered" controls autoplay playsinline></video>
    </div>
    <style>
        body {
            margin: 0;
        }

        .video-container {
            width: 640px;
            height: 480px;
            margin: 15px;
        }
    </style>
    <script>
        (function play() {
            // Get playback URL from Amazon IVS API
            var PLAYBACK_URL = '';
            
            // Register Amazon IVS as playback technology for Video.js
            registerIVSTech(videojs);

            // Initialize player
            var player = videojs('amazon-ivs-videojs', {
               techOrder: ["AmazonIVS"]
            }, () => {
               console.log('Player is ready to use!');
               // Play stream
               player.src(PLAYBACK_URL);
            });
        })();
    </script>
</body>
</html>
```

### Setup With NPM
<a name="videojs-npm-setup"></a>

To use Amazon IVS player through npm: 

1. Install the [video.js](https://www.npmjs.com/package/video.js/v/7.6.6) npm package or ensure that your project has some other access to the Video.js library.

1.  Install the `amazon-ivs-player` npm package:

   ```
   npm install amazon-ivs-player
   ```

1. When you’re ready to register the Amazon IVS tech, import the `registerIVSTech` function:

   ```
   import { registerIVSTech } from 'amazon-ivs-player';
   ```

1. Register the tech using the `registerIVSTech` function:

   ```
   registerIVSTech(videojs, options);
   ```

   where:
   + `videojs` is the object provided by Video.js.
   + `options` is the options for the Amazon IVS tech layer. Supported options are:.
     + `wasmWorker`: URL where the `amazon-ivs-wasmworker.min.js` file is hosted.
     + `wasmBinary`: URL where the `amazon-ivs-wasmworker.min.wasm` file is hosted.

     The worker files are in your `node_modules/` folder under `amazon-ivs-player/dist/`. You need to host them, to use the IVS player.

1. When creating an instance of the player, add `AmazonIVS` as your first tech in the `techOrder` option:

   ```
   const player = videojs('videojs-player', {
       techOrder: ["AmazonIVS"]
   });
   ```

### TypeScript
<a name="videojs-typescript"></a>

If you’re using TypeScript, our npm package includes the following types you may want to import and use.
+ `VideoJSEvents`, which describes the returned structure from `getIVSEvents()`.
+ `VideoJSIVSTech`, which describes the interface to a player instance that uses the `AmazonIVS` tech. This can be [intersected](https://www.typescriptlang.org/docs/handbook/advanced-types.html#intersection-types) with the `VideoJsPlayer` type exposed by the [@types/video.js](https://www.npmjs.com/package/@types/video.js) npm package.
+ `TechOptions`, which describes the interface defining the configuration options you can send to `registerIVSTech()`.

For more information on these types, see the [Amazon IVS Player SDK: Web Reference](https://aws.github.io/amazon-ivs-player-docs/1.51.0/web/).

## Events
<a name="videojs-events"></a>

To listen to standard Video.js events, use the [on](https://docs.videojs.com/docs/api/player.html#Methodson) function of the Video.js player.

To listen to events that are specific to Amazon IVS, add and remove event listeners on the Amazon IVS Web player:

```
player.getIVSPlayer().addEventListener(event, callback);
player.getIVSPlayer().removeEventListener(event, callback);
```

where `callback` is a callback you define, and `event` is one of: `PlayerEventType` or `PlayerState`. For more information about events, see the [Amazon IVS Player SDK: Web Reference](https://aws.github.io/amazon-ivs-player-docs/1.51.0/web/).

## Errors
<a name="videojs-errors"></a>

For general Video.js errors, listen to the generic `error` event on the player:

```
player.on("error", callback);
```

For errors specific to Amazon IVS, listen on the Amazon IVS player for its own errors:

```
let playerEvent = player.getIVSEvents().PlayerEventType;
player.getIVSPlayer().addEventListener(playerEvent.ERROR, callback);
```

The callback will receive an object with the following fields:


| Field | Description | 
| --- | --- | 
| `type` |  The error type. Corresponds to `ErrorType` events. For more information, see [Amazon IVS Player SDK: Web Reference](https://aws.github.io/amazon-ivs-player-docs/1.51.0/web/).  | 
| `code` | The error code. | 
| `source` | Source of the error. | 
| `message` | Human readable error message. | 

## Plugins
<a name="videojs-plugins"></a>

We provide a plugin that creates a UI toggle for available qualities. To use this plugin, it must be loaded by including the `amazon-ivs-quality-plugin.min.js` file if you are using our tech through the following `script` tag (for the latest version of the IVS Player): 

```
<script src="https://player.live-video.net/1.51.0/amazon-ivs-quality-plugin.min.js"></script>
```

If you are using npm, import the `registerIVSQualityPlugin` from the `amazon-ivs-player` module:

```
import { registerIVSQualityPlugin } from 'amazon-ivs-player';
```

Then, once you create an instance of your Video.js player, the following calls are required to register and enable it:

```
registerIVSQualityPlugin(videojs); // where videojs is the video.js variable
player.enableIVSQualityPlugin(); // where player is the instance of the videojs player
```

This will create a UI menu button which allows you to select a quality for the stream.

### Plugins and TypeScript
<a name="videojs-plugins-typescript"></a>

If you’re using TypeScript, our npm package includes the `VideoJSQualityPlugin` type that you may want to import and use with our plugin. Plugins essentially are mixins, so this type interface is to be used as an [intersection type](https://www.typescriptlang.org/docs/handbook/advanced-types.html#intersection-types) with the `VideoJSIVSTech` typescript interface.

## Content Security Policy
<a name="videojs-content-security-policy"></a>

The Amazon IVS Video.js API is configured to work on pages that use Content Security Policy (CSP). See the section on “Working with Content Security Policy” in the [IVS Player SDK: Web Guide](web-content-security-policy.md).

## Functions
<a name="videojs-functions"></a>

### Playback
<a name="videojs-functions-playback"></a>

The Amazon IVS Video.js API supports the necessary interfaces for internal use by the Video.js framework. The client application is not likely to need to use these methods directly, since Video.js does the necessary integration and presents a standard interface. However, if needed, one way to access internal Video.js and Amazon IVS player methods is to use the Video.js player object to get the needed object handle to the tech.

To access the API, retrieve the instance of your Video.js player as you would normally:

```
let player = videojs("videoTagId"); //replace videoTagId with your <video> tag’s id
```

Then you can call functions on that instance.

The following are the subset of Video.js functions that the Amazon IVS tech layer overrides. For the full list of Video.js functions, see the [video.js API documentation](https://docs.videojs.com/player).


| Function | Description and Amazon IVS-Specific Information | 
| --- | --- | 
| `currentTime` |  Gets or sets the time (in seconds from the beginning). Amazon IVS: We do not recommend setting current time for live streams.  | 
| `dispose` | Deletes the player instance Amazon IVS: This also deletes the Amazon IVS tech backend.  | 
| `duration` | Returns the duration of the video, in seconds. Amazon IVS: For live streams, this returns `Infinity`.  | 
| `load` | Starts loading the `src()` data. Amazon IVS: This is a no-op.  | 
| `play` | Plays the stream that was set up via the `src` call. Amazon IVS: If a live stream was paused, this plays the live stream from the latest frames, instead of continuing from where it was paused.   | 
| `playbackRate` | Gets or sets the video-playback rate. 1.0 means normal speed; 0.5, half normal speed; 2.0, two times normal speed; and so on. Amazon IVS: On a live stream, a get returns 1, and a set is ignored.  | 
| `seekable` | Returns the `TimeRanges` of the media that can be seeked to. Amazon IVS: For live streams, calling `end(0)` on the return value (`TimeRange`) returns Infinity.  | 

### Amazon IVS Specific
<a name="videojs-functions-ivs"></a>

The Amazon IVS Video.js tech has additional functions for accessing behaviors specific to Amazon IVS features:


| Function | Description | 
| --- | --- | 
| `getIVSPlayer` |  Returns the underlying Amazon IVS player instance. The full Amazon IVS Player Web API is available through this instance. We recommend using the basic Video.js playback API as much as possible, and using this function only to access Amazon IVS-specific features. The most common functions you are likely to need to access on the Amazon IVS player instance are `setQuality()` and `addEventListener()` / `removeEventListener()` .  | 
| `getIVSEvents` | Returns an object that holds Amazon IVS-specific enums. This is used for listening to Amazon IVS-specific errors. For more information, see [Events](#videojs-events) and [Errors](#videojs-errors).  | 

## currentTime
<a name="videojs-currenttime"></a>

Gets or sets the time (in seconds from the beginning).

Amazon IVS: We do not recommend setting current time for live streams.

### Signatures
<a name="videojs-currenttime-signatures"></a>

```
currentTime
currentTime(time)
```

### Parameter
<a name="videojs-currenttime-parameter"></a>


| Parameter | Type | Description | 
| --- | --- | --- | 
| `time` | number |  If `time` is absent, gets the current time. If `time` is present, sets video playback to that time.  | 

### Return Value
<a name="videojs-currenttime-return"></a>


| Type | Description | 
| --- | --- | 
| number |  The current time, in seconds from the beginning.  | 

## dispose
<a name="videojs-dispose"></a>

Deletes the player instance.

Amazon IVS: This also deletes the Amazon IVS tech backend.

### Signature
<a name="videojs-dispose-signatures"></a>

```
dispose()
```

### Parameters
<a name="videojs-dispose-parameter"></a>

None

### Return Value
<a name="videojs-dispose-return"></a>

None

## duration
<a name="videojs-duration"></a>

Returns the duration of the video, in seconds.

Amazon IVS: For live streams, this returns `Infinity`.

### Signature
<a name="videojs-duration-signatures"></a>

```
duration()
```

### Parameters
<a name="videojs-duration-parameter"></a>

None

### Return Value
<a name="videojs-duration-return"></a>


| Type | Description | 
| --- | --- | 
| number |  The duration of the stream, in seconds. For live streams, this value is `Infinity`.  | 

## getIVSEvents
<a name="videojs-getivsevents"></a>

Returns an object that holds Amazon IVS-specific enums. This is used for listening to Amazon IVS-specific errors and events. For more information, see:
+ [Events](#videojs-events) and [Errors](#videojs-errors) in this document.
+ [Amazon IVS Player SDK: Web Reference](https://aws.github.io/amazon-ivs-player-docs/1.51.0/web/) for more information about events, error types, and error sources.

### Signature
<a name="videojs-getivsevents-signatures"></a>

```
getIVSEvents()
```

### Parameters
<a name="videojs-getivsevents-parameter"></a>

None

### Return Value
<a name="videojs-getgetivsevents-return"></a>


| Type | Description | 
| --- | --- | 
| `object` |  An object with `PlayerEventType`, `PlayerState`, and `ErrorType` keys, which map to their associated enums.  | 

## getIVSPlayer
<a name="videojs-getivsplayer"></a>

Returns the underlying Amazon IVS player instance. The full Amazon IVS Player Web API is available through this instance. We recommend using the basic Video.js playback API as much as possible, and using this function only to access Amazon IVS-specific features. The most common functions you are likely to need to access on the Amazon IVS player instance are `setQuality()` and `addEventListener()` / `removeEventListener()`.

### Signature
<a name="videojs-getivsplayer-signatures"></a>

```
getIVSPlayer()
```

### Parameters
<a name="videojs-getivsplayer-parameter"></a>

None

### Return Value
<a name="videojs-getivsplayer-return"></a>


| Type | Description | 
| --- | --- | 
| `MediaPlayer` |  The created instance of the player.  | 

## load
<a name="videojs-load"></a>

Starts loading the `src()` data.

Amazon IVS: This is a no-op.

### Signature
<a name="videojs-load-signatures"></a>

```
load()
```

### Parameters
<a name="videojs-load-parameter"></a>

None

### Return Value
<a name="videojs-load-return"></a>

None

## play
<a name="videojs-play"></a>

Plays the stream that was set up via the `src` call.

Amazon IVS: If a live stream was paused, this plays the live stream from the latest frames, instead of continuing from where it was paused.

### Signature
<a name="videojs-play-signatures"></a>

```
play()
```

### Parameters
<a name="videojs-play-parameter"></a>

None

### Return Value
<a name="videojs-play-return"></a>

None

## playbackRate
<a name="videojs-playbackrate"></a>

Gets or sets the video-playback rate. 1.0 means normal speed; 0.5, half normal speed; 2.0, two times normal speed; and so on.

Amazon IVS: On a live stream, a get returns 1, and a set is ignored.

### Signatures
<a name="videojs-playbackrate-signatures"></a>

```
playbackRate
playbackRate(rate)
```

### Parameter
<a name="videojs-playbackrate-parameter"></a>


| Parameter | Type | Description | 
| --- | --- | --- | 
| `rate` | number |  The playback rate. Valid values: in the range [0.25, 2.0].  | 

### Return Value
<a name="videojs-playbackrate-return"></a>


| Type | Description | 
| --- | --- | 
| number |  The playback rate.  | 

## seekable
<a name="videojs-seekable"></a>

Returns the `TimeRanges` of the media that can be seeked to.

Amazon IVS: For live streams, calling `end(0)` on the return value (`TimeRange`) returns Infinity.

### Signature
<a name="videojs-seekable-signatures"></a>

```
seekable()
```

### Parameter
<a name="videojs-seekable-parameter"></a>

None

### Return Value
<a name="videojs-seekable-return"></a>


| Type | Description | 
| --- | --- | 
| `TimeRange` |  TimeRange of the media that is available for seeking to.  | 

# IVS Player SDK: JW Player Integration
<a name="player-jwplayer"></a>

This document describes the most important functions available in the Amazon Interactive Video Service (IVS) JW Player integration.

**Latest version of JW Player integration:** 1.51.0 ([Release Notes](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/release-notes.html#apr16-26-player-web-ll))

## Getting Started
<a name="jwplayer-getting-started"></a>

Amazon IVS support for JW Player is implemented through a Provider. Amazon IVS Provider is supported only on JW Player’s web player. The Provider is loaded through a script tag, and any streams requiring Amazon IVS Provider playback must be tagged with `type: 'ivs'` in the playlist. Amazon IVS supports JW Player version 8.18.4 and later.

### Setup
<a name="jwplayer-getting-started-setup"></a>

In these instructions, `JW_PLAYER_DIV` is the name of the `<div>` of your JW Player instance and `IVS_STREAM` is your IVS playback URL. To set up the Amazon IVS Provider and enable playback:

1. Include the following `script` tag (for the latest version of the player integration; in this case, 1.51.0):

   ```
   <script src="https://player.live-video.net/1.51.0/amazon-ivs-jw-provider.min.js"></script>
   ```

1. Use the `ivs` type to mark your IVS playlist items. Set the `cast` value in your `setup()` to `null` (since Chromecast is not supported).

   ```
   jwplayer(JW_PLAYER_DIV).setup({
      playlist: [{
         file:IVS_STREAM,
         type: 'ivs',
      }]
   });
   ```

1. If you want a reference to the underlying Amazon IVS Player to make Amazon IVS Player API calls or you want references to Amazon IVS-specific enums for callback handling, add a listener to the `'providerPlayer'` event:

   ```
   jwplayer(JW_PLAYER_DIV).on('providerPlayer', function (player) {
      // player object has 'ivsPlayer' and 'ivsEvents' properties
      // ...callback code...
   });
   ```

### Sample Code
<a name="jwplayer-getting-started-code"></a>

In this example, `JW_PLAYER_LIB` is the URL to your JW Player library script and `IVS_STREAM` is your IVS playback URL.

```
<!DOCTYPE html>
<html lang="en">
<head>
   <script src=JW_PLAYER_LIB></script>
   <script src="https://player.live-video.net/1.51.0/amazon-ivs-jw-provider.min.js"></script>
</head>
<body>
   <div id='player'></div>
   <script>
      // set default values for ivsPlayer and ivsEvents
      var ivsPlayer = {};
      var ivsEvents = {};

      // define our player setup
      const ivsConfig = {
         playlist: [{
            file: IVS_STREAM,
            type: 'ivs',
         }]
      };

      jwplayer('player')
         .setup(ivsConfig)
         .on('providerPlayer', function (player) {
            console.log('Amazon IVS Player: ', player.ivsPlayer);
            console.log('Amazon IVS Player Events: ', player.ivsEvents);

            // store the reference to the Amazon IVS Player
            ivsPlayer = player.ivsPlayer;
            // store the reference to the Amazon IVS Player Events
            ivsEvents = player.ivsEvents;
         });
   </script>
</body>
</html>
```

## Events
<a name="jwplayer-events"></a>

To listen to standard JW Player events, use the [on](https://docs.jwplayer.com/players/docs/jw8-reference#event-listening-with-the-jwp-api) function of the JW Player.

To listen to events that are specific to Amazon IVS, or to add and remove event listeners on the Amazon IVS Web player, you must listen to the `'providerPlayer'` event to get a reference to the Amazon IVS Player and then add event listening onto it. For example:

```
// store a default value for ivsPlayer
var ivsPlayer = {};

// store references to the Amazon IVS Player and Amazon IVS Events:
jwplayer(JW_PLAYER_DIV).on('providerPlayer', function (player) {
   ivsPlayer = player.ivsPlayer;
});

// set up event listening
ivsPlayer.addEventListener(event, callback);
ivsPlayer.removeEventListener(event, callback);
```

where `callback` is a callback that you define, and `event` is one of: `PlayerEventType`, `PlayerState`, or `ErrorType`. For more information about events, see the [Amazon IVS Player SDK: Web Reference](https://aws.github.io/amazon-ivs-player-docs/1.51.0/web/).

The `'providerPlayer'` event is emitted by JW Player, and the callback you register with it will receive an object with the following fields:


| Field | Description | 
| --- | --- | 
|  `ivsPlayer`  |  Returns the underlying Amazon IVS player instance. The full Amazon IVS Player Web API is available through this instance. We recommend using the basic JW Player playback API as much as possible, and using this function only to access Amazon IVS-specific features. The most common functions you are likely to need to access on the Amazon IVS player instance are `addEventListener()` and `removeEventListener()`.  | 
|  `ivsEvents`  |  Returns an object with `PlayerEventType`, `PlayerState`, and `ErrorType` fields, which map to their associated Amazon IVS-specific enums. For more information, see [Amazon IVS Player SDK: Web Reference](https://aws.github.io/amazon-ivs-player-docs/1.51.0/web/).  | 

## Errors
<a name="jwplayer-errors"></a>

For general JW Player errors, use the [on](https://docs.jwplayer.com/players/docs/jw8-reference#event-listening-with-the-jwp-api) function of the JW Player to listen to error events.

For errors specific to Amazon IVS, listen on the Amazon IVS player for its own errors:

```
// set default values for ivsPlayer and ivsEvents
var ivsPlayer = {};
var ivsEvents = {};

// store references to the Amazon IVS Player and Amazon IVS Events
jwplayer(JW_PLAYER_DIV).on('providerPlayer', function (player) {
   ivsPlayer = player.ivsPlayer;
   ivsEvents = player.ivsEvents;
});

// set up event listening:
let playerEvent = ivsEvents.PlayerEventType;
ivsPlayer.addEventListener(playerEvent.ERROR, callback);
```

The callback will receive an object with the following fields:


| Field | Description | 
| --- | --- | 
|  `type`  |  The error type. Corresponds to `ErrorType` events. For more information, see [Amazon IVS Player SDK: Web Reference](https://aws.github.io/amazon-ivs-player-docs/1.51.0/web/).  | 
|  `code`  |  The error code.  | 
|  `source`  |  Source of the error.  | 
|  `message`  |  Human readable error message.  | 

## Content Security Policy
<a name="jwplayer-content-security-policy"></a>

The Amazon IVS Provider API is configured to work on pages that use Content Security Policy (CSP). See the section on “Working with Content Security Policy” in the [IVS Player SDK: Web Guide](web-content-security-policy.md).

## Limitations
<a name="jwplayer-limitations"></a>

The Provider does not support casting. If you enabled casting in the JW Player dashboard, you can disable it by setting `cast` to `null` when calling `setup()`. This hides the casting button.