# Video and audio components (`media`)

`media` brings together frame storage, container and bitstream parsers, audio
DSP, transforms, packet formats and codec components. Use `"media"` for the
facade or component imports such as `"media/tensor_media"` and
`"media/audio/wav_mux"` for a focused pipeline. A container parser, a packetizer
and a complete codec are distinct pieces: choose the component that matches
your input and required output.

## Frame storage

`VexMediaTensor` owns a byte buffer with dimensions, a format, `ptsNs` and flags.
Presentation timestamps are **nanoseconds**. The format determines how to
interpret its dimensions:

| Format | Layout |
| --- | --- |
| `MEDIA_FORMAT_RGB24` | Packed RGB; image consumers require three channels |
| `MEDIA_FORMAT_YUV420P` | Planar Y, U, V; use `channels = 1` |
| `MEDIA_FORMAT_NV12` | Y plane plus interleaved UV; use `channels = 1` |
| `MEDIA_FORMAT_AUDIO_PCM_F32` | Interleaved float samples; width is sample-frame count, height is 1, channels is audio channel count |

`newMediaTensor` checks dimensions and allocation arithmetic, returning an empty
tensor on invalid layout or allocation failure. Check `bufferLen` and the
buffer before processing. The allocation is **not initialized**: fill its
samples before encoding, filtering or exposing it to another consumer. Chroma
planes round width and height independently for odd 4:2:0 dimensions.

The tensor releases its buffer on drop. `freeMediaTensor` releases it early
and resets the descriptor; borrowed buffers cannot survive either release.
`MEDIA_FLAG_KEYFRAME`, `MEDIA_FLAG_INTERFRAME`, `MEDIA_FLAG_AUDIO` and
`MEDIA_FLAG_HARDWARE` describe payloads. An empty error/EOS product can carry
`MEDIA_FLAG_ERROR`; it is not a decoded frame.

## Create PCM and a WAV header

This complete program produces a short stereo sine wave in a caller-owned
300-byte WAV buffer. It performs no file I/O.

```vex [media-wav.vx]
import { newMediaTensor, MEDIA_FORMAT_AUDIO_PCM_F32 } from "media/tensor_media";
import { generateSineWaveFloat, encodeFloatToPcm16, createWavHeader } from "media/audio/wav_mux";

fn main() {
    let! samples = newMediaTensor(64, 1, 2, MEDIA_FORMAT_AUDIO_PCM_F32);
    if samples.bufferLen != 512 { $panic("audio allocation failed"); }
    generateSineWaveFloat(&samples!, 48000.0 as f32, 440.0 as f32);

    let! bytes: [u8; 300] = [0; 300];
    let header = RawBuf.of(&bytes[0] as Ptr<Opaque>);
    let payload = RawBuf.of(&bytes[44] as Ptr<Opaque>);
    let written = encodeFloatToPcm16(&samples, payload, 256);
    if written != 256 { $panic("PCM encoding failed"); }
    if createWavHeader(header, 44, 48000, 2, 16, 256) != 44 {
        $panic("WAV header failed");
    }
    if bytes[0] != 82 || bytes[8] != 87 { $panic("wrong WAV signature"); }
    $println("media WAV: PASS");
}
```

`createWavHeader` writes a 44-byte RIFF/PCM header and returns zero for invalid
parameters or insufficient header capacity. It does not append samples.
`dataSize` is the byte count of the following PCM payload and must contain
whole interleaved frames. `encodeFloatToPcm16` clamps samples to `[-1, 1]`, maps
NaN to zero and emits little-endian PCM16. Its output count excludes the header.
The raw buffers above borrow the array only for the calls shown.

## Decode lifecycle

`newMediaPipelineBuilder()` creates a configuration record. Set `maxBufferMb`
before `openMedia(&builder, input, length)` to bound accepted encoded input.
The `Media` value exposes `width`, `height`, `durationMs` and its `pipeline`.
Inspect `pipeline.isOpen` before reading. The pipeline borrows the encoded input;
retain those bytes until `closeMedia(&media!)` and the last read are complete.

The integrated video path consumes the supported MP4/AVC sample-table subset
with parsed SPS/PPS and H.264 samples. `decodeNextFrame(&media!)` returns an
owning tensor. `pipeline.isEos`, empty storage and the error flag describe
termination/error products; do not process them as full frames. This interface
does not provide a distinct typed error for every open/decode failure.

Hardware acceleration, HDR and audio-sync fields in `MediaPipelineBuilder`
are configuration preferences; `openMedia` currently connects only the input
budget to the decode pipeline. Use explicit transform/sync components where
their contracts fit, rather than expecting those preferences to install a
backend automatically.

## Compose lower-level components

| Work | Component surface |
| --- | --- |
| Containers | MP4 sample tables, Matroska/WebM parsing, GIF/WebP/APNG metadata; MP4/MKV muxing components |
| Bitstreams | Bounded readers/writers, H.264 NAL/SPS/PPS/slice helpers, entropy and prediction primitives |
| Audio | ADTS/Opus header parsing, MP3 components, resampling, EBU R128 measurement, PCM/WAV output |
| Image output | `encodeBmp` for three-channel packed RGB; returns a byte count or zero |
| Pixel processing | Colour-space conversion, scaling, deinterlacing, frame-rate conversion, LUT3D and tone-mapping helpers |
| Timing | A/V synchronization state, seek control, circular buffering and presentation timestamps |
| Transport formats | RTP, RTSP, HLS/DASH, MPEG-TS and RTMP/FLV parsing/building components |
| Image interoperation | `vipsToMediaTensor`, `mediaTensorToVips` copy packed RGB into independent storage |

These components expose particular syntax/layout operations. An AAC ADTS or
Opus header parser does not synthesize compliant PCM audio: the AAC raw-data
block/codebook path and Opus packet synthesis are outside the complete decoder
surface. Likewise, codec-specific H.265/VP9/AV1 primitives are not a declaration
that the high-level `Media` reader decodes every such stream.

The `transcodeMp4ToMkv`, `transcodeMkvToMp4`, `transcodeMp3ToAac` and
`transcodeAacToOpus` entry points return zero output; there is no complete
cross-format conversion route behind them. VideoToolbox, VA-API and NVDEC
configuration records do not open or submit to a hardware decoder. Select a
working external codec/backend when your application needs those end-to-end
operations, and adapt its output to the explicit tensor layout.

## Buffer and pipeline boundaries

Supply actual readable/writable extents with every `RawBuf` and length pair.
A caller-provided output budget does not allocate storage. Do not overlap
encoded input, decoded output and scratch storage unless the specific function
documents in-place operation. Validate dimensions before allocating images
derived from untrusted metadata and impose stream-level frame/byte budgets.

Container timestamps, RTP timestamps and `ptsNs` have different units.
Convert through the stream's time base instead of treating all integer
timestamps as milliseconds. [WebRTC](webrtc.md) covers RTP clocks and encoded
media delivery; [image processing](vips.md) covers packed image operations.
