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

# EncodedVideoChunk

> Represents a chunk of encoded video data (keyframe or delta frame)

# EncodedVideoChunk

The `EncodedVideoChunk` class represents a single chunk of encoded video data. Each chunk is either a **keyframe** (can be decoded independently) or a **delta frame** (requires previous frames to decode).

<Info>
  This class follows the [W3C WebCodecs EncodedVideoChunk specification](https://www.w3.org/TR/webcodecs/#encodedvideochunk-interface).
</Info>

## Quick Example

```typescript theme={null}
import { EncodedVideoChunk } from 'node-webcodecs';

// Create from encoded H.264 data
const chunk = new EncodedVideoChunk({
  type: 'key',           // 'key' for keyframe, 'delta' for P/B frames
  timestamp: 0,          // Presentation time in microseconds
  duration: 33333,       // Frame duration in microseconds (30fps = ~33333μs)
  data: encodedH264Data  // Uint8Array or ArrayBuffer
});

// Access properties
console.log(chunk.type);       // 'key'
console.log(chunk.timestamp);  // 0
console.log(chunk.byteLength); // Size of encoded data

// Copy data to another buffer
const buffer = new Uint8Array(chunk.byteLength);
chunk.copyTo(buffer);
```

***

## Constructor

Creates a new `EncodedVideoChunk` from initialization data.

```typescript theme={null}
new EncodedVideoChunk(init: EncodedVideoChunkInit)
```

<ParamField body="init" type="EncodedVideoChunkInit" required>
  Configuration object for the encoded chunk.

  <Expandable title="EncodedVideoChunkInit properties">
    <ParamField body="type" type="'key' | 'delta'" required>
      The frame type. Use `'key'` for keyframes (I-frames) that can be decoded independently,
      or `'delta'` for frames that depend on previous frames (P/B-frames).
    </ParamField>

    <ParamField body="timestamp" type="number" required>
      Presentation timestamp in **microseconds**. This determines when the frame should be displayed.
    </ParamField>

    <ParamField body="duration" type="number">
      Duration of the frame in **microseconds**. For 30fps video, this is typically `33333` (1/30 second).
    </ParamField>

    <ParamField body="data" type="BufferSource" required>
      The encoded video data as an `ArrayBuffer` or `TypedArray` (e.g., `Uint8Array`).
      The data is copied internally, so you can reuse the source buffer.
    </ParamField>
  </Expandable>
</ParamField>

<Warning>
  The `type` must be exactly `'key'` or `'delta'`. Any other value will throw a `TypeError`.
</Warning>

***

## Properties

All properties are **readonly** after construction.

<ResponseField name="type" type="'key' | 'delta'" required>
  The chunk type indicating whether this is a keyframe or delta frame.

  * `'key'` - Keyframe (I-frame) that can be decoded without any other frames
  * `'delta'` - Delta frame (P/B-frame) that requires previous frames
</ResponseField>

<ResponseField name="timestamp" type="number" required>
  Presentation timestamp in microseconds. Determines when this frame should be displayed
  relative to the start of the video.
</ResponseField>

<ResponseField name="duration" type="number | null" required>
  Duration of this frame in microseconds, or `null` if not specified during construction.
</ResponseField>

<ResponseField name="byteLength" type="number" required>
  Size of the encoded data in bytes. Use this to allocate a buffer for `copyTo()`.
</ResponseField>

***

## Methods

### copyTo()

Copies the encoded video data to a destination buffer.

```typescript theme={null}
chunk.copyTo(destination: BufferSource): void
```

<ParamField body="destination" type="BufferSource" required>
  An `ArrayBuffer` or `TypedArray` to copy the data into. Must have at least `byteLength` bytes available.
</ParamField>

**Throws:** `TypeError` if the destination buffer is smaller than `byteLength`.

<Accordion title="Example: Copying chunk data">
  ```typescript theme={null}
  const chunk = new EncodedVideoChunk({
    type: 'key',
    timestamp: 0,
    data: someEncodedData
  });

  // Allocate buffer with exact size needed
  const buffer = new Uint8Array(chunk.byteLength);
  chunk.copyTo(buffer);

  // Now buffer contains a copy of the encoded data
  console.log(`Copied ${buffer.length} bytes`);
  ```
</Accordion>

***

## Type Definitions

### EncodedVideoChunkType

```typescript theme={null}
type EncodedVideoChunkType = 'key' | 'delta';
```

| Value     | Description                                         |
| --------- | --------------------------------------------------- |
| `'key'`   | Keyframe (I-frame) - can be decoded independently   |
| `'delta'` | Delta frame (P/B-frame) - requires reference frames |

### EncodedVideoChunkInit

```typescript theme={null}
interface EncodedVideoChunkInit {
  type: EncodedVideoChunkType;  // Required: 'key' or 'delta'
  timestamp: number;            // Required: microseconds
  duration?: number;            // Optional: microseconds
  data: BufferSource;           // Required: encoded data
}
```

***

## Usage with VideoEncoder

`EncodedVideoChunk` objects are typically created by `VideoEncoder` and passed to your output callback:

```typescript theme={null}
import { VideoEncoder, VideoFrame } from 'node-webcodecs';

const encoder = new VideoEncoder({
  output: (chunk, metadata) => {
    // chunk is an EncodedVideoChunk
    console.log(`Got ${chunk.type} frame at ${chunk.timestamp}μs`);
    console.log(`Size: ${chunk.byteLength} bytes`);

    // Copy to your own buffer for storage/transmission
    const data = new Uint8Array(chunk.byteLength);
    chunk.copyTo(data);

    // First keyframe includes decoder config in metadata
    if (metadata?.decoderConfig) {
      console.log('Decoder config:', metadata.decoderConfig);
    }
  },
  error: (e) => console.error('Encoding error:', e)
});

encoder.configure({
  codec: 'avc1.42001f',  // H.264 Baseline
  width: 1920,
  height: 1080,
  bitrate: 5_000_000
});
```

## Usage with VideoDecoder

Pass `EncodedVideoChunk` objects to `VideoDecoder.decode()`:

```typescript theme={null}
import { VideoDecoder, EncodedVideoChunk } from 'node-webcodecs';

const decoder = new VideoDecoder({
  output: (frame) => {
    console.log(`Decoded frame: ${frame.codedWidth}x${frame.codedHeight}`);
    frame.close();  // Don't forget to close frames!
  },
  error: (e) => console.error('Decoding error:', e)
});

decoder.configure({
  codec: 'avc1.42001f',
  codedWidth: 1920,
  codedHeight: 1080
});

// Decode a chunk
const chunk = new EncodedVideoChunk({
  type: 'key',
  timestamp: 0,
  data: h264KeyframeData
});

decoder.decode(chunk);
await decoder.flush();
```

***

## See Also

<CardGroup cols={2}>
  <Card title="EncodedAudioChunk" icon="music" href="/api-reference/EncodedAudioChunk">
    The audio equivalent for encoded audio data
  </Card>

  <Card title="VideoEncoder" icon="video" href="/api-reference/VideoEncoder">
    Encodes VideoFrames into EncodedVideoChunks
  </Card>

  <Card title="VideoDecoder" icon="film" href="/api-reference/VideoDecoder">
    Decodes EncodedVideoChunks into VideoFrames
  </Card>

  <Card title="VideoFrame" icon="image" href="/api-reference/VideoFrame">
    Raw video frame data
  </Card>
</CardGroup>
