# Video

`go.hasen.dev/shirei/media` decodes video and audio and presents each frame as a
Shirei image inside the normal compositor pass. UI widgets, translucent control
bars, and popups drawn after `player.View` hover cleanly above playing video.

Reference example: [`examples/video_player`](https://github.com/hasenj/go-shirei/tree/master/examples/video_player).

## Setup and frame usage

Open before `app.Run` (or on demand from an action), clean up with `Close`, and
render inside an `Extrinsic` container:

```go
p, err := media.Open(path)
if err != nil {
	return err
}
p.SetLoop(true)
g.AddExitCleanup(p.Close)
```

In the frame function:

```go
Container(Attrs(Viewport, Background(0, 0, 3, 1), Clip), func() {
	box := GetAvailableSize()

	// Extrinsic lets the video shrink cleanly when the window resizes.
	Container(Attrs(Expand, Grow(1), Extrinsic, Center), func() {
		player.View(box)
	})

	// Translucent overlay controls drawn in the same compositor pass.
	if box[0] > 0 && box[1] > 0 {
		Container(Attrs(Float(0, 0), FixSize(box[0], box[1]), Pad(14), NoAnimate, ClickThrough), func() {
			Container(Attrs(Grow(1), ClickThrough), func() {})
			Container(Attrs(Row, CrossMid, Gap(10), Expand, Pad2(8, 12), Background(220, 12, 6, 0.68), Corners(10), NoClickThrough), func() {
				// play/pause button, seek slider, duration label, mute/volume
			})
		})
	}
})
```

### Layout rules for video

- Always wrap `player.View(box)` in an `Extrinsic` container so it fits the
  parent's budget instead of expanding the parent to the video's pixel size.
- For hovering controls, place a `Float(0, 0)` container sized to `FixSize(box[0], box[1])`
  with `ClickThrough`, and put `NoClickThrough` on the control bar itself.
- Keep play/pause buttons fixed-width (icon buttons) so toggling play/pause does
  not shift the seek bar.
- For scrubbing: pause on slider press (`st.Active && !scrubbing`), throttle
  live seeks (~80 ms), and seek + restore play state on release (`!st.Active && scrubbing`).

## API (`go.hasen.dev/shirei/media`)

| API | behavior |
|---|---|
| `Open(path) (*Player, error)` | opens local path (all platforms) or `http://` / `https://` / `file://` URL (macOS, iOS, Android; Android also accepts `content://`) |
| `Play()` / `Pause()` | starts, resumes, or pauses playback (`Play` restarts from `0` after EOF) |
| `Seek(sec float64)` | seeks to `sec` seconds (playing or paused) |
| `SetLoop(bool)` | loops at end of stream when true |
| `SetMuted(bool)` / `Muted() bool` | mute toggle |
| `SetVolume(float32)` / `Volume() float32` | volume in `[0, 1]` |
| `Playing() bool` / `Ended() bool` | playback state |
| `Position() time.Duration` | current playback position |
| `Duration() time.Duration` | total duration (`0` until metadata is ready) |
| `Size() (int, int)` | pixel dimensions (`0, 0` before first frame) |
| `ImageId() shirei.ImageId` | current frame handle (`0` before first frame) for custom placement via `ImageViewAt` |
| `View(maxSize Vec2)` | places current frame fitted to `maxSize` preserving aspect ratio (placeholder until ready) |
| `Err() error` | async decode/playback error, if any |
| `Close()` | stops playback, releases native resources and Shirei image entry; idempotent |

### Threading

- All control, query, and lifecycle methods (`Play`, `Pause`, `Seek`,
  `Position`, `View`, `Close`, etc.) are thread-safe and do not require the
  frame lock.
- Opening or closing a player can still take a few milliseconds of native I/O
  or teardown, so when switching videos at runtime open the new player in a
  goroutine, swap `player` via `shirei.Post`, and close the previous player in a
  background goroutine (`go old.Close()`) to keep frames responsive.
- Decoding starts lazily on the first `View`, `ImageId`, `Play`, or `Seek` call.
- `AVPlayer` (macOS/iOS) loads metadata asynchronously: `Duration()` and `Size()`
  may be `0` for the first few frames until ready.

## Codec and container support

Default builds require zero bundled LGPL/GPL libraries and zero cgo on desktop.

### Containers

| Container | macOS | Windows | Linux | iOS | Android |
|---|---|---|---|---|---|
| **MP4 / MOV** | ✅ OS + BSD | ✅ OS + BSD | ✅ GSt / BSD / ffmpeg | ✅ OS + BSD | ✅ OS |
| **WebM** | ✅ BSD | ✅ BSD | ✅ GSt / BSD / ffmpeg | ✅ BSD | ✅ OS |
| **MKV** | ✅ BSD *(AV1/VPx)* | ✅ BSD *(AV1/VPx)* | ✅ GSt / BSD / ffmpeg | ✅ BSD *(AV1/VPx)* | ⚠️ Partial *(OS)* |
| **HLS (`.m3u8`)** | ✅ OS | ❌ | ❌ | ✅ OS | ✅ OS |

### Video codecs

| Video Codec | macOS | Windows | Linux | iOS | Android |
|---|---|---|---|---|---|
| **H.264 (AVC)** | ✅ OS | ✅ OS | ✅ GSt / ffmpeg *(1)* | ✅ OS | ✅ OS |
| **AV1** | ✅ BSD *(+ OS on M3+)* | ✅ BSD *(+ Store ext)* | ✅ GSt / BSD / ffmpeg | ✅ BSD *(+ OS on A17 Pro+)* | ✅ OS *(Android 10+)* |
| **VP9** | ✅ BSD | ✅ BSD *(+ Store ext)* | ✅ GSt / BSD / ffmpeg | ✅ BSD | ✅ OS |
| **VP8** | ✅ BSD | ✅ BSD | ✅ GSt / BSD / ffmpeg | ✅ BSD | ✅ OS |
| **HEVC (H.265)** | ✅ OS | ⚠️ Paid Store ext | ⚠️ GSt / ffmpeg *(1)* | ✅ OS | ✅ OS *(API 21+)* |

### Audio codecs

| Audio Codec | macOS | Windows | Linux | iOS | Android |
|---|---|---|---|---|---|
| **AAC** | ✅ OS | ✅ OS | ✅ GSt / ffmpeg *(1)* | ✅ OS | ✅ OS |
| **Opus** | ✅ BSD | ✅ BSD | ✅ GSt / BSD / ffmpeg | ✅ BSD *(+ OS in MP4)* | ✅ OS |
| **Vorbis** | ✅ BSD | ✅ BSD | ✅ GSt / BSD / ffmpeg | ✅ BSD | ✅ OS |
| **MP3** | ✅ OS | ✅ OS | ✅ GSt / ffmpeg | ✅ OS | ✅ OS |
| **FLAC** | ✅ OS *(in MP4/MOV)* | ✅ OS | ✅ GSt / ffmpeg | ✅ OS *(in MP4)* | ✅ OS |

- **Universal 5-platform safe formats:** **MP4 (H.264 + AAC)** and **WebM or MP4 (VP9 or AV1 + Opus)**.
- **OS** — AVFoundation (macOS/iOS), Media Foundation (Windows), `MediaPlayer` (Android).
- **BSD** — Pure-Go WebM/MKV & MP4 demuxer + BSD-2/3 codecs (`libdav1d`, `libvpx`, `libopus`, `libvorbis`): dynamically loaded via `purego` on desktop, and auto-linked statically on iOS when built with `shirei/media/scripts/build_ios_codecs.sh`.
- **GSt** — Linux system GStreamer 1.0 via `purego` (uses VA-API / OpenH264 / distro plugins).
- **(1)** On Linux distros that strip patented codecs (Fedora, openSUSE without RPM Fusion/Packman), H.264/HEVC/AAC require distro codec packages (or `openh264`), while WebM/MP4 + AV1/VP9/VP8 + Opus/Vorbis work everywhere with the BSD libs.
- **Web (Wasm):** Returns `media.ErrUnsupported`.

## Platform details & overrides

- **macOS (`CGO_ENABLED=0`):** AVFoundation (`purego`) imports each frame's `IOSurface` directly into Metal (`ExternalIOSurfaceBGRA`, CPU RGBA fallback when `SHIREI_GPU=0`), routing WebM/MKV and AV1/VP9/VP8/Opus/Vorbis to the BSD fallback (`purego`).
- **iOS (`CGO_ENABLED=1`):** AVFoundation (ObjC/cgo bridge) imports `IOSurface` into Metal and pauses active players automatically on backgrounding, audio interruptions, and headphone disconnect. To enable BSD codecs on iOS (~2.4 MB total static `.a`s), run `shirei/media/scripts/build_ios_codecs.sh` once; `shirei_mobilerun` links them automatically without build tags.
- **Android (`CGO_ENABLED=1`):** `MediaPlayer` + `SurfaceTexture` (JNI/cgo bridge) sampled via `GL_TEXTURE_EXTERNAL_OES`, managing `AudioManager` focus and pausing on `APP_CMD_PAUSE`/`APP_CMD_STOP`.
- **Windows (`CGO_ENABLED=0`):** `IMFMediaEngine` decodes into a shared D3D11 texture (`ExternalD3D11Texture`) with BSD fallback (`purego`). Optional `-tags libav` requires `CGO_ENABLED=1`.
- **Linux (`CGO_ENABLED=0` by default):** Backend order: `libav` (opt-in `-tags libav`, requires `CGO_ENABLED=1`) → `gstreamer` (`purego`) → `permissive` (BSD codecs via `purego`) → `ffmpeg` CLI (`CGO_ENABLED=0`).
- **Env vars & tags:**
  - `SHIREI_MEDIA`: force backend (`avfoundation`/`permissive` on Apple; `mf`/`libav`/`permissive` on Windows; `libav`/`gstreamer`/`permissive`/`ffmpeg` on Linux).
  - `SHIREI_CODEC_DIR`: search directory for desktop `libdav1d`/`libvpx`/`libopus`/`libvorbis` shared libraries (also searched next to the executable, macOS `../Frameworks`, Homebrew, and system library paths).
  - `SHIREI_IOS_CODECS_DIR`: override directory for iOS static `.a` codec archives.
  - `-tags libav`: opt-in LGPL cgo backend on Linux & Windows (VA-API dmabuf zero-copy on Linux Wayland).

## External GPU textures (low-level)

Custom producers can hand GPU frames directly to the compositor from any
goroutine (the image registry uses its own internal lock; call
`shirei.RequestNextFrame()` after updating a frame):

- `shirei.SupportsExternalKind(kind)` — check backend support (`ExternalIOSurfaceBGRA`, `ExternalD3D11Texture`, `ExternalNV12`, `ExternalDMABuf`, `ExternalAndroidSurfaceTexture`).
- `shirei.UseExternalImage(key, frame)` — register or update an external frame (replaces previous frame and invokes its `Release` callback outside the lock).
- `shirei.ReleaseImage(key)` — drop the image entry and free GPU resources.

Reference: [`demos/gputexture`](https://github.com/hasenj/go-shirei/tree/master/demos/gputexture).
