> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tenbyte.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Player SDK for Embedded Video Control

The Vidinfra Player SDK is a lightweight, type safe JavaScript library for controlling embedded video players inside iframes.

It uses the **`postMessage`** API for secure, real time communication, making custom player integration simple and efficient.

## Key Features

* **Unified API**: One class manages both controlling existing iframes and embedding new players.
* **Type-safe**: Full TypeScript support with comprehensive type definitions for a reliable development - experience.
* **Framework-agnostic**: Works seamlessly with any JavaScript framework or plain JavaScript.
* **Secure**: Built-in origin validation for postMessage communication to ensure safe interactions.
* **Event-driven**: Listen to real-time player events such as play, pause, and time updates.
* **Lightweight**: The SDK is approximately 15KB when minified, making it efficient and easy to use.

## Installation

### NPM Installation

To install the Vidinfra Player SDK via npm, run the following command:

```bash theme={null}
npm install @vidinfra/player
```

### CDN Installation

Alternatively, you can load the SDK via a CDN:

```html theme={null}
<script src="https://unpkg.com/@vidinfra/player/dist/player.global.js"></script>
```

This method allows you to use the SDK without needing to install it locally, making it easy to integrate into static or non-Node.js projects.

***

## Quick Start

The Player SDK allows you to control existing iframe players and create embedded players on the fly. Below are the basic instructions for both use cases.

### Control an Existing Iframe

If you already have an iframe on your page and want to control the video player inside it, you can easily use the **`Player`** class. With just a few lines of code, you can target an existing iframe, wait for it to be ready, and start playing the video.

```JavaScript theme={null}
import { Player } from "@vidinfra/player";

const player = new Player("iframe");

player.on("play", () => {
  console.log("Video started playing");
});

await player.whenReady();
await player.play();
```

### Creating an Embedded Player

If you want to embed a video player directly into your page, Vidinfra can automatically create and inject an iframe for you. You can configure the player with your desired settings like autoplay, volume, and aspect ratio.

```JavaScript theme={null}
import { Player } from "@vidinfra/player";

const player = new Player("vidinfra-player", {
  libraryId: default,
  videoId: default,
  playerId: default,
  autoplay: false,
  loop: false,
  muted: false,
  controls: true,
  preload: true,
  aspectRatio: "16:9"
});

player.setVolume(0.5);
```

<Note>
  To learn how to copy a video ID, check the [Quickstart Guide](/docs/vidinfra/quickstart#copy-your-video-id) in the Vidinfra section.
</Note>

***

## Usage

### Controlling an Existing Iframe

If you already have an iframe in your HTML, you can control it by passing the iframe element or a CSS selector.

#### Javascript

```Javascript theme={null}
import { Player } from "@vidinfra/player";

const player = new Player("#player-iframe");

await player.whenReady();
await player.play();
```

#### CDN

```html theme={null}
<div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;">
  <iframe
  id="vidinfra-iframe-player"
    src="https://player.vidinfra.com/{librayID}/default/{videoID}?autoplay=false&loop=false&muted=false&controls=true&preload=true"
    loading="lazy"
    style="border: none; position: absolute; top: 0; height: 100%; width: 100%;"
    allow="accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture;"
    allowfullscreen="true">
  </iframe>
</div>
```

### Creating an Embedded Player

You can dynamically create an embedded player by specifying a target element for the player:

#### Javascript

```Javascript theme={null}
import { Player } from "@vidinfra/player";

const player = new Player("vidinfra-player", {
  libraryId: default,
  videoId: default,
  playerId: default,
  autoplay: false,
  loop: false,
  muted: false,
  controls: true,
  preload: true,
  aspectRatio: "16:9"
});
```

#### CDN

```html theme={null}
<div id="vidinfra-player"></div>

<script src="https://unpkg.com/@vidinfra/player/dist/player.global.js"></script>
<script>
  const player = new Vidinfra.Player("vidinfra-player", {
    libraryId: default,
    videoId: default,
    playerId: default,
    autoplay: false,
    loop: false,
    muted: false,
    controls: true,
    preload: true,
    aspectRatio: "16:9"
  });
</script>
```

***

## API Reference

### Constructor

```Javascript theme={null}
new Player(element: HTMLIFrameElement | HTMLElement | string)
new Player(element: HTMLElement | string, options: PlayerOptions)
```

#### Parameters

* **`element`** - An iframe element, CSS selector for an iframe, or a container element for embedding
* **`options`** - Configuration options for creating an embedded player (required when creating an embed)

### PlayerOptions

The PlayerOptions defines all the customizable settings for configuring a Vidinfra player. Here, you specify key details about the video and player behavior. You can set the video’s library ID, video ID, and the player’s size, playback options, and more.

```Javascript theme={null}
interface PlayerOptions {
  // Vidinfra player (required)
  libraryId: string | number;
  videoId: string | number;
  playerId?: string | number; // Optional, defaults to 'default'

  // Display options
  width?: number | string;
  height?: number | string;
  aspectRatio?: string; // e.g., "16:9", "4:3"

  // Playback options
  autoplay?: boolean;
  loop?: boolean;
  muted?: boolean;
  controls?: boolean;
  preload?: boolean;

  // Advanced options
  loading?: "lazy" | "eager";
  allow?: string;
  className?: string;
  baseUrl?: string;
}
```

### Playback Methods

These methods control the basic playback behavior of the video. They include actions like starting, pausing, seeking, and changing playback speed.

Start video playback.

```Javascript theme={null}
play(): Promise<void>
```

Pause video playback.

```Javascript theme={null}
pause(): Promise<void> 
```

Toggle between play and pause states.

```Javascript theme={null}
togglePlay(): Promise<void>
```

Seek to a specific time in seconds.

```Javascript theme={null}
seek(time: number): Promise<void> 
```

Set playback speed (e.g., 0.5, 1.0, 2.0).

```Javascript theme={null}
setPlaybackRate(rate: number): Promise<void> 
```

Get current playback rate.

```Javascript theme={null}
getPlaybackRate(): Promise<number> 
```

Get current playback position in seconds.

```Javascript theme={null}
getCurrentTime(): Promise<number> 
```

Get total video duration in seconds.

```Javascript theme={null}
getDuration(): Promise<number> 
```

Check if video is currently paused.

```Javascript theme={null}
getPaused(): Promise<boolean> 
```

### Volume Methods

These methods manage the audio settings for the player. You can adjust the volume, mute, or check the current audio state.

Set volume level (0-1).

```Javascript theme={null}
setVolume(volume: number): Promise<void>
```

Get current volume level.

```Javascript theme={null}
getVolume(): Promise<number>
```

Mute audio.

```Javascript theme={null}
mute(): Promise<void>
```

Unmute audio.

```Javascript theme={null}
unmute(): Promise<void>
```

Set muted state.

```Javascript theme={null}
setMuted(muted: boolean): Promise<void>
```

Get current muted state.

```Javascript theme={null}
getMuted(): Promise<boolean>
```

### Display Methods

These methods manage the visual behavior of the player, including fullscreen and control visibility.

Toggle fullscreen mode.

```Javascript theme={null}
toggleFullscreen(): Promise<void> 
```

Enter fullscreen mode.

```Javascript theme={null}
requestFullscreen(): Promise<void> 
```

Exit fullscreen mode.

```Javascript theme={null}
exitFullscreen(): Promise<void> 
```

Show player controls.

```Javascript theme={null}
showControls(): Promise<void> 
```

Hide player controls.

```Javascript theme={null}
hideControls(): Promise<void> 
```

Set controls visibility.

```Javascript theme={null}
setControlsVisible(visible: boolean): Promise<void> 
```

### Watermark Methods

These methods add a watermark to your video, which can be customized with text and styling options.

Add a watermark overlay to the video.

```Javascript theme={null}
addWatermark(config: WatermarkConfig): Promise<void> 
```

WatermarkConfig:

```Javascript theme={null}
interface WatermarkConfig {
  text: string;
  color?: string;
  opacity?: number;
  fontSize?: number;
}
```

### Utility Methods

These methods help you interact with the player’s internal state and configuration.

Check if player is ready to receive commands.

```Javascript theme={null}
isReady(): boolean 
```

Returns a promise that resolves when the player is ready.

```Javascript theme={null}
whenReady(): Promise<void>
```

Get the iframe element.

```Javascript theme={null}
getIframe(): HTMLIFrameElement
```

Get the wrapper element (only available for embedded players).

```Javascript theme={null}
getWrapper(): HTMLElement | null
```

Get the iframe source URL.

```Javascript theme={null}
getSrc(): string
```

Update player options (only available for embedded players).

```Javascript theme={null}
update(options: Partial<PlayerOptions>): void
```

Clean up event listeners and remove the player.

```Javascript theme={null}
destroy(): void
```

### Event Methods

These methods allow you to listen for events like play, pause, and custom player events.

Register an event listener.

```Javascript theme={null}
on(event: string, callback: Function): this
```

Remove an event listener.

```Javascript theme={null}
off(event: string, callback?: Function): this
```

Register a one-time event listener.

```Javascript theme={null}
once(event: string, callback: Function): this 
```

### Events

The player emits the following events:

| **Event**              | **Description**                     |
| ---------------------- | ----------------------------------- |
| **`ready`**            | Player is ready to receive commands |
| **`play`**             | Playback has started                |
| **`playing`**          | Playback is playing                 |
| **`pause`**            | Playback has paused                 |
| **`ended`**            | Playback has ended                  |
| **`timeupdate`**       | Playback position changed           |
| **`volumechange`**     | Volume or muted state changed       |
| **`seeking`**          | Seeking started                     |
| **`seeked`**           | Seeking completed                   |
| **`waiting`**          | Waiting for data                    |
| **`canplay`**          | Enough data to play                 |
| **`canplaythrough`**   | Can play through without buffering  |
| **`loadedmetadata`**   | Metadata loaded                     |
| **`loadeddata`**       | Frame data loaded                   |
| **`durationchange`**   | Duration changed                    |
| **`ratechange`**       | Playback rate changed               |
| **`fullscreenchange`** | Fullscreen state changed            |
| **`error`**            | Playback error occurred             |

***

## Examples

### Basic Playback Control

```Javascript theme={null}
import { Player } from "@vidinfra/player";

const player = new Player("#player-iframe");

await player.whenReady();

document.getElementById("play-btn").addEventListener("click", () => {
  player.play();
});

document.getElementById("pause-btn").addEventListener("click", () => {
  player.pause();
});

player.on("timeupdate", (state) => {
  const currentTime = Math.floor(state.currentTime);
  const duration = Math.floor(state.duration);
  console.log(`${currentTime}s / ${duration}s`);
});
```

### Volume Control

```Javascript theme={null}
import { Player } from "@vidinfra/player";

const player = new Player("#player-iframe");

await player.whenReady();

const volumeSlider = document.getElementById("volume");
volumeSlider.addEventListener("input", (e) => {
  const volume = e.target.value / 100;
  player.setVolume(volume);
});

const muteBtn = document.getElementById("mute");
muteBtn.addEventListener("click", async () => {
  const isMuted = await player.getMuted();
  player.setMuted(!isMuted);
});
```

### Creating and Controlling an Embed

```Javascript theme={null}
import { Player } from "@vidinfra/player";

const player = new Player("vidinfra-player", {
  libraryId: default,
  videoId: default,
  playerId: default,
  autoplay: false,
  loop: false,
  muted: false,
  controls: true,
  preload: true,
  aspectRatio: "16:9"
});

player.on("ready", () => {
  console.log("Player created and ready");
});

player.on("play", () => {
  console.log("Video playing");
});

setTimeout(() => {
  player.update({ loop: true });
}, 5000);
```

### TypeScript Example

```Javascript theme={null}
import { Player, PlayerOptions, WatermarkConfig } from "@vidinfra/player";

const options: PlayerOptions = {
  libraryId: default,
  videoId: default,
  playerId: default,
  autoplay: false,
  loop: false,
  muted: false,
  controls: true,
  preload: true,
  aspectRatio: "16:9"
};

const player = new Player("vidinfra-player", options);

await player.whenReady();

const volume: number = await player.getVolume();
const duration: number = await player.getDuration();

const watermark: WatermarkConfig = {
  text: "Confidential",
  color: "#ffffff",
  opacity: 0.3,
  fontSize: 24
};

await player.addWatermark(watermark);
```

### Security

The Player automatically validates the origin of postMessage communications based on the iframe's source URL. For iframe-side implementations, you should also validate the origin of incoming messages:

```Javascript theme={null}
window.addEventListener("message", (event) => {
  const allowedOrigin = "https://trusted-parent.com";
  if (event.origin !== allowedOrigin) return;
  
  // Handle message
});
```

***

## Browser Support

* Modern browsers with ES6+ support
* Requires **`postMessage`** API
* Fullscreen API support varies by browser

## TypeScript

Full TypeScript definitions are included with the package:

```Javascript theme={null}
import { Player, PlayerOptions, WatermarkConfig, WatermarkOptions } from "@vidinfra/player";
```
