# White Rose

> The full text of the public documentation, for machine consumption. The index is at /llms.txt.

## Cliamp

### cliamp

URL: https://docs.cliamp.stream/docs/cliamp/cliamp

[![Docs on contextowl.co](https://contextowl.co/uploads/_brand/badge-docs.svg)](https://contextowl.co)

A retro terminal music player inspired by Winamp. Play local files, streams, podcasts, YouTube, YouTube Music, SoundCloud, Mixcloud, Bilibili, Spotify, NetEase Cloud Music, Xiaoyuzhou (小宇宙), Navidrome, Lyrion, Plex, Jellyfin, and Audiobookshelf. Use the spectrum visualizer, parametric EQ, and playlist manager.

**[cliamp.stream](https://cliamp.stream)** | **[docs](https://whiterose.org.contextowl.co/docs/cliamp)**

cliamp uses [Bubbletea](https://github.com/charmbracelet/bubbletea), [Lip Gloss](https://github.com/charmbracelet/lipgloss), [Beep](https://github.com/gopxl/beep), and [go-librespot](https://github.com/devgianlu/go-librespot).


https://github.com/user-attachments/assets/fbc33d20-e3ac-4a62-a991-8a2f0243c8ea

<div align="center">
  <a href="https://contextowl.co"><img src="https://contextowl.co/uploads/_brand/sponsor-dark.svg" alt="Proudly sponsored by contextowl.co" width="400"></a>
</div>

## Install

```sh
curl -fsSL https://raw.githubusercontent.com/bjarneo/cliamp/HEAD/install.sh | sh
```

**Homebrew**

```sh
brew install bjarneo/cliamp/cliamp
```

The formula installs all required runtime libraries.

**Arch Linux (AUR)**

```sh
yay -S cliamp
```

**Nix**

```sh
nix run github:bjarneo/cliamp
```

For a declarative NixOS configuration, add `github:bjarneo/cliamp` as a flake
input. Install its default package:

```nix
inputs.cliamp.url = "github:bjarneo/cliamp";

environment.systemPackages = [
  inputs.cliamp.packages.${pkgs.stdenv.hostPlatform.system}.default
];
```

**Go**

```sh
go install github.com/bjarneo/cliamp@latest
```

Install ALSA development headers before you build on Linux. See [Building from source](#building-from-source).

**Pre-built binaries**

Download from [GitHub Releases](https://github.com/bjarneo/cliamp/releases/latest).

> **macOS:** Pre-built binaries link dynamically to FLAC, Vorbis, Ogg, and mpg123
> from Homebrew. If you download from Releases or use `install.sh`, install these
> libraries first. Otherwise, you can see errors such as
> `Library not loaded: /opt/homebrew/opt/libvorbis/lib/libvorbisenc.2.dylib`:
>
> ```sh
> brew install flac libvorbis libogg mpg123
> ```
>
> `brew install bjarneo/cliamp/cliamp` installs these libraries.
>
> **Linux:** Pre-built binaries link FLAC, Vorbis, Ogg, and mpg123 statically. No
> extra codec packages are required. You can still need an ALSA bridge for your
> sound server. See [Troubleshooting](#troubleshooting).
>
> **Windows:** Download and extract `cliamp-windows-amd64.zip` from Releases. It
> includes the codec DLLs that Spotify requires. If `HOME` is not set, cliamp stores
> its config under `%APPDATA%\cliamp`.

**Optional runtime dependencies** for all platforms and install methods:

- [ffmpeg](https://ffmpeg.org/) for AAC, ALAC, Opus, and WMA playback
- [yt-dlp](https://github.com/yt-dlp/yt-dlp) for YouTube, YouTube Music, SoundCloud, Mixcloud, Bandcamp, Bilibili, and NetEase Cloud Music

On macOS, run `brew install ffmpeg yt-dlp`. On Linux, use your distribution package manager.

On Windows, install `ffmpeg` and `yt-dlp` with your package manager. Keep both on `PATH`.

**Build from source**

```sh
git clone https://github.com/bjarneo/cliamp.git && cd cliamp && go build -o cliamp .
```

## Quick Start

```sh
cliamp ~/Music                     # play a directory
cliamp *.mp3 *.flac               # play files
cliamp https://example.com/stream  # play a URL
```

Press `Ctrl+K` to see all keybindings.

**Configure remote providers** such as Navidrome, Lyrion, Plex, Jellyfin, Audiobookshelf, Spotify, Mixcloud, YouTube Music, and NetEase Cloud Music with the interactive wizard:

```sh
cliamp setup
```

The wizard guides you through each provider. It writes the required block to your config file (`~/.config/cliamp/config.toml`, or `%APPDATA%\cliamp\config.toml` on Windows when `HOME` is unset). It validates supported server connections during setup. It checks optional Mixcloud browser-session or OAuth credentials when you use them. See [docs/cli.md](https://whiterose.org.contextowl.co/docs/cli-flags#setup-wizard) for details.

See the [Mixcloud provider guide](https://whiterose.org.contextowl.co/docs/mixcloud) for discovery, account,
creator/show, genre search, local genre favorites, authentication, signed-in
playback, resume, seeking, and limitations.

## Radio

Press `R` in the player to browse and search more than 30,000 online radio stations in the [Radio Browser](https://www.radio-browser.info/) directory.

Add stations to `~/.config/cliamp/radios.toml` (or `%APPDATA%\cliamp\radios.toml` on Windows when `HOME` is unset). See [docs/configuration.md](https://whiterose.org.contextowl.co/docs/configuration#custom-radio-stations).

To host a radio station, use [cliamp-server](https://github.com/bjarneo/cliamp-server).

## Building from source

**Prerequisites:**

- [Go](https://go.dev/dl/) 1.25.5 or later
- ALSA development headers (Linux only, required by the audio backend)

**Linux (Debian/Ubuntu):**

```sh
sudo apt install libasound2-dev libflac-dev libvorbis-dev libogg-dev libmpg123-dev
```

**Linux (Fedora):**

```sh
sudo dnf install alsa-lib-devel flac-devel libvorbis-devel libogg-devel mpg123-devel
```

**Linux (Arch):**

```sh
sudo pacman -S alsa-lib flac libvorbis libogg mpg123
```

**macOS:** `brew install flac libvorbis libogg mpg123 pkg-config`

**Windows:** The core player needs no extra SDKs. It uses pure-Go audio decoding. `ffmpeg.exe` and `yt-dlp.exe` remain optional runtime dependencies for the same formats and providers as other platforms.

Spotify support uses `go-librespot`. It needs CGO and a MinGW toolchain:

1. Install [MSYS2](https://www.msys2.org/).
2. Open the **MSYS2 MinGW64** terminal, not the standard MSYS2 terminal. Install the toolchain and codec libraries:
   ```sh
   pacman -S mingw-w64-x86_64-gcc mingw-w64-x86_64-pkg-config \
     mingw-w64-x86_64-libogg mingw-w64-x86_64-libvorbis \
     mingw-w64-x86_64-flac mingw-w64-x86_64-mpg123
   ```
3. In that MinGW64 terminal, build with CGO enabled. This keeps `gcc` and `pkg-config` on `PATH`:
   ```sh
   CGO_ENABLED=1 go build -o cliamp.exe .
   ```
   Some MSYS2 `libogg` builds provide `libogg-0.dll` without `ogg_stream_iovecin` in its export table. The static `libogg.a` has this symbol. If linking fails with `undefined reference to 'ogg_stream_iovecin'`, use static linking for this library only:
   ```sh
   CGO_LDFLAGS="-Wl,-Bstatic -logg -Wl,-Bdynamic" CGO_ENABLED=1 go build -o cliamp.exe .
   ```
4. `cliamp.exe` links dynamically to codec and MinGW runtime DLLs. Keep `C:\msys64\mingw64\bin` on `PATH` at runtime, or copy each `/mingw64/bin/*.dll` that `ldd cliamp.exe` shows next to `cliamp.exe`.

**Clone and build:**

```sh
git clone https://github.com/bjarneo/cliamp.git
cd cliamp
make && make install
```

Or without Make: `go build -o cliamp .`

`make install` places the binary in `~/.local/bin/`.

**Optional runtime dependencies:**

- [ffmpeg](https://ffmpeg.org/) for AAC, ALAC, Opus, and WMA playback
- [yt-dlp](https://github.com/yt-dlp/yt-dlp) for YouTube, SoundCloud, Mixcloud, Bandcamp, Bilibili, and NetEase Cloud Music

## Docs

Full documentation is hosted at **[whiterose.org.contextowl.co/docs/cliamp](https://whiterose.org.contextowl.co/docs/cliamp)**.

## Troubleshooting

**No audio output (silence with no errors)**

On Linux systems that use PipeWire or PulseAudio, the cliamp ALSA backend needs a bridge package to route audio through the sound server:

- **PipeWire:** `pipewire-alsa`
- **PulseAudio:** `pulseaudio-alsa`

Install the package for your system:

```sh
# PipeWire (Arch)
sudo pacman -S pipewire-alsa

# PulseAudio (Arch)
sudo pacman -S pulseaudio-alsa

# Debian/Ubuntu (PipeWire)
sudo apt install pipewire-alsa
```

## Author

[x.com/iamdothash](https://x.com/iamdothash)

## Disclaimer

Use this software at your own risk. The authors are not responsible for damage or issues that result from its use.

### CLI Flags

URL: https://docs.cliamp.stream/docs/cliamp/cli-flags

Override a config option for one session without editing `~/.config/cliamp/config.toml`. Put flags before or after file and URL arguments.

## Playback

```sh
cliamp --vol -5 track.mp3             # volume in dB [-30, +6]
cliamp --shuffle ~/Music              # enable shuffle
cliamp --repeat all ~/Music           # repeat mode: off, all, one
cliamp --mono track.mp3               # downmix to mono
cliamp --no-mono track.mp3            # force stereo
cliamp --auto-play ~/Music            # start playback immediately
cliamp --playlist "Blade Runner"      # load a local TOML playlist (add --auto-play to start playback)
```

## Audio engine

```sh
cliamp --sample-rate 48000 track.mp3      # output sample rate (22050, 44100, 48000, 96000, 192000)
cliamp --buffer-ms 2000 track.mp3         # speaker buffer in ms (50-5000; useful for unstable radio)
cliamp --resample-quality 1 track.mp3     # resample quality factor (1–4)
cliamp --bit-depth 32 track.m4a           # PCM bit depth: 16 (default) or 32 (lossless)
```

## Appearance

```sh
cliamp --simplified ~/Music                  # no visualizer or playlist
cliamp --eq-preset "Bass Boost" ~/Music
cliamp --visualizer-60fps ~/Music            # smoother visualizer animation (higher CPU use)
```

`--visualizer-60fps` renders a visible visualizer at about 60 FPS during playback. `Wave`, `Scope`, and `Heartbeat` already use this rate because they draw from audio samples. The flag does not affect overlays or low-power mode.

## Diagnostics

```sh
cliamp --log-level debug                     # raise log verbosity for one session
```

cliamp writes logs to `~/.config/cliamp/cliamp.log`. Use `debug`, `info` (default), `warn`, or `error`.

## Low-power mode

```sh
cliamp --low-power track.mp3                 # reduce CPU load for this session
```

This reduces CPU load. It lowers the UI and render rate and sets the visualizer to `none`. Use it on battery power, slow terminals, or SSH sessions. Press `v` in the player to enable a visualizer again.

To make this persistent, set it in `~/.config/cliamp/config.toml`:

```toml
low_power = true
```

## Headless daemon mode

```sh
cliamp --daemon                              # no TUI, IPC only
cliamp --daemon --auto-play --playlist Lofi  # start playing on launch
cliamp -d ~/Music --auto-play                # short flag form
```

Run cliamp without a UI. It listens on the Unix socket that the TUI uses. All `cliamp <subcommand>` IPC clients work. UI-only commands (`theme`, `vis`) return an error. See [Headless Daemon Mode](https://whiterose.org.contextowl.co/docs/headless-daemon-mode) for use cases and configuration examples for Waybar, Hyprland, systemd, and cron.

## Search

Search for and play a track from the command line. This requires [yt-dlp](https://github.com/yt-dlp/yt-dlp):

```sh
cliamp search "never gonna give you up"       # search YouTube
cliamp search-sc "lofi beats"                  # search SoundCloud
```

Press `Ctrl+F` in the player for context-aware search. cliamp uses the active provider search when available. Otherwise, it searches YouTube.

## Updates

```sh
cliamp upgrade                # latest stable release
cliamp upgrade --prerelease   # latest beta or release candidate
```

Select prerelease updates for each upgrade. Normal installs, package-manager updates, and `cliamp upgrade` use stable releases only.

Maintainers publish a prerelease by tagging the release commit with a SemVer prerelease tag such as `v1.5.0-beta.1` or `v1.5.0-rc.1`. The release workflow builds binaries for all platforms and creates a GitHub prerelease. It does not update Homebrew, AUR, or the public changelog.

## General

| Flag | Short | Description |
|------|-------|-------------|
| `--help` | `-h` | Show help and exit |
| `--version` | `-v` | Print version and exit |

## Shell completion

Generate completion scripts for supported shells.

```sh
cliamp completion bash
cliamp completion zsh
cliamp completion fish
cliamp completion pwsh
```

Source the generated script directly or install it as your shell documentation describes.

## Mixing flags and files

Put flags before, after, or between positional arguments:

```sh
cliamp --shuffle track.mp3 --volume -5
cliamp track.mp3 --repeat all --mono ~/Music
```

## Flag reference

| Flag | Type | Default | Range / Values |
|------|------|---------|----------------|
| `--vol` | float | 0 | -30 to +6 dB |
| `--shuffle` | bool | false | |
| `--repeat` | string | off | off, all, one |
| `--mono` / `--no-mono` | bool | false | |
| `--auto-play` | bool | false | |
| `--simplified` | bool | false | artist/title and time strip; no visualizer or playlist |
| `--visualizer-60fps` | bool | false | render a visible visualizer at about 60 FPS |
| `--start-theme` | string | | theme name |
| `--eq-preset` | string | | preset name |
| `--sample-rate` | int | 44100 | 22050, 44100, 48000, 96000, 192000 |
| `--buffer-ms` | int | 250 | 50-5000 |
| `--resample-quality` | int | 4 | 1-4 |
| `--bit-depth` | int | 16 | 16, 32 |
| `--playlist` | string | | local TOML playlist name |
| `--log-level` | string | info | debug, info, warn, error |
| `--low-power` | bool | false | lower UI cadence; disable visualization |
| `--daemon` / `-d` | bool | false | run headless; IPC only, no TUI |

CLI flags override config file values for the current session only. cliamp does not save them.

## Setup wizard

Configure remote providers through a small TUI. Supported providers are Navidrome, Lyrion, Plex, Jellyfin, Emby, Spotify, Qobuz, Tidal, Mixcloud, NetEase, Audiobookshelf, and YouTube Music. Each provider page links to its required credentials. The wizard writes the `[provider]` block to `~/.config/cliamp/config.toml` and leaves the rest of the file unchanged. It validates supported server connections during setup. OAuth providers (Spotify, Qobuz, Tidal) authenticate later in the player. Mixcloud checks optional browser-session or OAuth credentials when you use them.

```sh
cliamp setup
```

Use `↑/↓` to navigate. Use `Enter` to confirm or submit. Use `Esc` to go back. Use `q` in the menu to quit. Passwords and tokens are masked. Running setup again for a configured provider replaces its section.

## Playlist Management

Manage local TOML playlists from the command line without opening the TUI.

```sh
cliamp playlist list                          # list playlists with track counts
cliamp playlist create "Name"                 # create an empty playlist
cliamp playlist create "Name" file1 dir/ ...  # create from files/folders (recursive, skips duplicate paths)
cliamp playlist create "Name" --ssh HOST dir/ # create from remote machine via SSH
cliamp playlist create "Name" --dir ~/Music   # reference a directory as a [[dir]] source (scanned at load)
cliamp playlist add "Name" file1 ...          # append tracks to existing playlist, skipping duplicates
cliamp playlist add "Name" --dir ~/Music      # add another directory source
cliamp playlist dirs "Name"                   # list directory sources
cliamp playlist rename "Old" "New"            # rename a playlist
cliamp playlist show "Name"                   # display tracks
cliamp playlist show "Name" --json            # machine-readable output
cliamp playlist remove "Name" --index 3       # remove track by index
cliamp playlist dedupe "Name"                 # remove duplicate paths, keeping the first
cliamp playlist sort "Name" --by album         # sort in place
cliamp playlist doctor [Name]                  # report missing local files
cliamp playlist doctor "Name" --fix            # prune missing local files
cliamp playlist export "Name" -o mix.m3u       # export as M3U
cliamp playlist export "Name" --format pls     # export as PLS to stdout
cliamp playlist import mix.m3u --name "Name"   # import local M3U/M3U8/PLS
cliamp playlist bookmark "Name" --index 3      # toggle bookmark flag
cliamp playlist bookmarks                       # list bookmarked tracks
cliamp playlist enrich "Name"                   # probe duration/album 
cliamp playlist enrich "Name" --source metadata   # probe duration/album (forces to use the file's metadata as source)
cliamp playlist delete "Name"                   # delete entire playlist
```

Sort keys: `track`, `title`, `artist`, `album`, `artist+album`, `path`.

See [playlists.md](https://whiterose.org.contextowl.co/docs/playlists) for the TOML format. See [ssh-streaming.md](https://whiterose.org.contextowl.co/docs/ssh-streaming) for remote playback.

## Recently Played

```sh
cliamp history                                # show the 50 most recent plays
cliamp history --limit 200                    # change the cap
cliamp history --json                         # machine-readable output
cliamp history clear                          # wipe ~/.config/cliamp/history.toml
```

cliamp records a play after you listen to at least 50% of a track. In the TUI,
the Local Playlists provider shows this data in the virtual "Recently Played"
entry. See [history.md](https://whiterose.org.contextowl.co/docs/recently-played).

## Spotify

```sh
cliamp spotify reset                          # clear stored Spotify credentials
```

Use `spotify reset` for persistent `rate-limited on /v1/me` warnings or stale authentication errors. Then restart cliamp and select Spotify to sign in again. See [spotify.md](https://whiterose.org.contextowl.co/docs/spotify-integration) for the setup guide.

## Remote Control (IPC)

Control a running cliamp instance from another terminal:

```sh
cliamp play / pause / toggle / stop    # playback control
cliamp next / prev                     # track navigation
cliamp status                          # current state
cliamp status --json                   # machine-readable state
cliamp volume -5                       # adjust volume (dB)
cliamp seek 30                         # seek relative to current position (seconds)
cliamp load "Playlist Name"            # load a playlist
cliamp queue /path/to/file.mp3         # queue a track
cliamp shuffle [on|off|toggle]         # toggle or set shuffle
cliamp repeat [off|all|one|cycle]      # set or cycle repeat mode
cliamp mono [on|off|toggle]            # toggle or set mono output
cliamp speed 1.5                       # set playback speed (0.25–2.0)
cliamp eq Rock                         # set EQ preset by name
cliamp eq --band 0 6.0                 # set EQ band 0 to +6 dB
cliamp device list                     # list audio output devices
cliamp device "My DAC"                 # switch audio output device
cliamp remote state                     # v2 GUI-ready runtime snapshot
cliamp remote capabilities              # v2 operation list
cliamp remote events runtime.state      # v2 event stream
```

See [remote-control.md](https://whiterose.org.contextowl.co/docs/remote-control-ipc) for the protocol specification.

### Configuration

URL: https://docs.cliamp.stream/docs/cliamp/configuration

Use the interactive wizard to configure remote providers. Supported providers are Navidrome, Lyrion, Plex, Jellyfin, Emby, Spotify, Qobuz, Tidal, Mixcloud, NetEase, Audiobookshelf, and YouTube Music:

```sh
cliamp setup
```

The wizard writes the required TOML block and leaves the rest of your config unchanged. It validates server credentials during setup when the provider supports it: Navidrome, Lyrion, Plex, Jellyfin, and Emby. OAuth providers such as Spotify, Qobuz, and Tidal sign in later in the player. Tidal uses a `link.tidal.com` device code. Mixcloud checks optional browser-session or OAuth credentials when you use them. See [cli.md](https://whiterose.org.contextowl.co/docs/cli-flags#setup-wizard) for details.

## Config directory

cliamp searches for its config directory in this order:

- `CLIAMP_CONFIG_DIR`
- `XDG_CONFIG_HOME/cliamp`
- `HOME/.config/cliamp`
- on Windows, `%APPDATA%\cliamp` when `HOME` is not set

The examples below use `~/.config/cliamp`. On Windows without `HOME`, use `%APPDATA%\cliamp` instead.

For other settings, copy and edit the example config:

```sh
mkdir -p ~/.config/cliamp
cp config.toml.example ~/.config/cliamp/config.toml
```

## Options

```toml
# Default volume in dB (range: volume_min to 6)
volume = 0

# Minimum volume floor in dB (range: -90 to 0, default: -50)
# Controls how low the volume control can go.
volume_min = -50

# Repeat mode: "off", "all", or "one"
repeat = "off"

# Start with shuffle enabled
shuffle = false

# Start with mono output (L+R downmix)
mono = false

# Initial directory for the file browser ('o' key)
initial_directory = "~/Music"

# Shift+Left/Right seek jump in seconds
seek_large_step_sec = 30

# EQ preset: "Flat", "Rock", "Pop", "Jazz", "Classical",
#             "Bass Boost", "Treble Boost", "Vocal", "Electronic", "Acoustic"
# Leave empty or "Custom" to use manual eq values below
eq_preset = "Flat"

# 10-band EQ gains in dB (range: -12 to 12)
# Bands: 70Hz, 180Hz, 320Hz, 600Hz, 1kHz, 3kHz, 6kHz, 12kHz, 14kHz, 16kHz
# Saved Custom curve; applied when eq_preset is "Custom" or empty
eq = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

# Manual EQ changes update this curve automatically. Cycling presets with e
# keeps it available, and both values are restored after restart.

# Visualizer mode (leave empty for default Bars)
# Options: Bars, BarsDot, Rain, BarsOutline, Bricks, Columns, ClassicPeak, Wave, Scatter, Flame, Retro, Pulse, Matrix, Binary, Sakura, Firework, Bubbles, Logo, Terrain, Scope, Heartbeat, Butterfly, Ascii, Firefly, Mosaic, Sand, Geyser, ClassicLED, Stereo, Mirror, None
# Mirror draws tapered Braille bars around a persistent horizontal center axis.
visualizer = "Bars"

# Visualizer volume linking (default: true)
# When true, bar height follows the current volume level (classic behavior).
# Set to false to decouple the visualizer from volume — bars stay visible
# even at very low volume levels.
vis_volume_linked = true

# Reduce CPU usage by lowering UI cadence and disabling visualization.
# This has the same effect as starting with --low-power.
low_power = false

# Simplified mode: artist/title and time strip without a visualizer or playlist.
# No visualizer or playback controls are shown.
simplified = false

# UI theme name (see available themes in ~/.config/cliamp/themes/)
theme = "Tokyo Night"

# Log level: "debug", "info", "warn", or "error" (default "info")
# Logs are written to ~/.config/cliamp/cliamp.log
log_level = "info"

```

`Stereo` shows separate left and right horizontal LED meters with held peak markers.

## Terminal Layout

cliamp adapts its playback screen to the terminal size:

| Terminal size | Layout |
| --- | --- |
| At least `80x24` | Full controls, five visualizer rows, and detailed source controls |
| At least `56x16` | Compact controls and three visualizer rows |
| At least `40x10` | Minimal playback, list, seek bar, and help layout |
| Smaller than `40x10` | Resize message only |

`simplified = true` replaces the main playback view with the current track
artist/title, time, and seek-progress strip. It hides the visualizer, playback
controls, and playlist. Provider browsing and overlays keep their list-focused
layout. Start one session with `cliamp --simplified`.

List views such as provider browsing, file selection, queues, playlists, search
results, themes, and keybindings use a content-first layout. This layout replaces
the visualizer and detailed controls with a compact now-playing summary. It leaves
more rows for navigation. The visualizer picker keeps its live preview.

## Secrets from Environment Variables

Set a string value in `config.toml` to `$VAR_NAME` or `${VAR_NAME}` to read it from an environment variable. This keeps passwords, tokens, and client secrets out of the file.

```toml
[navidrome]
url = "https://music.example.com"
user = "alice"
password = "${NAVIDROME_PASSWORD}"

[lyrion]
url = "http://nas.local:9000"
user = "alice"
password = "${LYRION_PASSWORD}"
# show_unplayable = true  # include plugin-contributed tracks and playlists

[plex]
url = "http://plex.local:32400"
token = "$PLEX_TOKEN"

[jellyfin]
url = "https://jelly.example.com"
token = "${JELLYFIN_TOKEN}"

[emby]
url = "https://emby.example.com"
token = "${EMBY_TOKEN}"

[audiobookshelf]
url = "https://abs.example.com"
token = "${AUDIOBOOKSHELF_TOKEN}"

[ytmusic]
client_id = "${YTMUSIC_CLIENT_ID}"
client_secret = "${YTMUSIC_CLIENT_SECRET}"
# Optional: resolve full playlists from list= URLs (default true). Set to false to strip playlist params.
# expand_playlist = true

[mixcloud]
access_token = "${MIXCLOUD_ACCESS_TOKEN}"
```

Rules:

- Interpolation occurs only when the **entire** value is `$NAME` or `${NAME}`. cliamp keeps mixed values such as `"p@$$word"` literally. No escaping is required.
- Variable names match `[A-Za-z_][A-Za-z0-9_]*`.
- If the variable is unset, the value is empty (the same as if you had left it blank).
- Works for any string field, including plugin config under `[plugins.<name>]`.

## Default Provider

Set the provider that cliamp opens at start:

```toml
provider = "radio"
```

Valid values: `radio` (default), `navidrome`, `lyrion`, `spotify`, `plex`, `jellyfin`, `emby`, `qobuz`, `tidal`, `soundcloud`, `mixcloud`, `netease`, `audiobookshelf`, `yt`, `youtube`, `ytmusic`.

You can also override this setting on the CLI: `cliamp --provider jellyfin`.

## SoundCloud

SoundCloud is optional. Add this section to `~/.config/cliamp/config.toml` to register the provider:

```toml
[soundcloud]
enabled = true
```

After you enable SoundCloud, use `Ctrl+F` to search. Pasted SoundCloud URLs play through yt-dlp. The empty browse view contains search-backed genre playlists: **Trending**, **Hip-Hop**, **Electronic**, **House**, **Lo-Fi**, **Indie**, and **Pop**.

> SoundCloud official chart and discover endpoints return 404 through yt-dlp. cliamp cannot show anonymous real chart data. The genre playlists use search results. Result quality varies but reflects current uploads.

### Browse a profile

Set a username to show that profile tracks, likes, and reposts in the browse view:

```toml
[soundcloud]
enabled = true
user = "yourname"
```

Three playlists appear for `soundcloud.com/yourname`: **Tracks**, **Likes**, and **Reposts**. This works for any public profile.

### Sign in via browser cookies

SoundCloud closed its OAuth program in 2014. The bring-your-own-client_id method that Spotify uses is not available. Instead, point yt-dlp to an existing browser session. It reads your SoundCloud login from the browser cookie jar:

```toml
[soundcloud]
enabled = true
user = "yourname"
cookies_from = "firefox"   # or chrome, chromium, brave, edge, opera, safari, vivaldi
```

With cookies set, yt-dlp can stream subscriber-gated tracks (SoundCloud Go+) and access private likes and playlists that your account can access. The same cookies apply to player yt-dlp calls. Playback uses your signed-in session.

Requires `yt-dlp` on `PATH`.

## Mixcloud

Mixcloud is optional. Public recent releases, popular shows, global show browsing,
the live category catalog, Latest/Popular genre charts, genre and tag search,
native show search, direct creator jumps, and playback need no account:

```toml
[mixcloud]
enabled = true
```

Add `username` for your following stream, activity, uploads, read-only show
favorites, listening history, collections, and followed-creator browsing. An
optional developer `access_token` sets `/me/` as the account identity and adds
Listen Later. `cookies_from` gives yt-dlp your signed-in browser session for
playback that requires it.

```toml
[mixcloud]
enabled = true
username = "yourname"
access_token = "${MIXCLOUD_ACCESS_TOKEN}"
cookies_from = "firefox"
styles = ["ambient", "deep-house", "jazz", "techno"]
max_items = 100
stream_creators = 20
```

The `styles` list is also the local genre-favorites list for the provider. In
the **Genres** browser, `/` filters and searches the complete tag catalog. `f`
adds or removes a style as one action and refreshes its Latest/Popular provider
rows. These favorites do not change the Mixcloud website account.

See [mixcloud.md](https://whiterose.org.contextowl.co/docs/mixcloud) for the feature matrix, provider-pane inventory,
navigation and keybindings, favorite terminology, OAuth-token setup, signed-in
playback, resume, seeking, and upstream limitations.

## NetEase Cloud Music

NetEase is optional and uses an existing browser session. Sign in at `music.163.com`, then run:

```sh
cliamp setup
```

Select **NetEase Cloud Music** and the browser that you used to sign in. The menu lists common browsers. Select the custom option only for profile-specific values. The setup wizard validates the session and writes:

```toml
[netease]
enabled = true
cookies_from = "chrome"
user_id = "your-account-user-id"
```

After you enable NetEase, the provider shows liked songs, created playlists, saved playlists, and public charts. Use `Ctrl+F` to search. Playback uses `yt-dlp` with the same browser cookie source.

## Custom Radio Stations

Add stations to `~/.config/cliamp/radios.toml`:

```toml
[[station]]
name = "Jazz FM"
url = "https://jazz.example.com/stream"

[[station]]
name = "Ambient Radio"
url = "https://ambient.example.com/stream.m3u"
```

These stations appear with the built-in cliamp radio in the Radio provider.

See [audio-quality.md](https://whiterose.org.contextowl.co/docs/audio-quality) for sample rate, buffer, bit depth, and resample quality settings.

## WSL2 (Windows Subsystem for Linux)

cliamp uses ALSA for audio on Linux. WSL2 does not expose ALSA hardware directly. WSLg provides a PulseAudio server that ALSA can use.

If you see `ALSA lib pcm.c: Unknown PCM default`, use these two steps:

**1. Install the ALSA PulseAudio plugin:**

```sh
sudo apt install libasound2-plugins
```

**2. Create `~/.asoundrc` to route ALSA through PulseAudio:**

```sh
cat > ~/.asoundrc << 'EOF'
pcm.default pulse
ctl.default pulse
EOF
```

WSLg must be active. `echo $PULSE_SERVER` should print a path. If it is empty, use Windows 11 with WSLg enabled. Run `wsl --shutdown`, then reopen the terminal.

## ffmpeg (optional)

AAC, ALAC (`.m4a`), Opus, and WMA playback require [ffmpeg](https://ffmpeg.org/):

```sh
# Arch
sudo pacman -S ffmpeg
# Debian/Ubuntu
sudo apt install ffmpeg
# macOS
brew install ffmpeg
```

MP3, WAV, FLAC, and OGG work without ffmpeg.

### Keybindings

URL: https://docs.cliamp.stream/docs/cliamp/keybindings

Press `Ctrl+K` in any mode, or `?` in the player, to view keybindings. The
keymap first shows commands for the active screen. It then shows player and
library commands.

## Playback

| Key | Action |
|---|---|
| `Space` | Play / Pause |
| `s` | Stop |
| `>` `.` | Next track |
| `<` `,` | Previous track |
| `Left` `Right` | Seek -/+5s |
| `Shift+Left` `Shift+Right` | Seek -/+30s (configurable) |
| `N` then `j` | Seek to N * 10% of the track (for example, `7j` jumps to 70%, `0j` to the start) |
| `+` `-` | Volume up/down |
| `]` `[` | Change speed by 0.25x |
| `m` | Toggle mono |
| `Ctrl+J` | Jump to time |

## Navigation

| Key | Action |
|---|---|
| `Tab` | Cycle visible controls (Playlist / EQ / Source / Speed on full and compact layouts) |
| `j` `k` / `Up` `Down` | Playlist scroll / EQ band adjust (wraps around) |
| `PageUp` `PageDown` / `Ctrl+U` `Ctrl+D` | Scroll playlist/file browser by page (outside text input) |
| `Home` `End` / `g` `G` | Go to top/end of playlist/file browser |
| `Shift+Up` `Shift+Down` | Move track up/down in playlist/queue |
| `h` `l` | EQ cursor left/right |
| `Enter` | Play selected track |
| `/` | Search playlist (navigate results with `↑` `↓` / `Ctrl+N` `Ctrl+P`; `Ctrl+U` clears the query) |
| `Ctrl+X` | Expand/collapse playlist |
| `Ctrl+Z` | Undo the last playlist removal or queue clear |
| `o` | Open file browser |
| `b` `Esc` | Back to provider |

In the `40x10` and simplified layouts, `Tab` keeps playback focus on the
playlist. This prevents accidental changes to EQ, source, and speed settings.
`Esc` still opens the separate provider-list view.

## Text Input

Playlist search, native-provider search, URL, playlist-name, keymap, and jump
fields support these editor keys:

| Key | Action |
|---|---|
| `Left` `Right` / `Home` `End` | Move cursor |
| `Backspace` `Delete` | Delete before/at cursor |
| `Ctrl+W` | Delete previous word |
| `Ctrl+U` | Clear text before cursor |


## EQ and Appearance

| Key | Action |
|---|---|
| `e` | Cycle EQ preset, including the saved Custom curve |
| `t` | Choose theme |
| `v` | Cycle visualizer |
| `Ctrl+V` | Pick visualizer from a list (live preview) |
| `V` | Full screen visualizer |
| `Ctrl+H` | Toggle album headers |

Theme and visualizer pickers support `/` filtering. While you browse, arrow
keys preview the selected option. `Enter` keeps it. `Esc` restores the option
active when the picker opened. While you type a filter, `Enter` completes it
and `Esc` clears it.

## Features

| Key | Action |
|---|---|
| `f` | Toggle bookmark ★ on the selected track. In the radio browser, favorite the selected station. |
| `n` | Toggle favorite ♥ on the selected track. Favorited tracks appear in the cross-playlist "Favorites" virtual playlist. |
| `Ctrl+F` | Search with the active provider (Spotify, Qobuz, Tidal, Navidrome, Lyrion, Jellyfin, Emby, Plex, Audiobookshelf, Mixcloud, NetEase, Local), or search YouTube. Available in playlist and provider-browser views. |
| `u` | Load URL (stream/playlist) |
| `y` | Show or close lyrics |
| `r` | Retry lyrics lookup while lyrics are open |
| `i` | Show track metadata (`↑`/`↓` scrolls) |
| `Ctrl+S` | Save track to `~/Music/cliamp` |
| `w` | Write the highlighted track to a local playlist |
| `N` | Open the active provider browser. On a selected Mixcloud show, open that creator's Uploads/Favorites. |
| `L` | Browse local playlists (with cliamp radio) |
| `R` | Open radio provider |
| `S` | Open Spotify provider |
| `P` | Open Plex provider |
| `J` | Open Jellyfin provider |
| `E` | Open Emby provider |
| `Y` | Open YouTube provider |
| `C` | Open SoundCloud provider |
| `X` | Open Mixcloud provider |
| `M` | Open NetEase provider |
| `Q` | Open Qobuz provider |
| `T` | Open Tidal provider |
| `B` | Open Audiobookshelf provider |

## Playlist and Queue

| Key | Action |
|---|---|
| `a` | Toggle the queue (play next) |
| `A` | Queue manager |
| `x` | Remove the highlighted track from the current playlist |
| `p` | Playlist manager |
| `r` | Cycle repeat mode (Off / All / One) |
| `z` | Toggle shuffle |

### Inside the playlist manager

| Key | Action |
|---|---|
| `↑` `↓` / `j` `k` | Move cursor |
| `/` | Filter (incremental); `Esc` clears |
| `Enter` / `→` | List screen: open the selected playlist. Tracks screen: play the **selected** track. |
| `p` | Tracks screen: play all from the top |
| `w` | List: save the current queue with the playlist picker. Tracks: copy marked or selected tracks to another playlist. |
| `Space` | Tracks: mark/unmark highlighted track and advance |
| `[` `]` | Tracks: move highlighted track and save the playlist |
| `s` | Tracks: sort and save, cycling `track`, `title`, `artist`, `album`, `artist+album`, `path` |
| `o` | Tracks: open file browser to add files to this playlist |
| `D` | List: open the file browser to add `[[dir]]` sources to the selected playlist. Tracks: open the directory-sources screen. |
| `a` | List: create a playlist. After naming it, the file browser opens at `~`. Use `Enter` to enter a directory, `Space` to select folders or files, `Enter` to confirm, or `Esc` to finish. Tracks: mark or unmark all visible tracks. |
| `r` | List: rename the playlist (`Recently Played` cannot be renamed) |
| `d` | List: delete playlist (confirms; `Recently Played` cannot be deleted). Tracks: remove marked tracks, or highlighted track when none are marked |
| `u` | Undo the last manager edit |
| `←` `Backspace` `h` | Tracks screen: go back to the list |
| `Esc` | Close the playlist manager or go back |

Shift-letter keys switch providers. Playlist-manager track actions use lowercase
or punctuation keys. `D` is the exception. It opens the directory-sources
screen.

#### Directory sources screen (`D` from the tracks screen)

| Key | Action |
|---|---|
| `↑` `↓` / `j` `k` | Navigate directory sources |
| `a` | Open the file browser to add a directory as a `[[dir]]` source |
| `d` then `y` | Remove the selected source. `y` confirms; any other key cancels. |
| `r` | Toggle `recursive` on the highlighted source |
| `←` `Backspace` `h` `Esc` | Back to the tracks screen |

## File browser

| Key | Action |
|---|---|
| `↑` `↓` / `j` `k` | Move cursor |
| `←` `→` / `h` `l` / `Enter` | Go back; open a directory or file |
| `/` | Filter files |
| `Space` | Select or unselect file/directory |
| `a` | Select/unselect all visible audio files |
| `R` | Replace the current queue with selected files (confirm when it is non-empty) |
| `w` | Write selected files to a local playlist |
| `D` | Add selected folders as live `[[dir]]` sources to the target playlist. If none are selected, add the selected folder or the open directory. The browser stays open. |
| `~` `.` | Jump to home / current working directory |
| `Esc` `o` | Close file browser |

When the browser adds to a playlist, selected folders become `[[dir]]` sources.
Selected audio files become explicit tracks. This mode starts when you open the
browser with `D` from the manager list, with `o` from the tracks screen, or
after you create a playlist with `a`. In this mode, `Esc` means "done". cliamp
commits pending selections before it closes the browser.

## Provider browser (`N` key)

Press `N` to open a provider. These providers use the same album, artist, and
track screen keys: Navidrome, Lyrion, Plex, Jellyfin, Emby, Audiobookshelf,
Spotify, Qobuz, Tidal, Mixcloud, and YouTube Music.

| Key | Action |
|---|---|
| `↑` `↓` / `j` `k` | Move cursor (wraps from top to bottom) |
| `←` `→` / `h` `l` | Go back; open the selected item |
| `/` | Filter the visible list. In the Mixcloud Genres list, `Enter` searches the complete server-side genre/tag catalog. |
| `f` | In the Mixcloud Genres list, favorite or unfavorite the selected genre locally. Update `[mixcloud].styles`. |
| `Enter` | Open the selected artist or album. Play the selected track and queue the rest of the visible list. |
| `R` | Replace the queue with all visible tracks (start from the top, confirm when non-empty) |
| `a` | Append all visible tracks to the queue |
| `q` | Queue the highlighted track to play next |
| `s` | Cycle album sort (album list only) |
| `S` `N` `P` `J` `E` `Y` `C` `X` `M` `Q` `T` `L` | Switch to that provider without opening the main pane. `R` replaces the queue on the track screen. |
| `Esc` `b` | Go back one level; close the browser |

The Mixcloud browser menu has **By Show**, **By Creator**, **By Creator / Show**,
and **Genres**. Genre favorites add Latest/Popular rows to the provider pane and
show-sort menu. They do not change the Mixcloud website account. The header
shows a source path such as `Navidrome / Miles Davis / Kind of Blue / Tracks`.
This keeps the current provider and open location visible. Track rows show
right-aligned durations when the provider provides them.

For Mixcloud, selecting a Show, a creator Uploads/Favorites collection, or a
genre Latest/Popular view replaces the main playlist and closes the browser. An
empty result leaves the current playlist and browser unchanged.

## Provider playlist list

The playlists pane appears when the focus is on a provider, such as Spotify,
Navidrome, or Local Playlists:

| Key | Action |
|---|---|
| `↑` `↓` / `j` `k` | Move cursor (wraps) |
| `Ctrl+U` `Ctrl+D` | Scroll by page |
| `Enter` | Load the selected playlist tracks into the queue |
| `/` | Filter the playlist list |
| `Ctrl+F` | Run the provider online or server search (Spotify, Navidrome, NetEase, and others). |
| `Ctrl+R` | Refresh the playlist list from the provider. For Mixcloud, also clear the cached `/me/` identity. |
| `p` | Open the playlist manager (Local pane only; create, rename, delete, add dirs/tracks) |
| `S` `N` `P` `J` `E` `Y` `C` `X` `M` `Q` `L` `R` | Switch to that provider |
| `Tab` | Switch focus to EQ |
| `Esc` `b` | Back to the playlist pane |

Playlist rows show `Name · N tracks · 1h 23m` when the provider returns track
counts and total duration. The header shows `Provider / Playlists`. The loaded
playlist has a `▶` prefix. Spotify groups playlists under section headers (`── library ──`, `── your playlists ──`, `── followed playlists ──`). For configured accounts, Mixcloud shows Your Mixcloud first: Stream, then Favorites. It then
shows Browse shortcuts, public collections, Discover charts, and a
Latest/Popular pair for each locally favorited genre under Music Styles. Leaving
a provider-pane Browse shortcut returns to the provider pane.

## Search results overlays

Use these keys when `Ctrl+F` opens provider search or YouTube/SoundCloud network
search and the results list is open:

| Key | Action |
|---|---|
| `↑` `↓` / `j` `k` / `Ctrl+N` `Ctrl+P` | Move cursor (single item) |
| `Ctrl+U` `Ctrl+D` | Scroll results by page |
| `Enter` | Play the selected track now |
| `a` | Append the selected track to the playlist |
| `q` | Queue the selected track to play next |
| `p` | (Spotify only) Save the selected track to a Spotify playlist |
| `Esc` `Backspace` | Back to the search input |

## Fuzzy search

Local search boxes use fuzzy matching. Query characters must appear in order but
do not need to be next to each other. Results are ranked by relevance, with the
best match first. For example, `skr` and `saku` both find a track named "Sakura".

This applies to:

- `/` playlist search
- `/` file browser filter
- `Ctrl+F` when the active provider is Local (your saved playlists)

Other `Ctrl+F` providers, including Spotify, Qobuz, Tidal, Navidrome, Lyrion,
Jellyfin, Emby, Plex, Audiobookshelf, Mixcloud, NetEase, and YouTube, send the
query to their search API. Their services control matching rules.

## General

| Key | Action |
|---|---|
| `?` / `Ctrl+K` | Show keymap |
| `q` | Quit |

### Audio Quality

URL: https://docs.cliamp.stream/docs/cliamp/audio-quality

Set the output sample rate, speaker buffer size, resample quality, and bit depth in `~/.config/cliamp/config.toml`. The `OUT` status line below the EQ shows the active settings.

## Configuration

Add these settings to your config file as needed:

```toml
# Output sample rate in Hz (22050, 44100, 48000, 96000, 192000)
sample_rate = 44100

# Speaker buffer in milliseconds (50-5000)
buffer_ms = 250

# Resample quality (1-4, where 4 is best)
resample_quality = 4

# PCM bit depth for FFmpeg-decoded formats: 16 (default) or 32 (lossless)
bit_depth = 16
```

All settings are optional. The defaults are shown above.

## What they do

| Setting            | Effect                                                                 |
|--------------------|------------------------------------------------------------------------|
| `sample_rate`      | Output rate sent to the sound card. 48000 matches most modern DACs. |
| `buffer_ms`        | Lower values reduce latency. Higher values reduce glitches. Try 200 if audio pops, or 2000 for unstable radio streams. |
| `resample_quality` | Sinc interpolation quality when a file rate differs from the output rate. 4 gives the best quality; 1 is fastest. |
| `bit_depth`        | PCM precision for FFmpeg-decoded formats (m4a, aac, alac, opus, wma, webm). 32 uses float PCM and preserves up to 24-bit audio without truncation. Native formats (mp3, flac, wav, ogg) always decode at full precision. This setting does not affect them. |

## Quick recipes

**Lossless / high-resolution setup** (good DAC, high CPU capacity):

```toml
sample_rate = 96000
buffer_ms = 250
resample_quality = 4
bit_depth = 32
```

**Low-latency / low-capacity hardware**:

```toml
sample_rate = 44100
buffer_ms = 200
resample_quality = 1
```

**Unstable radio connection**:

```toml
buffer_ms = 2000
```

This can add up to two seconds of playback latency. It gives the audio device more time to handle short network interruptions.

Live HTTP radio also uses an automatic decoded-audio jitter buffer. If the
network has no data, cliamp outputs silence without blocking the UI. It waits
for a short refill before it resumes. This avoids rapid sound breaks. A source
that stays slower than its audio bitrate can still have silent gaps. cliamp
cannot reconstruct missing audio.

Changes take effect when you next start cliamp.

### Media Controls

URL: https://docs.cliamp.stream/docs/cliamp/media-controls

cliamp integrates with operating system media controls. Desktop environments,
hardware media keys, and command line tools can control playback, read track
metadata, and adjust volume without using the TUI.

## Platform Support

| Platform | Backend | Requirements |
|---|---|---|
| Linux | [MPRIS2](https://specifications.freedesktop.org/mpris-spec/latest/) over D-Bus | Running D-Bus session bus (provided by most desktop environments and Wayland compositors) |
| macOS | MPNowPlayingInfoCenter / MPRemoteCommandCenter | None (built-in frameworks) |
| Other | No-op stub | None |

## Linux (MPRIS2)

### Bus Name

cliamp registers this name:

```
org.mpris.MediaPlayer2.cliamp
```

Only one instance can hold this name. If a second cliamp process starts, its
MPRIS registration fails without an error message. That instance runs without
D-Bus integration.

### Playback Control

The `org.mpris.MediaPlayer2.Player` interface supports all standard transport commands:

| playerctl command | Effect |
|---|---|
| `playerctl play-pause` | Toggle play / pause |
| `playerctl play` | Resume playback |
| `playerctl pause` | Pause playback |
| `playerctl stop` | Stop playback |
| `playerctl next` | Skip to the next track |
| `playerctl previous` | Go to the previous track (or restart if more than 3 seconds in) |

### Seeking

You can seek by an absolute or relative value:

```sh
playerctl position 30          # seek to 30 seconds
playerctl position 5+          # seek forward 5 seconds
playerctl position 5-          # seek backward 5 seconds
```

Desktop widgets with a progress bar receive `Seeked` signals and stay in sync.

### Volume

Volume is available as a linear value from 0.0 to 1.0. Internally, cliamp uses
a decibel scale from -30 dB to +6 dB. It converts the values automatically.

```sh
playerctl volume               # print current volume (0.0 to 1.0)
playerctl volume 0.5           # set volume to 50%
```

Setting volume through `playerctl` updates the player immediately. When you
change volume with the TUI `+` and `-` keys, D-Bus clients receive the new value
on the next tick.

### Metadata

cliamp publishes track metadata with standard MPRIS keys:

| Key | Description |
|---|---|
| `mpris:trackid` | D-Bus object path for the current track |
| `xesam:title` | Track title |
| `xesam:artist` | Artist name as a list with one entry |
| `xesam:album` | Album name, when available |
| `xesam:url` | File path or stream URL |
| `mpris:artUrl` | Embedded album art from local files, when available |
| `mpris:length` | Duration in microseconds |

Query metadata:

```sh
playerctl metadata              # all keys
playerctl metadata artist       # just the artist
playerctl metadata title        # just the title
```

For live radio streams with ICY metadata, artist and title update when the
station sends new track information.

### Status

```sh
playerctl status                # prints Playing, Paused, or Stopped
```

### Hyprland bindings

Hyprland does not bind `XF86Audio*` keys by default. Add the following to the
Hyprland config, usually `~/.config/hypr/bindings.conf` or `hyprland.conf`, to
bind hardware media keys to cliamp through `playerctl`:

```conf
bindl = , XF86AudioPlay,  exec, playerctl --player=cliamp play-pause
bindl = , XF86AudioPause, exec, playerctl --player=cliamp play-pause
bindl = , XF86AudioNext,  exec, playerctl --player=cliamp next
bindl = , XF86AudioPrev,  exec, playerctl --player=cliamp previous
```

Notes:

- `bindl` runs even when the session is locked. Keys continue to work under `hyprlock`.
- `--player=cliamp` limits the command to cliamp. Remove the flag to control the most recently active MPRIS player. Use this when cliamp shares the session with browsers or Spotify.
- Run `hyprctl reload` after you edit the configuration.
- Install `playerctl`, for example with `pacman -S playerctl` or `apt install playerctl`.

## macOS

On macOS, cliamp publishes now-playing information to the system MPNowPlayingInfoCenter. This enables:

- Control Centre and Lock Screen media controls
- Touch Bar playback buttons
- Hardware media keys (play/pause, next, previous)
- Bluetooth headphone buttons

Local files with embedded cover art publish that art to Control Centre and Lock
Screen media controls. cliamp caches art by content in
`~/.local/share/cliamp/album-art/`. It removes cached art as needed to keep the
cache near 100 MB.

The macOS media-control runtime pins the main goroutine to thread 0 with
`runtime.LockOSThread`. This lets the Cocoa run loop process events. Bubbletea
runs on a background goroutine.

## Architecture

The application playback command and notifier boundary is in
`internal/playback`. The `mediactl` package translates platform APIs to and from
this boundary. It owns the platform-specific interactive runtime helper.

Platform-specific `Service` implementations:

- `internal/playback/*`: application playback commands and outbound notifier state.
- `mediactl/service_linux.go`: connects to the session bus, claims the MPRIS bus name, translates D-Bus calls to playback commands, and publishes state through MPRIS properties.
- `mediactl/service_darwin.go`: starts NSApplication as an accessory process, registers MPRemoteCommandCenter handlers, translates them to playback commands, and publishes now-playing state in the main-thread run loop.
- `mediactl/service_stub.go`: no-op implementation for unsupported platforms.

The model sends playback state through the playback notifier when state changes.
On Linux, `mediactl` uses `SetMust`, not `Set`, to bypass property-library
writable checks and callback triggers. These checks and triggers apply to
external D-Bus writes. For writable properties such as Volume, `mediactl`
translates the D-Bus callback to an application playback command. It sends this
command to the Bubbletea event loop.

## Limitations

cliamp does not expose shuffle and loop status. The TUI `z` and `r` keys control
shuffle and repeat locally. External tools cannot view or control these states.

On Linux, `HasTrackList` is false. cliamp does not implement the optional
`org.mpris.MediaPlayer2.TrackList` interface.

### Playlists

URL: https://docs.cliamp.stream/docs/cliamp/playlists

cliamp supports local **TOML playlists** that you manage in the TUI or CLI. It also loads **M3U/M3U8/PLS playlists** from files and URLs.

## M3U and PLS Playlists

Load local or remote `.m3u`, `.m3u8`, and `.pls` files:

```sh
cliamp ~/radio-stations.m3u
cliamp http://radio.example.com/streams.m3u
cliamp ~/music.m3u https://example.com/live.m3u   # mix local + remote
cliamp ~/radio.pls
```

### EXTINF Metadata

cliamp reads titles and durations from `#EXTINF` lines:

```m3u
#EXTM3U
#EXTINF:180,Radio Station 1
http://station-1.com/stream
#EXTINF:-1,Radio Station 2
http://station-2.com/stream/hd
```

Entries without `#EXTINF` also work. cliamp uses the file name or URL as the title.

### Relative Paths

cliamp resolves paths in a local M3U file from the M3U file directory:

```m3u
#EXTINF:240,My Song
../Music/song.mp3
#EXTINF:-1,Live Stream
http://example.com/live
```

If `radio.m3u` is in `~/playlists/`, cliamp resolves `../Music/song.mp3` to `~/Music/song.mp3`.

### Edge Cases Handled

- UTF-8 BOM (common in Windows-created files)
- `\r\n` line endings
- Missing `#EXTM3U` header
- Mixed local and remote entries in the same file
- Other `#` directives (silently skipped)

---

## Local TOML Playlists

Create and manage playlists as `.toml` files in `~/.config/cliamp/playlists/`. The folder follows cliamp config directory resolution: `CLIAMP_CONFIG_DIR`, then `XDG_CONFIG_HOME/cliamp`, then `HOME/.config/cliamp`.

### File Format

Each playlist has one `.toml` file. cliamp automatically reads every file in the `playlists/` folder with a `.toml` extension, case-insensitively. The CLI or a user can create these files. cliamp skips files that it cannot parse. The file name without its extension is the playlist name:

```text
~/.config/cliamp/playlists/
├── radio-stations.toml   → playlist "radio-stations"
├── music.toml            → playlist "music"
└── gym.toml              → playlist "gym"
```

Use one file for each collection. You can use files that you create and files that the CLI creates. cliamp keeps empty playlists on disk so they remain visible in the TUI and CLI.

```toml
# ~/.config/cliamp/playlists/radio-stations.toml

[[track]]
path = "http://station-1.com/stream"
title = "Radio Station 1"
realtime = true

[[track]]
path = "http://station-2.com/stream/hd"
title = "Radio Station 2"
artist = "Radio Network"

[[track]]
path = "/home/user/Music/song.mp3"
title = "My Song"
artist = "My Artist"
```

Each `[[track]]` section supports these keys:

| Key | Required | Description |
|-----|----------|-------------|
| `path` | Yes | File path or HTTP URL |
| `title` | Yes | Title to display |
| `artist` | No | Artist name |
| `album` | No | Album name |
| `genre` | No | Genre name |
| `year` | No | Release year |
| `track_number` | No | Track number |
| `duration_secs` | No | Duration in seconds |
| `realtime` | No | Treat an HTTP URL as live radio. Reconnect after pause or disconnect. |
| `embedded_lyrics` | No | Lyrics from local file tags |
| `album_art_url` | No | Cached file URL for embedded album art |
| `bookmark` | No | Bookmark flag |

cliamp treats HTTP/HTTPS paths as streams. Set `realtime = true` for live radio.
cliamp keeps this flag when it saves the playlist.

### Directory Sources (`[[dir]]`)

Instead of listing each file, reference a directory in a playlist. cliamp scans
the directory for audio files each time it loads the playlist. New files appear
automatically. Removed files no longer appear:

```toml
# ~/.config/cliamp/playlists/music.toml

[[dir]]
path = "~/Music"

[[track]]
path = "https://radio.example.com/stream"
title = "My Radio"
```

Each `[[dir]]` section supports these keys:

| Key | Required | Description |
|-----|----------|-------------|
| `path` | Yes | Directory path. cliamp expands `~` and environment variables. |
| `recursive` | No | Also scan subdirectories (default `true`) |

cliamp returns directory tracks in document order and sorts each directory by
path. An explicit `[[track]]` with the same path overrides a directory scan. Use
this to save a bookmark or custom metadata for a file. When you bookmark a
directory track with TUI `f` or `cliamp playlist bookmark`, cliamp writes an
explicit `[[track]]` entry so the bookmark remains. Unreadable or missing
directories add no tracks.

Use `--dir` to create or extend these playlists on the CLI:

```sh
cliamp playlist create "Music" --dir ~/Music
cliamp playlist add "Music" --dir ~/Downloads/live
cliamp playlist dirs "Music"               # list referenced directories
```

Do not combine `--dir` with `--ssh`. The CLI and TUI refuse to remove a
directory track because the directory source owns it. Delete the file from the
directory or edit the `[[dir]]` section instead.

### Adding Files and Directories

A playlist file can contain any number of `[[track]]` and `[[dir]]` sections.
Mix them as needed. This `mix.toml` has two directory sources, two absolute file
paths, and a stream URL:

```toml
# ~/.config/cliamp/playlists/mix.toml

[[dir]]
path = "~/Music"

[[track]]
path = "/home/user/Downloads/live-set.mp3"
title = "Live Set"

[[dir]]
path = "~/Downloads/podcasts"
recursive = false

[[track]]
path = "https://radio.example.com/stream"
title = "My Radio"
```

You can also use many files. Each `.toml` file in the `playlists/` folder is a
separate playlist:

```toml
# ~/.config/cliamp/playlists/gym.toml

[[dir]]
path = "~/Music/gym"

[[track]]
path = "/home/user/Documents/warmup.mp3"
title = "Warmup"
```

```toml
# ~/.config/cliamp/playlists/chill.toml

[[track]]
path = "/home/user/Downloads/chill-lofi.mp3"
title = "Lofi"
```

Build the same playlists on the command line without editing files. Positional
paths become `[[track]]` entries. `--dir` stores a directory reference that
cliamp scans on every load:

```sh
cliamp playlist create "mix" ~/Downloads/live-set.mp3 --dir ~/Music --dir ~/Downloads/podcasts
cliamp playlist create "gym" ~/Documents/warmup.mp3 --dir ~/Music/gym
cliamp playlist create "chill" ~/Downloads/chill-lofi.mp3
```

Add more files and directories to an existing playlist:

```sh
cliamp playlist add "mix" another-track.mp3 --dir ~/Downloads/live
```

`recursive = false` has no CLI flag. Set it in the playlist `[[dir]]` section.

### Podcast / RSS Feed Playlists

Save podcast RSS feed URLs in a playlist. Set `feed = true` to mark a track as a
feed. When you play it, cliamp resolves the feed into individual episodes. It
does not stream the feed directly.

```toml
# ~/.config/cliamp/playlists/podcasts.toml

[[track]]
path = "https://feeds.simplecast.com/54nAGcIl"
title = "The Daily"
feed = true

[[track]]
path = "https://lexfridman.com/feed/podcast/"
title = "Lex Fridman Podcast"
feed = true
```

Each `[[track]]` with `feed = true` supports these keys:

| Key | Required | Description |
|-----|----------|-------------|
| `path` | Yes | RSS/Atom feed URL |
| `title` | Yes | Display name for the feed |
| `feed` | Yes | Must be `true` to enable feed resolution |

When you select a feed entry, cliamp fetches the RSS feed. It extracts episodes
with audio enclosures and loads them into the playlist. It keeps episode titles
and durations from `<itunes:duration>`.

cliamp also detects URLs with `.xml`, `.rss`, or `.atom` extensions as feeds. You
do not need `feed = true` for these URLs.

### Browsing and Loading Playlists

Run `cliamp` without arguments to connect to the built-in radio channel. If you configure Navidrome, cliamp opens the provider browser instead.

To browse local playlists, press `Esc` or `b` during playback to open the
provider browser. Use `Up`/`Down` or `j`/`k` to navigate. Press `Enter` to load
a playlist. Its tracks replace the current playlist and start playback. Press
`Tab` to return to the now-playing playlist without loading it again.

If you also configure Navidrome, both sources appear in one list with provider
labels, such as `[Navidrome] Jazz` and `[Local Playlists] favorites`.

You can start with CLI files and browse playlists later:

```sh
cliamp song.mp3                    # starts playing, Esc opens browser
```

### Managing Playlists

Press `p` in any view to open the playlist manager:

1. **Browse**: View all playlists and their track counts.
2. **Filter**: Press `/` to filter the list as you type. This works on the playlists and tracks screens. `Esc` clears the filter.
3. **Open**: Press `Enter` or `→` to view playlist tracks.
4. **Create playlist**: Press `a`, enter a name, and press `Enter`. The file browser opens at `~` for the new playlist. Use `Space` to select folders or files. Folders become live `[[dir]]` sources. Press `Enter` to confirm or `Esc` to finish.
5. **Rename playlist**: Press `r` on the list screen.
6. **Delete playlist**: Press `d`, then `y` to confirm.
7. **Mark tracks**: Open a playlist. Press `Space` to mark a track and advance, or `a` to mark or unmark all visible tracks.
8. **Move tracks**: Press `[` or `]`. cliamp saves the playlist immediately.
9. **Sort tracks**: Press `s` to cycle `track`, `title`, `artist`, `album`, `artist+album`, and `path`.
10. **Remove tracks**: Press `d` to remove marked tracks, or the selected track when none are marked.
11. **Undo manager edits**: Press `u` after delete, remove, move, or sort.
12. **Write tracks elsewhere**: Press `w` to copy marked or selected tracks to another playlist. cliamp skips duplicate paths.
13. **Add files**: Press `o` inside a playlist to browse and add files to it.
14. **Play this**: Press `Enter` in the track list to start at the selected track. The rest of the playlist follows.
15. **Play all**: Press `p` to start from the top, regardless of cursor position.
16. **New playlist**: Select "+ New Playlist...", enter a name, and press `Enter`. The file browser opens so you can add tracks immediately. If a `/` filter is active, cliamp fills the new playlist name with the filter text.

Tracks with an `album` field are grouped by album with separator headers in the
playlist manager and the main player view. Album grouping is hidden while a
filter is active.

cliamp creates `~/.config/cliamp/playlists/` on first use. Removing the last
track leaves an empty playlist file. Use `d` in the playlist list or `cliamp
playlist delete` to delete the playlist.

### Writing to Playlists

Press `w` on a track in the main playlist to open the local playlist picker.
Select an existing playlist or `+ New Playlist...`. cliamp skips and reports
exact duplicate paths.

In the file browser, use `Space` to select files. Use `a` to select all visible
audio files. Press `w` to write the selection to a playlist instead of loading
it into the current queue.

### Command Line Management

Manage local TOML playlists without opening the TUI:

```sh
cliamp playlist list
cliamp playlist create "Name"                    # create an empty playlist
cliamp playlist create "Name" file1 dir/ ...     # create from files/folders
cliamp playlist create "Name" --dir ~/Music      # reference a directory dynamically
cliamp playlist add "Name" file1 dir/ ...        # append, skipping duplicate paths
cliamp playlist add "Name" --dir ~/Music         # add another directory source
cliamp playlist dirs "Name"                      # list directory sources
cliamp playlist rename "Old" "New"
cliamp playlist dedupe "Name"
cliamp playlist sort "Name" --by artist+album
cliamp playlist doctor                           # report missing local files in all playlists
cliamp playlist doctor "Name" --fix              # prune missing local files
cliamp playlist export "Name" --format m3u -o mix.m3u
cliamp playlist import mix.pls --name "Imported"
cliamp playlist show "Name" --json
cliamp playlist remove "Name" --index 3
cliamp playlist bookmark "Name" --index 3       # toggle bookmark flag
cliamp playlist bookmarks                        # list all bookmarked tracks
cliamp playlist enrich "Name"                    # backfill duration/album metadata
cliamp playlist delete "Name"
```

Use `track`, `title`, `artist`, `album`, `artist+album`, or `path` as sort keys.

New playlist names reject path separators and non-portable file name characters.
cliamp can still read and write existing playlist files with older Unix-only
names.

### Creating Playlists Manually

Create the directory, then add a `.toml` file:

```sh
mkdir -p ~/.config/cliamp/playlists
```

```toml
# ~/.config/cliamp/playlists/favorites.toml

[[track]]
path = "/home/user/Music/song.mp3"
title = "Great Song"
artist = "Good Artist"

[[track]]
path = "https://radio.example.com/stream"
title = "My Radio"
```

### Controls

**Playlist browser (provider view):**

| Key | Action |
|-----|--------|
| `Up` `Down` / `j` `k` | Navigate playlists |
| `Enter` | Load the selected playlist |
| `Tab` | Switch to the now-playing playlist |
| `Esc` `b` | Open browser (from playlist view) |

**Playlist manager (`p` key):**

| Key | Action |
|-----|--------|
| `p` / `Esc` | Open or close the playlist manager. `Esc` on the tracks screen goes back. |
| `Up` `Down` / `j` `k` | Navigate |
| `/` | Filter playlists or tracks; `Esc` clears |
| `Enter` / `→` | List screen: open a playlist. Tracks screen: play the **selected** track. |
| `p` | Play all tracks from the top (tracks screen) |
| `a` | List: create a playlist. After naming it, the file browser opens at `~`. Use `Space` to select folders or files and `Esc` to finish. Tracks: mark or unmark all visible tracks. |
| `r` | Rename the highlighted playlist (list screen; `Recently Played` cannot be renamed) |
| `Space` | Mark/unmark track and advance (tracks screen) |
| `s` | Cycle supported sort keys (tracks screen) |
| `w` | Write marked or selected tracks to another playlist. On the list screen, write the current queue. |
| `o` | Add files to the open playlist (tracks screen) |
| `D` | List: open the file browser to add `[[dir]]` sources to the selected playlist. Tracks: open the directory-sources screen for the open playlist. |
| `[` `]` | Move track up/down and save (tracks screen) |
| `d` | Delete a playlist after confirmation. `Recently Played` cannot be deleted. In tracks, remove marked tracks or the selected track if none are marked. |
| `u` | Undo the last playlist-manager edit |
| `←` / `Backspace` | Go back from tracks screen to list |

The playlist list marks playlists with `[[dir]]` sources with a `· N dir(s)`
indicator next to the track count.

**Directory sources screen (tracks screen, `D`):**

| Key | Action |
|-----|--------|
| `Up` `Down` / `j` `k` | Navigate directory sources |
| `a` | Open the file browser to add a directory as a `[[dir]]` source |
| `d` then `y` | Remove the selected source. Confirm with `y`; any other key cancels. |
| `r` | Toggle `recursive` on the selected source. cliamp scans it again immediately. |
| `←` / `Backspace` / `Esc` | Back to the tracks screen |

In the file browser, press `D` to add selected directories as live `[[dir]]`
sources instead of expanding them into explicit tracks. If none are selected,
cliamp adds the selected directory or the directory that you are browsing. This
browser mode starts with `a` above, `o` from the tracks screen, or `D` from the
list screen. cliamp skips and reports directories that are already referenced.

## Favorites

Press `n` on a track in the track list to toggle its favorite state. cliamp
collects favorited tracks in the virtual **"Favorites"** playlist. This playlist
always appears at the top of the playlist list, even when empty and regardless
of the source playlist.

Favorites apply across playlists. A track that you favorite in "gym" appears in
"Favorites", and the reverse is also true. `~/.config/cliamp/favorites.toml`
stores the "Favorites" playlist. Like "Recently Played", it is a virtual
playlist that you cannot rename, delete, or change in the playlist manager. Use
`n` again to remove a favorite.

Favorited tracks show a small red `♥` marker in the track list. The bookmark
system is separate: it uses the `f` key and `★` marker. Bookmarks apply to one
playlist. Favorites apply to all playlists.

### Lyrics

URL: https://docs.cliamp.stream/docs/cliamp/lyrics

Press `y` to show lyrics for the current track. For a local file, cliamp first uses lyrics embedded in file tags. If the file has no embedded lyrics, cliamp fetches lyrics from LRCLIB and NetEase Cloud Music.

## Modes

- **Synced lyrics**: For local files, Navidrome tracks, and YouTube/yt-dlp tracks with a known duration, lyrics scroll automatically and highlight the active line during playback.
- **Scroll mode**: For plain lyrics without timestamps, live radio (ICY), and YouTube Live, use `j`/`k` or the arrow keys to scroll manually. The YouTube Live position is not relative to the song.

cliamp keeps timestamps in embedded LRC lyrics. It shows embedded plain-text lyrics in scroll mode.

## Streams

cliamp updates lyrics when ICY metadata changes, for example when an internet radio station changes tracks.

## YouTube and SoundCloud

cliamp parses titles such as "Artist - Song (Official Video)" to build search queries.

### Recently Played

URL: https://docs.cliamp.stream/docs/cliamp/recently-played

cliamp stores local listening history in `~/.config/cliamp/history.toml`. It
records a play after you listen to at least 50% of a track. This is the same
threshold that Last.fm and the Navidrome scrobbler use. Skipped tracks do not
enter the list.

## Browsing in the TUI

Open the **Local Playlists** provider. After cliamp records at least one play,
a virtual `Recently Played` entry appears at the top. Open it like any other
playlist. Tracks are newest first. The list is read-only. cliamp rejects
bookmark, track removal, and playlist deletion requests with an error.

To clear the list, run `cliamp history clear`.

## CLI

```sh
cliamp history                # show the 50 most recent plays
cliamp history --limit 200    # show the 200 most recent
cliamp history --limit 0      # show all (capped at 200 entries on disk)
cliamp history --json         # machine-readable output
cliamp history clear          # wipe the history file
```

The relative timestamp, such as `3m ago` or `yesterday`, uses local time. The
JSON output uses `played_at` in RFC 3339 UTC for portability.

## File format

`history.toml` uses the same minimal TOML format as cliamp local playlists:

```toml
[[entry]]
played_at = "2026-05-06T22:09:11Z"
path = "/home/me/Music/AC-DC/Highway to Hell.flac"
title = "Highway to Hell"
artist = "AC/DC"
album = "Highway to Hell"
year = 1979
duration_secs = 208
```

The default limit is 200 entries. cliamp removes older plays in FIFO order.
Consecutive plays of the same track within 5 minutes update the top entry time
instead of adding another entry.

## What is not recorded

- Tracks skipped before the 50% threshold.
- Live streams without a known duration, such as radio stations and ICY streams.
  cliamp cannot detect their 50% point.
- Tracks with empty paths. This is a defensive check.

### Themes

URL: https://docs.cliamp.stream/docs/cliamp/themes

cliamp includes 21 color themes that pass contrast checks. You can add custom themes with TOML files.

Press `t` during playback to open the theme picker. Use `↑`/`↓` to navigate and preview each theme. Press `Enter` to select it or `Esc` to cancel.

cliamp saves your selection and restores it at the next start.

## Built-in themes

ayu-mirage-dark, catppuccin, catppuccin-latte, dracula, ember, ethereal, everforest, flexoki-light, gruvbox, hackerman, kanagawa, matte-black, miasma, neon-blade-runner, nord, osaka-jade, ristretto, rose-pine, tokyo-night, vantablack, winamp

## Creating a custom theme

Create a `.toml` file in `~/.config/cliamp/themes/`:

```
mkdir -p ~/.config/cliamp/themes
```

Each file needs all six foreground colors as `#RRGGBB` hex values. Add `bg` to
set a background. Omit it to keep the terminal background. cliamp ignores
incomplete or malformed custom themes. The file name without `.toml` is the
theme name.

### Example: `~/.config/cliamp/themes/solarized.toml`

```toml
bg = "#002b36"
accent = "#268bd2"
bright_fg = "#eee8d5"
fg = "#839496"
green = "#859900"
yellow = "#b58900"
red = "#dc322f"
```

Press `t` to show the theme in the list immediately.

### Color reference

| Key         | Color use                                   |
|-------------|---------------------------------------------|
| `bg`        | Optional application background             |
| `accent`    | Title, track name, seek bar, selected items |
| `bright_fg` | Primary text and time display               |
| `fg`        | Muted text, help bar, inactive elements     |
| `green`     | Playing, success, volume, spectrum low      |
| `yellow`    | Warnings and spectrum middle               |
| `red`       | Errors and spectrum top                    |

All values are six-digit hex strings, for example `"#ff5733"`. Help-key pill
text switches between black and white for readable contrast.

Important UI states also use stable text markers: `>`, `Q`, `★`, `!`, `WARN:`,
and `ERR:`. These markers keep state and feedback distinct in monochrome
terminals.

## Overriding a built-in theme

If a custom file has the same name as a built-in theme, the custom file takes
priority. For example, `~/.config/cliamp/themes/catppuccin.toml` replaces the
built-in catppuccin theme.

## Setting a default theme

Add a `theme` line to `~/.config/cliamp/config.toml`:

```toml
theme = "catppuccin"
```

Use the file name without `.toml`. Leave the value empty or omit it to use
terminal default colors.

### Spotify Integration

URL: https://docs.cliamp.stream/docs/cliamp/spotify-integration

Use Cliamp to stream your [Spotify](https://www.spotify.com/) library through its audio pipeline. EQ, the visualizer, and other effects apply. You need a [Spotify Premium](https://www.spotify.com/premium/) account.

> **Windows:** Build cliamp with CGO enabled and a MinGW toolchain for Spotify support. See [Building from source](https://whiterose.org.contextowl.co/docs/cliamp#building-from-source) in the README. Pre-built Windows binaries from Releases include Spotify support.
>
> **Quick start:** Run `cliamp setup`, select Spotify, and follow the prompts. Register a Spotify Developer app and enter its `client_id` to get a private Web API rate-limit quota, including for search. Cliamp authorizes playback separately with the built-in Spotify identity. You can instead use the built-in shared `client_id` without registering an app.

## Setup

### Recommended: bring your own client ID

Register a Spotify Developer app. Set its `client_id` in `~/.config/cliamp/config.toml`:

```toml
[spotify]
client_id = "your_client_id_here"
bitrate = 320
```

To register an app:

1. Go to [developer.spotify.com/dashboard](https://developer.spotify.com/dashboard) and sign in.
2. Click **Create app**.
3. Enter a name, such as "cliamp", and a description.
4. Add `http://127.0.0.1:19872/login` as a **Redirect URI**.
5. Select **Web API** under "Which API/SDKs are you planning to use?".
6. Click **Save**.
7. Open the app **Settings** and copy the **Client ID**.

`bitrate` is optional. If omitted, cliamp uses `320`. Supported values are `96`, `160`, and `320`. Values less than or equal to zero use `320`. cliamp rounds other positive values to the nearest supported bitrate.

Run `cliamp`, select Spotify, and press Enter to sign in. With your own `client_id`, the browser completes two authorization steps in one tab: one for Web API access and one for playback. The built-in client path needs one step. cliamp stores credentials in `~/.config/cliamp/spotify_credentials.json`. Later launches refresh them without a message.

### Development Mode search page size

Spotify introduced the current Development Mode restrictions for new apps on February 11, 2026. It migrated existing Development Mode apps on March 9, 2026. Extended Quota Mode apps are not affected. See the Spotify [February 2026 migration guide](https://developer.spotify.com/documentation/web-api/tutorials/february-2026-migration-guide) for the full timeline.

Search remains available in Development Mode, but `/v1/search` accepts at most **10 results per request**. A larger request returns `400 "Invalid limit"`. This does not mean search is blocked. Cliamp uses `offset` to page results in groups of 10. <kbd>Ctrl+F</kbd> returns the full result set.

Other Development Mode changes remove endpoints such as `/v1/browse/new-releases`. They restrict playlist items to playlists the user owns or collaborates on. `/v1/search` remains available and does not require Extended Quota Mode.

### Alternative: built-in shared client ID

To use no registered app, omit the `client_id` line:

```toml
[spotify]
bitrate = 320
```

cliamp uses a built-in `client_id`. [librespot](https://github.com/librespot-org/librespot) and [spotify-player](https://github.com/aome510/spotify-player) use the same client ID.

> **Shared rate limit:** The built-in `client_id` is shared by librespot, spotify-player, and cliamp users worldwide. Spotify applies its per-app quota globally. A busy pool can cause `429 Too Many Requests` during search or playlist loading. Cliamp retries with backoff. Persistent 429 errors indicate a busy pool. Your own `client_id` has a separate quota.

## Usage

After authentication, Spotify appears in the provider list. Press `Esc`/`b` to open the provider browser and select Spotify.

The provider panel lists Spotify playlists. Use the arrow keys to select one and press `Enter` to load it. Tracks stream through the cliamp audio pipeline. EQ, the visualizer, mono, and other effects work as they do for local files.

## Controls

When focused on the provider panel:

| Key | Action |
|---|---|
| `Up` `Down` / `j` `k` | Navigate playlists |
| `Enter` | Load the selected playlist |
| `Tab` | Switch between provider and playlist focus |
| `Esc` / `b` | Open provider browser |

After you load a playlist, Cliamp returns to the standard playlist view. Use the usual controls for seek, volume, EQ, shuffle, repeat, queue, search, and lyrics.

## Playlists

The provider shows only playlists in the Spotify library. This includes playlists you created and saved, or followed. If a public playlist is missing, open Spotify and click **Save** first. You do not need to copy tracks to a new playlist.

## Podcasts

Podcast episodes work as tracks. Press `Ctrl+F` to search Spotify. Matching episodes, such as "Joe Rogan", appear with songs. Press `Enter` to play. Playlists can load and play both songs and episodes.

## Troubleshooting

- **"OAuth failed"**: Ensure the Spotify dashboard redirect URI is exactly `http://127.0.0.1:19872/login`, without a trailing slash.
- **Two authorization steps**: This is expected with your own `client_id`. After you approve Web API access, the same browser tab redirects to create a playback credential with the required Spotify built-in identity.
- **Playlist not showing**: Save or follow the playlist in Spotify. The provider lists only library playlists.
- **Playback issues**: Spotify integration needs a Premium account. Free accounts cannot stream.
- **Re-authenticate**: Run `cliamp spotify reset` to clear stored credentials. Then restart cliamp, select Spotify, and sign in again. This is the same as deleting `~/.config/cliamp/spotify_credentials.json`.
- **Persistent "rate-limited" errors on `/v1/me`**: Stored authorization has expired or been revoked. Cliamp usually detects this at startup and prompts for sign-in. If it does not, run `cliamp spotify reset` and authenticate again. This is *not* a Spotify rate limit. Waiting does not fix it.
- **`429 Too Many Requests` on search or playlist loading (using the built-in fallback)**: The built-in `client_id` is shared with librespot- and spotify-player-based clients. When the global pool is busy, Spotify limits requests for every client that uses it. Cliamp retries with exponential backoff. If errors continue, register a developer app and set `client_id` in `[spotify]`. Your app has a separate quota.
- **`400 "Invalid limit"` on <kbd>Ctrl+F</kbd>**: Development Mode apps limit `/v1/search` to 10 results per request. Cliamp pages results automatically. This error means the limit is now less than 10. Open an issue.

## Requirements

- Spotify Premium account
- No additional system dependencies beyond cliamp itself
- A registered app at [developer.spotify.com/dashboard](https://developer.spotify.com/dashboard) is **optional**: cliamp has a built-in fallback `client_id`

### YouTube & YouTube Music Integration

URL: https://docs.cliamp.stream/docs/cliamp/youtube-youtube-music-integration

Use Cliamp to browse [YouTube](https://youtube.com/) and [YouTube Music](https://music.youtube.com/) playlists and play tracks through its audio pipeline. EQ, the visualizer, and other effects apply. Install yt-dlp for playback.

Cliamp automatically sorts playlists into two providers:
- **YouTube Music**: Playlists with music content.
- **YouTube**: Playlists with non-music content, such as podcasts, vlogs, and tutorials.

> **Quick start:**
> - **Cookie-based (zero OAuth):** Set `cookies_from = "your_browser"` in `~/.config/cliamp/config.toml`, or select a browser in `cliamp setup`. cliamp loads playlists through the existing browser session. You do not need OAuth credentials or `ytmusic_credentials.json`.
> - **OAuth-based:** Set Google Cloud OAuth credentials as described below. Then press Enter in the provider browser to sign in. cliamp stores credentials in `~/.config/cliamp/ytmusic_credentials.json`.

## Setup

### Option 1: Browser cookies (zero setup)

Add the browser name to `~/.config/cliamp/config.toml`, or run `cliamp setup`:

```toml
[ytmusic]
cookies_from = "chrome"
```

Supported browsers: `chrome`, `firefox`, `brave`, `edge`, `opera`, `safari`, `chromium`.

You can set a specific profile or path with yt-dlp `browser:path` syntax. For example, the Zen browser, a Firefox fork, stores its profile outside the default path:

```toml
[ytmusic]
cookies_from = "firefox:~/.config/zen"
```

### Option 2: Custom Google Cloud OAuth client

#### Creating your client ID

1. Go to [console.cloud.google.com](https://console.cloud.google.com/) and sign in.
2. Create a project or select an existing project.
3. Open **APIs & Services > Library**.
4. Search for **YouTube Data API v3** and click **Enable**.
5. Open **APIs & Services > Credentials**.
6. Click **Create Credentials > OAuth client ID**.
7. If prompted, configure the OAuth consent screen first:
    - User Type: **External**
    - Enter an app name, such as "cliamp", and an email address.
    - Add scope: `https://www.googleapis.com/auth/youtube.readonly`
    - Add yourself as a test user. This is required while the app is in "Testing" status.
8. For the OAuth client ID:
    - Application type: **Desktop app**
    - Name: Any name, such as "cliamp".
9. Copy the **Client ID** and **Client Secret**.

#### Configuring cliamp with OAuth

Add the client ID and client secret to `~/.config/cliamp/config.toml`:

```toml
[ytmusic]
client_id = "your_client_id_here"
client_secret = "your_client_secret_here"
```

Optional: To play uploaded or private tracks, set the browser for cookie access:

```toml
[ytmusic]
client_id = "your_client_id_here"
client_secret = "your_client_secret_here"
cookies_from = "chrome"
```

Optional: Control whether `list=` URLs expand a full playlist or resolve as one video:

```toml
[ytmusic]
expand_playlist = false
```

When `expand_playlist` is `true` (default), cliamp expands URLs with a `list=` parameter. This includes auto-generated mixes (RDAMVM, RDMM), album playlists (OLAK), and custom playlists (PL). cliamp loads the first 20 tracks immediately, then gets the remaining tracks in background batches. Set it to `false`, or pass `--no-expand-playlist`, to remove the playlist parameter and resolve only one video.

Run `cliamp`, `cliamp --provider ytmusic`, or `cliamp --provider youtube`. Select a provider and press Enter to sign in. cliamp stores credentials in `~/.config/cliamp/ytmusic_credentials.json`. Later launches refresh them without a message.

## Usage

After authentication, **YouTube** and **YouTube Music** appear as separate providers. Press `Esc`/`b` to open the provider browser.

- **YouTube Music** shows playlists classified as music (video category "Music").
- **YouTube** shows all other playlists, such as podcasts, vlogs, and tutorials.

Both use the same Google account sign-in. cliamp classifies playlists by video category and stores the result on disk. Later launches use the cached result.

## Controls

When focused on the provider panel:

| Key | Action |
|---|---|
| `Up` `Down` / `j` `k` | Navigate playlists |
| `Enter` | Load the selected playlist |
| `Tab` | Switch between provider and playlist focus |
| `Ctrl+R` | Refresh playlists from YouTube |
| `Esc` / `b` | Open provider browser |

After you load a playlist, Cliamp returns to the standard playlist view. Use the usual controls for seek, volume, EQ, shuffle, repeat, queue, search, and lyrics.

## Playlists

With OAuth authentication, cliamp splits playlists between the two providers:

**YouTube Music** shows:
- **Liked Music**: Liked songs in the YouTube Music special `LM` playlist.
- Playlists with music content, automatically classified by video category.

**YouTube** shows:
- **Liked Videos**: Liked videos in the YouTube special `LL` playlist.
- Playlists with non-music content.

For OAuth setups, cliamp samples a video from each playlist and checks its YouTube category. It stores results in `~/.config/cliamp/ytmusic_classification.json` and `~/.config/cliamp/ytmusic_cache.json`. Delete these files or press `Ctrl+R` in the TUI to classify again and refresh.

For cookie-backed providers (`cookies_from`), cliamp adds all custom playlists to both YouTube Music and YouTube results without category classification. It does not create `ytmusic_classification.json`. It stores results and tracks in memory for the current session. Press `Ctrl+R` to refresh them.

## Troubleshooting

- **Linux Keyring / Cookie Decryption (`cannot decrypt v11 cookies: no key found`)**: On Linux desktops or window managers, such as Hyprland, Sway, and i3, Chromium/Chrome can encrypt cookies with GNOME Keyring or KWallet. Append the keyring name to `cookies_from`:

  ```toml
  [ytmusic]
  cookies_from = "chromium+gnomekeyring"  # or "chrome+gnomekeyring", "brave+kwallet"
  ```

- **"ERR: waiting for audio data: EOF" / playback stops immediately**: yt-dlp did not produce a stream. cliamp shows the yt-dlp message, such as "Sign in to confirm you're not a bot", instead of only EOF. Read the full error. Common causes follow:
  - **Outdated yt-dlp**: Update it with `yt-dlp -U`, or reinstall from the [official repo](https://github.com/yt-dlp/yt-dlp). Distro and winget builds are often stale and can fail when YouTube changes.
  - **Bot detection**: YouTube blocks anonymous requests. Set `cookies_from` so yt-dlp uses the signed-in browser session. For Zen browser, use `cookies_from = "firefox:~/.config/zen"`.
  - **Wrong `cookies_from` value**: Install the browser, sign in to YouTube, and use the correct profile path.
- **"OAuth failed"**: Ensure that the Google Cloud project has YouTube Data API v3 enabled and uses OAuth client type "Desktop app".
- **"Access blocked"**: While the app is in "Testing" status, only added test users can sign in. Add the Google account as a test user in OAuth consent screen settings.
- **Playlist not showing**: The provider lists only library playlists. Save or follow a playlist in YouTube Music for it to appear.
- **Re-authenticate / Reset Cache**: Delete `~/.config/cliamp/ytmusic_credentials.json` for OAuth. Or press `Ctrl+R` in the TUI or remove `~/.config/cliamp/ytmusic_cache.json`.
- **Private/deleted videos**: cliamp automatically skips these when it loads a playlist.

## Requirements

- [yt-dlp](https://github.com/yt-dlp/yt-dlp) installed and on `PATH` for audio playback
- Browser cookies (`cookies_from = "browser"`, no Google Cloud setup) or a Google Cloud project with YouTube Data API v3 enabled for OAuth
- No Spotify Premium or other paid subscription is required. The YouTube Music free tier works.

### SoundCloud Integration

URL: https://docs.cliamp.stream/docs/cliamp/soundcloud-integration

Enable [SoundCloud](https://soundcloud.com) to search, paste URLs to play, browse profiles, and stream subscriber-gated tracks with browser cookies. Playback uses [yt-dlp](https://github.com/yt-dlp/yt-dlp). Put `yt-dlp` on `PATH`.

> SoundCloud closed its OAuth program to new applications in 2014. You cannot use the Spotify-style bring-your-own-`client_id` pattern. cliamp uses the existing SoundCloud session in your browser. See [Sign in via browser cookies](#sign-in-via-browser-cookies).

## Enable

SoundCloud is **off by default**. To enable it, add this to `~/.config/cliamp/config.toml`:

```toml
[soundcloud]
enabled = true
```

After you enable it:

- **Search** with `Ctrl+F` while SoundCloud is active. cliamp runs `scsearch:` against the SoundCloud public index.
- **Paste a URL** (`u`). Any `soundcloud.com/<artist>/<track>` URL plays.
- **Browse list with curated genres**. Without a configured profile, the playlists pane lists **Trending**, **Hip-Hop**, **Electronic**, **House**, **Lo-Fi**, **Indie**, and **Pop**. These are virtual playlists backed by real-time scsearch results, not editorial charts. SoundCloud official chart endpoints currently return 404 through yt-dlp.

## Browse a profile

Set a username to show the profile content in the browse pane:

```toml
[soundcloud]
enabled = true
user = "yourname"
```

This replaces the curated Browse list with three playlists from `soundcloud.com/yourname`:

- **Tracks**: All tracks the user uploaded.
- **Likes**: Tracks the user liked.
- **Reposts**: Tracks the user reposted.

This works for any public profile. It does not require SoundCloud sign-in.

## Sign in via browser cookies

For private likes, hidden uploads, or SoundCloud Go+ subscriber-gated tracks, point yt-dlp to the browser cookie jar:

```toml
[soundcloud]
enabled = true
user = "yourname"
cookies_from = "firefox"   # also: chrome, chromium, brave, edge, opera, safari, vivaldi
```

cliamp passes `--cookies-from-browser <name>` to every yt-dlp command for search, browse, and playback. Sign in to SoundCloud in that browser. You do not need to keep it open. yt-dlp then uses the account access permissions.

This is the same mechanism as `[ytmusic] cookies_from`. cliamp selects cookie
sources by service. SoundCloud and YouTube can use different browsers or
profiles in one cliamp process.

## CLI

```sh
cliamp https://soundcloud.com/forss/flickermood   # play a track
cliamp https://soundcloud.com/forss/sets/album    # play a set / playlist
cliamp https://soundcloud.com/forss               # play a profile's tracks
cliamp --provider soundcloud                      # start with SoundCloud as the active provider
cliamp search-sc "lofi beats"                     # legacy: SoundCloud search from the shell
```

URL playback works whether or not `[soundcloud]` is enabled. yt-dlp resolves any SoundCloud link passed by cliamp. The `enabled` flag controls only the in-app provider entry.

## When playback fails

Some tracks return 404 from the SoundCloud per-track format API even when the page and search index still list them. Common causes are Go+ subscriber-gated content, region-blocked streams, deleted cached entries, and temporary yt-dlp extractor errors. cliamp shows the yt-dlp exit message and the status notification *"Couldn't play X — track is gated, restricted, or unavailable."* This indicates an upstream issue.

If this occurs for an expected track, set `cookies_from` and confirm SoundCloud sign-in in that browser.

## Requirements

- [yt-dlp](https://github.com/yt-dlp/yt-dlp) on `PATH`
- Optional: a browser with an active SoundCloud session, for `cookies_from`

### Qobuz Integration

URL: https://docs.cliamp.stream/docs/cliamp/qobuz-integration

Use cliamp to stream your [Qobuz](https://www.qobuz.com/) library through its audio pipeline. EQ, the visualizer, and other effects apply. You need an active Qobuz subscription.

Qobuz delivers lossless FLAC. cliamp uses the same buffer-while-playing and `ffmpeg` pipeline as other lossless providers. Put `ffmpeg` on `PATH`.

## Setup

Run `cliamp setup` for the fastest setup. Select **Qobuz**, select a stream quality, and let the wizard write the `[qobuz]` block.

Or configure Qobuz in `~/.config/cliamp/config.toml`:

```toml
[qobuz]
enabled = true
quality = 6
```

You do not need developer credentials. cliamp gets the `app_id`, signing secrets, and OAuth private key from the Qobuz web player.

Run `cliamp`, select Qobuz, and press `Enter` to sign in. A browser window opens for Qobuz OAuth login. After authorization, cliamp stores credentials in `~/.config/cliamp/qobuz_credentials.json`. Later launches refresh them without a message.

> **Click "Back" to finish.** After authorization, Qobuz shows a *"You are signed in, you can leave this page"* screen with a **Back** button. It does not redirect automatically. Click **Back**. This sends the sign-in code to cliamp and completes authentication. cliamp waits for up to 5 minutes.

### Quality

`quality` selects the Qobuz `format_id`. If you omit it, cliamp uses `6` (FLAC CD). Supported values:

| Value | Format |
|---|---|
| `5`  | MP3 320 kbps |
| `6`  | FLAC 16-bit / 44.1 kHz (CD) |
| `7`  | FLAC 24-bit up to 96 kHz (Hi-Res) |
| `27` | FLAC 24-bit up to 192 kHz (Hi-Res) |

Hi-Res tiers need a Qobuz plan that includes them. Any other value uses `6`.

## Usage

Start cliamp with Qobuz selected:

```sh
cliamp --provider qobuz
```

After authentication, Qobuz appears in the provider list. Press `Q` to select Qobuz. Press `Esc`/`b` to open the provider browser and select it.

The provider shows your Qobuz library:

- **Favorite Tracks**: your liked songs.
- **Random Tracks**: A random sample of up to 500 tracks from all playlists, without duplicates. Press `Ctrl+R` to select a new sample.
- **Your playlists**: playlists you created or subscribed to.
- **Favorite albums**: browsable in the album view.
- **Favorite artists**: browse an artist to see their albums.

Press `Ctrl+F` while Qobuz is active to search the Qobuz catalog for tracks.

## Controls

When focused on the provider panel:

| Key | Action |
|---|---|
| `Up` `Down` / `j` `k` | Navigate |
| `Enter` | Load the selected playlist/album or play the selected track |
| `Ctrl+F` | Search Qobuz tracks |
| `Ctrl+R` | Refresh (re-resolves stream URLs) |
| `Tab` | Switch between provider and playlist focus |
| `Esc` / `b` | Open provider browser |

After you load a playlist or album, cliamp returns to the standard playlist view. Use the usual controls for seek, volume, EQ, shuffle, repeat, queue, search, and lyrics.

## Troubleshooting

- **"OAuth failed" / browser doesn't open**: cliamp opens a localhost redirect listener on a random port. Ensure that nothing blocks outbound access to `qobuz.com` and that a default browser is set. The flow times out after 5 minutes.
- **Sign-in seems to hang / "you can leave this page"**: The Qobuz OAuth page shows a confirmation screen with a **Back** button after authorization. It does not redirect automatically. Click **Back** to complete sign-in. cliamp waits for the redirect for up to 5 minutes.
- **Re-authenticate**: Run `cliamp qobuz reset` to clear stored credentials. Then restart cliamp, select Qobuz, and sign in again. This is the same as deleting `~/.config/cliamp/qobuz_credentials.json`.
- **Track is unplayable / skipped**: The track may not be available for the subscription tier or region. cliamp marks the track unplayable and continues.
- **Hi-Res not delivered**: `quality = 27` does not add Hi-Res to a plan that lacks it. Qobuz returns the best quality allowed by the plan.
- **Stalls after a long idle session**: Signed stream URLs expire. Press `Ctrl+R` to refresh and resolve the URLs again.

## Requirements

- An active Qobuz subscription
- `ffmpeg` on `PATH` for FLAC decoding
- No developer/API registration: cliamp obtains credentials automatically

### NetEase Cloud Music Integration

URL: https://docs.cliamp.stream/docs/cliamp/netease-cloud-music-integration

Enable NetEase Cloud Music to browse account playlists, saved playlists, liked songs, and public charts. Playback uses `yt-dlp`. Put `yt-dlp` and `ffmpeg` on `PATH`.

## Quick Start

Sign in to `music.163.com` in a browser. Then run:

```sh
cliamp setup
```

Select **NetEase Cloud Music**. Select the browser where you signed in. The wizard validates the session and writes:

```toml
[netease]
enabled = true
cookies_from = "chrome"
user_id = "your-account-user-id"
```

cliamp stores only the browser name and user id. It does not store your password or copy cookies to `config.toml`.

## Manual Config

```toml
[netease]
enabled = true
cookies_from = "chrome"
user_id = "78819429"
```

cliamp passes `cookies_from` to `yt-dlp --cookies-from-browser`. Supported names depend on the installed `yt-dlp` version. Common names include `chrome`, `chromium`, `firefox`, `brave`, `edge`, `opera`, `safari`, and `vivaldi`. The setup wizard lists common browsers. Use **Custom browser/profile** only for a profile value such as `chrome:Profile 1` or `firefox:default-release`.

`user_id` is optional with valid cookies. If you omit it, cliamp gets it from the signed-in account.

## Usage

Start cliamp with NetEase selected:

```sh
cliamp --provider netease
```

Inside the TUI:

| Key | Action |
|---|---|
| `M` | Open NetEase provider |
| `Ctrl+F` | Search NetEase songs while NetEase is active |
| `Enter` | Load the highlighted playlist or play the highlighted track |
| `Ctrl+R` | Refresh playlists |

You can also use direct NetEase URLs:

```sh
cliamp 'https://music.163.com/#/song?id=1973665667'
cliamp 'https://music.163.com/#/playlist?id=3778678'
```

## Limits

NetEase playback depends on the account, region, and track rights. If a song is unavailable upstream, cliamp shows the `yt-dlp` error. `cookies_from` gives `yt-dlp` the same account context as the browser. This can improve access to tracks that the account can play.

### YouTube, SoundCloud, Mixcloud, NetEase, Bandcamp and Bilibili

URL: https://docs.cliamp.stream/docs/cliamp/youtube-soundcloud-netease-bandcamp-and-bilibili

Install [yt-dlp](https://github.com/yt-dlp/yt-dlp), then play YouTube, SoundCloud, Mixcloud, NetEase, Bandcamp, and Bilibili URLs:

```sh
cliamp https://www.youtube.com/watch?v=dQw4w9WgXcQ
cliamp https://soundcloud.com/artist/track
cliamp https://www.mixcloud.com/creator/show-name/
cliamp 'https://music.163.com/#/song?id=1973665667'
cliamp https://artist.bandcamp.com/album/name
cliamp https://www.bilibili.com/video/BV1xxxxxxxxx
cliamp https://space.bilibili.com/uid/lists/id  # season/series playlists
```

You can play playlists and albums. Press `S` to save a downloaded track to `~/Music/cliamp/`.

You can also play live streams, such as 24/7 YouTube lofi radios. They have no audio-only formats. cliamp uses the best muxed stream and plays only its audio track. This also applies to live-stream URLs used as stations in `radios.toml`.

## Search

Search and play from the command line:

```sh
cliamp search "never gonna give you up"       # search YouTube
cliamp search-sc "lofi beats"                  # search SoundCloud
```

In the TUI, press `Ctrl+F` to search the active provider. This searches YouTube for YouTube/YT-Music, SoundCloud for SoundCloud, Mixcloud for Mixcloud, and NetEase for NetEase. These providers have signed-in playback guides: [SoundCloud](https://whiterose.org.contextowl.co/docs/soundcloud-integration), [Mixcloud](https://whiterose.org.contextowl.co/docs/mixcloud), and [NetEase](https://whiterose.org.contextowl.co/docs/netease-cloud-music-integration).

## Disclaimer

**Use at your own risk.** Downloading or streaming copyrighted content can violate the terms of service of these platforms. You are responsible for use of this feature.

### Streaming

URL: https://docs.cliamp.stream/docs/cliamp/streaming

cliamp plays audio from URLs, M3U/PLS playlists, and podcast RSS feeds.

## HTTP Streams

Play audio directly from a URL:

```sh
cliamp https://example.com/song.mp3
cliamp http://radio-station.com/stream.m3u
cliamp local.mp3 https://example.com/remote.mp3   # mix local + remote
```

For a non-seekable HTTP stream, the UI shows `● Streaming` and a static seek bar. Seek keys have no effect.

## PLS Playlists

cliamp supports PLS playlist files and M3U files:

```sh
cliamp https://radio.cliamp.stream/lofi/stream.pls
```

## HLS Streams

cliamp supports HLS master and media playlists (`.m3u8`). Large broadcasters, such as Brazilian RBS/Wowza stations, use these playlists:

```sh
cliamp "https://example.com/live/playlist.m3u8"
```

cliamp passes the URL to ffmpeg. ffmpeg resolves relative chunklist and segment URIs and follows the live segment window. This requires `ffmpeg`, which AAC and Opus also require.

Live HLS uses timed metadata, not inline ICY. cliamp does not update the now-playing track title for HLS streams.

## Podcasts

Play a podcast by passing its RSS feed URL:

```sh
cliamp https://example.com/podcast/feed.xml
```

cliamp reads episode titles and the podcast name from the feed and shows them in the playlist.

### Xiaoyuzhou (小宇宙)

Play an individual [Xiaoyuzhou](https://www.xiaoyuzhoufm.com) episode by passing its URL:

```sh
cliamp https://www.xiaoyuzhoufm.com/episode/xxxx
```

## Radio Catalog

Press `R` in the player to browse and search more than 30,000 online radio stations in the [Radio Browser](https://www.radio-browser.info/) directory. Use `/` to search by name, `Enter` to play, and `a` to add a station to the playlist.

## Track Info

For live radio, cliamp shows the current track from inline ICY metadata (`StreamTitle`). This works for most stations and codecs, including MP3, AAC, and Opus.

Some broadcasters do not send inline metadata. They publish now-playing data through a separate API. cliamp reads these APIs automatically:

| Station | Source | Shown |
| --- | --- | --- |
| FIP (and FIP Jazz, Rock, Groove, Reggae, Electro, Metal, Monde, Nouveautes) | Radio France livemeta API | Artist - Title |
| NTS 1 / NTS 2 | NTS live API | Current show |

NTS is live DJ radio with no tag for each track. cliamp shows the show or host name, not a song.

## Load URL at Runtime

Press `u` during playback to load a stream or playlist URL without restarting. It supports the same URL types as CLI arguments: direct audio URLs, M3U/PLS playlists, RSS podcast feeds, and yt-dlp compatible links.

## Run Your Own Radio Station

Run an internet radio station with [cliamp-server](https://github.com/bjarneo/cliamp-server). Point it to a directory of audio files to start broadcasting. It supports multiple stations, live metadata, and on-the-fly transcoding.

See [playlists.md](https://whiterose.org.contextowl.co/docs/playlists) for M3U playlist details.

### SSH Streaming

URL: https://docs.cliamp.stream/docs/cliamp/ssh-streaming

Play music from a remote machine through SSH. You do not need to mount a filesystem.

## How It Works

When a track path starts with `ssh://`, cliamp pipes audio through SSH with the system `ssh` binary:

```
ssh://hostname/absolute/path/to/file.mp3
```

The player runs `ssh hostname cat /path/to/file.mp3` and sends the output to the audio decoder. It uses no temporary files or filesystem mounts.

## Creating SSH Playlists

Use `--ssh HOST` with `playlist create` to scan a remote directory:

```sh
cliamp playlist create "Blade Runner" --ssh nas "/Volumes/Music/Blade Runner/"
# Created playlist "Blade Runner" (31 tracks, ssh://nas)
```

This runs `ssh nas find /path -type f -name '*.mp3' ...` to find audio files. It then creates a TOML playlist with `ssh://` path prefixes.

## TOML Format

SSH playlists use regular playlist format with `ssh://` paths:

```toml
name = "Blade Runner"

[[track]]
path = "ssh://nas/Volumes/Music/Blade Runner/01 - Prologue.mp3"
title = "Prologue And Main Titles"

[[track]]
path = "ssh://nas/Volumes/Music/Blade Runner/02 - Voight Kampff.mp3"
title = "Voight Kampff Test"
```

## SSH Configuration

cliamp uses the system `ssh` binary. It reads `~/.ssh/config`. Host aliases, keys, ports, and ProxyJump work automatically:

```
# ~/.ssh/config
Host nas
    HostName 192.168.1.50
    User music
    IdentityFile ~/.ssh/nas_key

Host mac-mini-ts
    HostName 100.64.0.5
```

## Supported Formats

SSH streaming supports formats that native decoders support:

- `.mp3` (native decoder)
- `.flac` (native decoder)
- `.ogg` / `.opus` (native decoder)
- `.wav` (native decoder)

Formats that require ffmpeg (`.m4a`, `.wma`) might not work over SSH because the ffmpeg decoder expects a seekable file.

## Error Handling

| Scenario | Behavior |
|----------|----------|
| Host unreachable | The player shows an error and advances to the next track. |
| Auth failure | SSH uses `BatchMode=yes` and does not wait for password prompts. |
| Connection drops mid-stream | The player detects EOF and advances to the next track. |
| Unknown host key | The connection is rejected. Add the host to `~/.ssh/known_hosts` first, or configure it in `~/.ssh/config`. |

## Mixing Local and SSH Tracks

A playlist can contain local and SSH paths:

```toml
name = "Mixed"

[[track]]
path = "/local/path/track1.mp3"
title = "Local Track"

[[track]]
path = "ssh://nas/remote/path/track2.mp3"
title = "Remote Track"
```

### Tidal Integration

URL: https://docs.cliamp.stream/docs/cliamp/tidal

Use cliamp to stream your [Tidal](https://tidal.com/) library through its audio pipeline. EQ, the visualizer, and other effects apply. You need a paid Tidal subscription. Every paid plan includes lossless FLAC.

Tidal delivers lossless FLAC. cliamp uses the same buffer-while-playing and `ffmpeg` pipeline as other lossless providers. Put `ffmpeg` on `PATH`.

## Setup

Run `cliamp setup` for the fastest setup. Select **Tidal**, select a stream quality, and let the wizard write the `[tidal]` block.

Or configure Tidal in `~/.config/cliamp/config.toml`:

```toml
[tidal]
enabled = true
quality = "lossless"
```

You do not need developer credentials. cliamp includes OAuth client credentials.

Run `cliamp`, select Tidal, and press `Enter` to sign in. cliamp shows a `link.tidal.com` URL and a short device code. It also opens the URL in a browser. Approve the device there. cliamp waits for up to 5 minutes. After authorization, cliamp stores credentials in `~/.config/cliamp/tidal_credentials.json`. Later launches refresh them without a message.

### Quality

`quality` selects the Tidal stream tier. If you omit it, cliamp uses `"lossless"`. Supported values:

| Value | Format |
|---|---|
| `"low"` | AAC 96 kbps |
| `"high"` | AAC 320 kbps |
| `"lossless"` / `"hires"` | FLAC up to 24-bit / 192 kHz where available (see note) |

> **FLAC availability note:** Tidal serves FLAC to third-party clients of this type only for tracks with a hi-res ("Max") master. It delivers these tracks as unencrypted MPEG-DASH. cliamp plays them natively at full hi-res quality. For a track without a hi-res master, Tidal downgrades this client to AAC 320 on the server. The python-tidal ecosystem reports the same limit. cliamp shows a one-time footer notice. Sign-in through the Tidal Android-type (PKCE) client, which unlocks FLAC for the full catalog, is planned.

Any other value uses `"lossless"`.

For hi-res playback settings, see [audio-quality.md](https://whiterose.org.contextowl.co/docs/audio-quality). Use `bit_depth = 32` with a matching `sample_rate` for lossless playback.

### Custom client credentials

The cliamp OAuth client credentials are shared with other open-source Tidal clients. Tidal sometimes revokes these client IDs. If sign-in fails with a client error, set a new pair without waiting for a cliamp release:

```toml
[tidal]
client_id = "your-client-id"
client_secret = "your-client-secret"
```

After you change credentials, run `cliamp tidal reset` and sign in again.

## Usage

Start cliamp with Tidal selected:

```sh
cliamp --provider tidal
```

After authentication, Tidal appears in the provider list. Press `T` to select Tidal. Press `Esc`/`b` to open the provider browser and select it.

The provider shows your Tidal library:

- **Favorite Tracks**: your liked songs (up to 500).
- **Your playlists**: playlists you created or subscribed to.
- **Favorite albums**: browsable in the album view.
- **Favorite artists**: browse an artist to see their albums.

Press `Ctrl+F` while Tidal is active to search the Tidal catalog for tracks and albums. Album results appear first. When you select an album, it expands to its track list. Enter plays, `a` appends, and `q` queues the next track.

## Controls

When focused on the provider panel:

| Key | Action |
|---|---|
| `Up` `Down` / `j` `k` | Navigate |
| `Enter` | Load the selected playlist/album or play the selected track |
| `Ctrl+F` | Search Tidal (tracks and albums) |
| `Ctrl+R` | Refresh (re-resolves stream URLs) |
| `Tab` | Switch between provider and playlist focus |
| `Esc` / `b` | Open provider browser |

After you load a playlist or album, cliamp returns to the standard playlist view. Use the usual controls for seek, volume, EQ, shuffle, repeat, queue, search, and lyrics.

## Troubleshooting

- **Sign-in fails immediately / "client_id may be revoked"**: Tidal sometimes revokes the shared cliamp client credentials. Set `client_id` and `client_secret` in `[tidal]`, run `cliamp tidal reset`, and sign in again.
- **Device code expired**: The `link.tidal.com` code is valid for about 5 minutes. Press `Enter` on the Tidal provider again to get a new code.
- **Re-authenticate**: Run `cliamp tidal reset` to clear stored credentials. Then restart cliamp, select Tidal, and sign in again. This is the same as deleting `~/.config/cliamp/tidal_credentials.json`.
- **Track is unplayable / skipped**: The track might not stream in the region, or its stream might be encrypted for this client type. cliamp marks the track unplayable and continues.
- **"delivered as HIGH (AAC)" notice**: The track has no hi-res master, so Tidal does not send FLAC to this client type. See the FLAC availability note. Playback continues at AAC 320.
- **Long-idle sessions**: cliamp resolves stream URLs when each track starts. Queued tracks continue after an idle period without manual refresh. `Ctrl+R` gets the playlist lists again.

## Requirements

- A paid Tidal subscription
- `ffmpeg` on `PATH` for FLAC/AAC decoding
- No developer/API registration: cliamp uses built-in credentials automatically

## A note on the API

cliamp uses the Tidal private client API, like open-source python-tidal-based clients. The official Tidal developer API allows only 30-second previews for third-party apps. cliamp only streams. It does not write decoded audio to disk.

### Mixcloud Integration

URL: https://docs.cliamp.stream/docs/cliamp/mixcloud

Enable [Mixcloud](https://www.mixcloud.com) to browse catalog metadata through
the Mixcloud public JSON API. Playback uses the existing `yt-dlp` and FFmpeg
pipeline. Put `yt-dlp` and `ffmpeg` on `PATH`.

## Feature summary

| Feature | Requirement | Where to use it |
|---|---|---|
| Direct Mixcloud show URL playback | `yt-dlp`; provider need not be enabled | Pass the URL to `cliamp` or press `u` |
| Recent releases, popular shows, show browsing, and show search | `[mixcloud] enabled = true` | Provider pane, `N`, or `Ctrl+F` |
| Live category catalogue and Latest/Popular genre charts | Provider enabled | **Genres** in the provider pane or `N` browser |
| Genre/tag search and local genre favorites | Provider enabled and writable config file | `/`, `Enter`, and `f` in **Genres** |
| Public profile activity, uploads, show favorites, listening history, and collections | Public profile `username`, or an `access_token` | **Your Mixcloud** and **Collections** sections |
| Following stream and followed-creator browser | Public profile `username`, or an `access_token` | **Stream (Following Releases)** and **Creators** |
| Open a highlighted show's creator Uploads/Favorites | Provider enabled; account not required | Press `N` on a Mixcloud show |
| Listen Later | Developer OAuth `access_token` | **Your Mixcloud** section |
| Signed-in or subscriber-gated playback | `cookies_from` for a supported browser with a Mixcloud session | Playback through yt-dlp |
| Exclusive-show warning | Provider enabled | `[E]` suffix on show rows |
| Resume and seek-by-restart for finite shows | Playable finite Mixcloud show | Normal cliamp seek keys and clean-exit resume |

The provider does not implement Mixcloud write actions. You cannot follow a
creator, favorite or repost a show, edit a collection, or upload. The
**Favorites** lists are read-only. Genre favorites are a separate local cliamp
feature described below.

## Setup

Run the setup wizard. Select **Mixcloud**:

```sh
cliamp setup
```

Public discovery does not need an account. Use this minimal manual
configuration:

```toml
[mixcloud]
enabled = true
```

Add a public username to show account views:

```toml
[mixcloud]
enabled = true
username = "your-mixcloud-username"
```

Use the username from the public profile URL. Do not use an email address or
display label. Keep the spelling from
`https://www.mixcloud.com/<username>/`.

To start with Mixcloud, also set the top-level provider option:

```toml
provider = "mixcloud"
```

## Provider pane

Press `X` to select Mixcloud. The provider pane has these sections.

| Section | Entry | Behaviour |
|---|---|---|
| **Your Mixcloud** | **Stream (Following Releases)** | Merges recent uploads from followed creators. See [Limits and tuning](#limits-and-tuning). |
| **Your Mixcloud** | **Favorites** | Reads the configured public account or the token owner `/me/` connections |
| **Your Mixcloud** | **Creators** | Lists the configured account and followed creators. Separates each creator **Uploads** and **Favorites**. |
| **Your Mixcloud** | **Uploads**, **Profile Activity**, **Listening History** | Reads the configured public account or the token owner `/me/` connections |
| **Your Mixcloud** | **Listen Later** | Appears only when `access_token` is set |
| **Browse** | **Shows** | Opens the global show catalogue. Sort by Recent Releases, Popular, or each configured style. |
| **Browse** | **Genres** | Loads the current Mixcloud category catalogue, shows local favorite state, and opens Latest or Popular shows for a category |
| **Collections** | One row per collection | Reads all collections for the account and shows the API track count |
| **Discover** | **Recent Releases**, **Popular** | Global public discovery. No account required. |
| **Music Styles** | `<Style> — Latest`, `<Style> — Popular` | One pair for each entry in `[mixcloud].styles` |

With a configured account, **Your Mixcloud** is first. It lists **Stream**,
then **Favorites**, then **Creators**. Public-only and degraded-account views
start with **Browse** and omit **Creators**. The hierarchy rows are shortcuts.
When you back out of the top-level Shows, Creators, or Genres list, cliamp
returns to this provider pane.

Select a **Show**, creator **Uploads** or **Favorites**, or genre **Latest** or
**Popular** view. cliamp loads the results in the main playlist and closes the
provider browser. For empty results, cliamp keeps the playlist and browser open
and shows a warning.

`Ctrl+R` reloads provider lists and clears the cached `/me/` identity. cliamp
otherwise gets show, category, collection, and account results when you open
them. It does not retain them as an expiring audio-URL cache.

If account resolution or collection loading fails, cliamp shows a warning. A
mistyped username, expired token, or API rate limit can cause this. cliamp then
temporarily omits **Your Mixcloud** and **Collections**. Public **Browse**,
**Discover**, and **Music Styles** entries remain available.

## Hierarchical browsing and controls

Press `N` with no recognized Mixcloud show selected to open the normal provider
browser. Mixcloud has four routes:

- **By Show** browses the global show catalogue. Press `s` to cycle Recent
  Releases, Popular, and Latest/Popular for each configured style.
- **By Creator** selects a creator and combines creator Uploads and Favorites
  into a track list.
- **By Creator / Show** selects a creator, then loads an **Uploads** or
  **Favorites** collection into the main playlist.
- **Genres** browses and searches categories, then loads Latest or Popular into
  the main playlist.

The creator list contains the configured account and followed creators. Both
creator routes need `username` or `access_token`. **By Show** and **Genres** are
public. Breadcrumbs use the Mixcloud terms **Creator** and **Show** to show the
current route.

When a Mixcloud show is selected in the main playlist, `N` becomes
**Browse creator**. It opens that show creator and the separate Uploads/Favorites
choices. This works even when you do not follow the creator. `Esc` returns to
the normal browse menu. Press `Esc` again to return to the source playlist.
Browsing through **Shows**, **Creators**, **Genres**, or the normal `N` menu
uses one-level back navigation.

| Key | Mixcloud action |
|---|---|
| `X` | Open the Mixcloud provider |
| `N` | Open the browse menu, or open the selected Mixcloud show creator |
| `Ctrl+F` | Search Mixcloud shows from the provider pane or browser |
| `/` | Filter the visible creator, show, genre, sort, or track list |
| `Enter` while filtering **Genres** | Replace the local category filter with a Mixcloud server tag search |
| `f` in the **Genres** list | Add or remove the selected genre from local Mixcloud favorites |
| `s` in the global show list | Cycle Recent, Popular, and configured-style show views |
| `Enter` / `→` / `l` | Drill in. On a track row, play it and queue the remaining visible rows. |
| `a` | Append visible browser tracks to the queue |
| `q` on a browser track | Queue the selected show to play next |
| `R` on browser tracks | Replace the queue with visible shows, with confirmation when needed |
| `Esc` / `←` / `h` / `b` | Go back one level or close the browser |
| `Ctrl+R` in the provider pane | Refresh Mixcloud lists and account identity |
| `u` | Paste a Mixcloud show URL |
| `Ctrl+S` | Save or download the current show through the cliamp track-save flow |

Search and browse result lists use the normal cliamp filter, append, play,
queue-next, and replace-queue actions.

## Genre browsing and favorites

cliamp loads **Genres** from the current Mixcloud public category catalogue. A
row shows `★` when a genre is in `[mixcloud].styles` and `☆` when it is not.
cliamp shows Mixcloud category groups, such as Music or Talk, next to the
category name.

Type after `/` to filter the loaded catalogue by category name or group. Press
`Enter` to submit the same text to the Mixcloud tag search. It can find
categories outside the initial catalogue. Select a category or search result to
open **Latest** and **Popular** show lists.

Press `f` on a genre to change its star. cliamp then:

1. Atomically rewrites only `styles` in the `[mixcloud]` config section.
2. Preserves other Mixcloud settings, comments, and unrelated sections.
3. Updates the in-memory favorite state.
4. Refreshes **Music Styles** provider rows. It adds or removes that genre Latest/Popular pair.

This is a local cliamp preference and does not need an access token. It does not
favorite anything on the Mixcloud website. If config write fails, cliamp keeps
the previous UI and configuration state.

The default styles are ambient, chillout, deep house, disco, drum and bass,
electronica, funk, hip-hop, house, jazz, reggae, soul, techno, trance, and
world. Override them with Mixcloud genre slugs:

```toml
[mixcloud]
enabled = true
styles = ["ambient", "balearic", "deep-house", "jazz"]
```

Omit `styles` to use defaults. Set `styles = []` to start with no favorite genres
and no **Music Styles** rows. The live **Genres** catalogue remains available,
so you can add styles again with `f`. cliamp normalizes values to lowercase
hyphenated slugs and removes duplicates.

### Favorite terminology

Mixcloud has several similarly named concepts:

- **Your Mixcloud / Favorites** reads shows that the configured account favorited.
- **Creator / Favorites** reads public show favorites for a selected creator.
- `f` on a show in the cliamp main playlist changes a local cliamp track bookmark.
- `f` in **Genres** changes a local Mixcloud style in `[mixcloud].styles`.

None of these controls writes a show favorite to Mixcloud.

## Account identity and authentication

Mixcloud allows public API reads without authentication. cliamp supports four
configuration levels:

| Configuration | Purpose |
|---|---|
| `enabled = true` | Public discovery, shows, genres, genre/tag search, and show search |
| `username` | Public account connections: following, activity, uploads, show favorites, listening history, and collections |
| `access_token` | Resolves the authorized user through `/me/` and adds Listen Later |
| `cookies_from` | Gives yt-dlp a signed-in browser session for playback only |

If both `username` and `access_token` are set, the access-token owner `/me/`
identity controls all account views. This prevents a stale or different public
username from mixing two accounts in one menu.

Browser cookies do not authenticate the JSON API, reveal private library data,
or replace a developer token. cliamp has no generic "logged in" badge for
cookie playback. It reads cookies only when yt-dlp starts a show.

## Access token and Listen Later

A developer OAuth access token enables `/me/` account resolution and the
read-only **Listen Later** view:

```toml
[mixcloud]
enabled = true
access_token = "${MIXCLOUD_ACCESS_TOKEN}"
```

Create an application and get a token through the Mixcloud browser OAuth flow.
See the [official API documentation](https://www.mixcloud.com/developers/).
cliamp does not request or store the application client secret. Treat the access
token as a secret. Environment interpolation keeps it out of `config.toml`.

cliamp uses the access token only for API metadata. It never adds it to playable
show URLs or passes it to yt-dlp. The Mixcloud API has write endpoints for
following, favoriting, reposting, and Listen Later. cliamp does not call them.

## Signed-in playback

Public shows normally play without authentication. To give yt-dlp the same
Mixcloud session as the browser for subscriber-only or other gated content,
configure a browser cookie source:

```toml
[mixcloud]
enabled = true
username = "your-mixcloud-username"
cookies_from = "firefox" # brave, chrome, chromium, edge, firefox, opera, safari, vivaldi, whale
```

cliamp passes `cookies_from` to the yt-dlp `--cookies-from-browser` option. The
installed yt-dlp version can also support custom profiles such as
`chrome:Profile 1` or `firefox:default-release`. Run `yt-dlp --help` and inspect
`--cookies-from-browser` for the current list.

yt-dlp does not currently expose Arc as a separate cookie source. Select a
supported browser where you are signed in to Mixcloud. On macOS, an
`Operation not permitted` error while reading `~/Library` means that the terminal
app that starts cliamp needs Full Disk Access. Restart the terminal after you
grant it.

cliamp selects yt-dlp cookies by service URL. Mixcloud can use a different
browser or profile from SoundCloud, NetEase, or YouTube. One provider does not
override another provider session.

Shows that Mixcloud flags as exclusive have an `[E]` suffix in the cliamp UI.
This presentation marker is not written to exported playlists, IPC output, or
Now Playing metadata. It is a warning, not an automatic skip. A signed-in user
may have access through a subscription. Another account gets the Mixcloud
restricted-show error when playback starts. cliamp cannot determine access from
public metadata, so it does not filter these rows.

## Direct URLs and playback metadata

Direct show URLs work anywhere cliamp accepts a URL, even when the provider is
not enabled:

```sh
cliamp https://www.mixcloud.com/creator/show-name/
```

In the TUI, press `u` and paste the same URL. Provider-generated queue entries
also store stable `https://www.mixcloud.com/<creator>/<show>/` page URLs. yt-dlp
resolves the current media URL only when playback starts. An idle or long queue
does not retain expired CDN URLs.

Mixcloud tracks contain the show title, creator, duration, publication year,
category tags, and the best image URL that the API returns. cliamp uses these
fields in track rows, the metadata view, IPC, and desktop media integration.

## Resume and seeking

When cliamp exits cleanly during a finite Mixcloud show, it saves the current
position. When cliamp next plays that show, it restarts the yt-dlp and FFmpeg
pipeline at the saved position. This also applies to shows first opened in the
provider browser. cliamp does not record live shows or failed or unstarted
playback.

Seek and resume can take several seconds. They start a replacement pipeline
instead of moving an in-memory decoder. cliamp combines several rapid seek
presses before it restarts.

The Mixcloud website and official widget limit fast-forward and rewind for some
accounts. cliamp does not call the widget seek operation. It restarts the same
playable media and asks FFmpeg to discard input before the target timestamp. The
website seek allowance is not available to cliamp. A large jump can take longer
while the replacement pipeline catches up.
See [Mixcloud's playback-limits article](https://help.mixcloud.com/hc/en-us/articles/360004054059-Why-are-there-limits-for-rewinds-and-fast-forwards)
and the [`seek` result in its Widget API](https://www.mixcloud.com/developers/widget/).

If Mixcloud, yt-dlp, or FFmpeg cannot create the replacement, cliamp restores
the existing pipeline and continues at the previous position. It does not leave
the player silent.

## Configuration reference

| Key | Default | Meaning |
|---|---|---|
| `enabled` | `false` | Registers the Mixcloud provider |
| `username` | empty | Public profile URL username for account views when no token is set |
| `access_token` | empty | Developer OAuth token for `/me/` and Listen Later |
| `cookies_from` | empty | Browser/profile sent to yt-dlp for signed-in playback |
| `styles` | cliamp default style list | Local genre favorites. Each produces Latest and Popular provider rows and show sort modes. |
| `max_items` | `100` | Maximum shows, creators, or collections per view. Setup accepts 1 to 500. Manual values at or below zero use the default. Values above 500 use 500. |
| `stream_creators` | `20` | Maximum followed creators for the following stream. Setup accepts 1 to 100. Manual values at or below zero use the default. Values above 100 use 100. |

Use this complete example:

```toml
provider = "mixcloud"

[mixcloud]
enabled = true
username = "your-mixcloud-username"
access_token = "${MIXCLOUD_ACCESS_TOKEN}"
cookies_from = "firefox"
styles = ["chillout", "deep-house", "drum-bass", "electronica", "house", "techno"]
max_items = 100
stream_creators = 20
```

## Limits and tuning

The API does not expose the exact personalized Mixcloud website home feed.
**Stream (Following Releases)** is an approximation. It gets the first
`stream_creators` followed accounts, merges their newest uploads, sorts by
publication time, removes duplicates, and returns at most `max_items` shows.
Lower these values if you encounter API rate limits. cliamp includes the
Mixcloud `Retry-After` value in the error it shows.

Mixcloud does not provide audio streams through its JSON API. The official
third-party playback method is the visible web widget. Terminal playback depends
on the yt-dlp Mixcloud extractor. It is not a Mixcloud-supported API and can
break when the website changes. Keep yt-dlp current. Use this integration only
where Mixcloud terms and content rights permit it.

The cliamp provider contract has no generic UI for Mixcloud write actions. You
cannot follow, favorite a show, repost, change Listen Later, upload, comment,
or edit collections. Mixcloud Live is not available. Show search uses Mixcloud
cloudcast search. Creator discovery uses followed creators and selected-show
jumps. Genre discovery uses the category and tag APIs.

### Navidrome Integration

URL: https://docs.cliamp.stream/docs/cliamp/navidrome-integration

Use Cliamp to connect to a [Navidrome](https://www.navidrome.org/) server and stream music from your library. Navidrome is a self-hosted music server that supports the Subsonic API.

> **Quick start:** Run `cliamp setup`. Enter the server URL, username, and password. The TUI validates the connection and writes the `[navidrome]` block. Manual steps follow.

## Setup

Set these three environment variables before you start Cliamp:

```sh
export NAVIDROME_URL="http://your-server:4533"
export NAVIDROME_USER="your-username"
export NAVIDROME_PASS="your-password"
```

Then start Cliamp without file arguments:

```sh
cliamp
```

You can combine local files with a Navidrome session:

```sh
NAVIDROME_URL=http://localhost:4533 NAVIDROME_USER=admin NAVIDROME_PASS=secret cliamp ~/Music/extra.mp3
```

## How It Works

When these environment variables are set, Cliamp authenticates with the Navidrome server through the Subsonic API. At startup, it gets playlists and shows them in the TUI.

Use the arrow keys to browse playlists. Press Enter to load one. Cliamp adds its tracks to the local playlist and starts playback. The server streams audio as MP3.

## Controls

When focused on the provider panel:

| Key | Action |
|---|---|
| `Up` `Down` / `j` `k` | Navigate playlists |
| `Enter` | Load the selected playlist |
| `Tab` | Switch between provider and playlist focus |
| `N` | Open the Navidrome browser |

After you load a playlist, Cliamp returns to the standard playlist view. Use the usual controls for seek, volume, EQ, shuffle, repeat, queue, and search.

## Navidrome Browser

Press `N` at any time, or from the provider panel, to open the full-screen Navidrome browser. Browse the library in three modes:

- **By Album**: Browse a paginated list of albums. Open an album to view its tracks.
- **By Artist**: Browse artists. Select an artist to load tracks from all albums, grouped by album with separator headers.
- **By Artist / Album**: Browse artist, album list, then track list.

### Browser controls

**Mode menu:**

| Key | Action |
|---|---|
| `↑` `↓` / `j` `k` | Navigate |
| `Enter` | Select mode |
| `Esc` / `N` | Close browser |

**Artist or album list:**

| Key | Action |
|---|---|
| `↑` `↓` / `j` `k` | Navigate |
| `Enter` / `→` | Drill in |
| `s` | Cycle album sort order (album list only) |
| `Esc` / `←` | Back |

**Track list:**

| Key | Action |
|---|---|
| `↑` `↓` / `j` `k` | Navigate |
| `Enter` | Append selected track to playlist |
| `a` | Append all tracks to playlist |
| `R` | Replace playlist with all tracks and start playing |
| `Esc` / `←` | Back |

### Album sort order

In the global album list, press `s` to cycle through sort modes:

| Value | Description |
|---|---|
| `alphabeticalByName` | A to Z by album title (default) |
| `alphabeticalByArtist` | A to Z by artist name |
| `newest` | Most recently added |
| `recent` | Most recently played |
| `frequent` | Most frequently played |
| `starred` | Starred / favourited |
| `byYear` | Chronological by release year |
| `byGenre` | Grouped by genre |

Cliamp saves the selected sort as `browse_sort` in the `[navidrome]` section of `~/.config/cliamp/config.toml`. It restores the sort at the next start.

## Architecture

The integration uses a `Provider` interface in the `playlist` package:

```go
type Provider interface {
    Name() string
    Playlists() ([]PlaylistInfo, error)
    Tracks(playlistID string) ([]Track, error)
}
```

The Navidrome client (`external/navidrome/client.go`) implements this interface. It creates authenticated Subsonic API requests with MD5 token authentication (password + random salt). It parses JSON responses into playlist and track structs.

Bubbletea commands get playlists and tracks asynchronously. The UI remains responsive while the server responds.

To support another Subsonic-compatible server, such as Airsonic or Gonic, implement the same `Provider` interface for that server API.

## Requirements

You need only a running Navidrome instance. The client uses the Go standard `net/http` and `crypto/md5` packages. The Navidrome server must have the Subsonic API enabled. This is the default.

### Jellyfin

URL: https://docs.cliamp.stream/docs/cliamp/jellyfin

Use cliamp to stream music from a Jellyfin server through Jellyfin's authenticated HTTP API. The provider pane shows music libraries as a flat album list, like the Plex provider.

> **Quick start:** Run `cliamp setup`. Select API-token or username+password authentication. The TUI validates `/Users/Me` and writes the `[jellyfin]` block. Manual steps follow.

## Prerequisites

- A reachable Jellyfin server
- At least one library with `CollectionType = music`
- A Jellyfin API token

## Configuration

Add a `[jellyfin]` section to `~/.config/cliamp/config.toml`:

```toml
[jellyfin]
url = "https://jellyfin.example.com"
user = "finamp"
password = "your_password_here"
# optional alternatives:
# token = "xxxxxxxxxxxxxxxxxxxx"
# user_id = "00000000000000000000000000000000"
```

| Key | Description |
|-----|-------------|
| `url` | Base URL of your Jellyfin server |
| `user` | Jellyfin username for password-based login |
| `password` | Jellyfin password for password login |
| `token` | Optional Jellyfin API token. Use it instead of a username and password. |
| `user_id` | Optional Jellyfin user id to skip discovery |

## Usage

After configuration, **Jellyfin** appears in the provider list.

To start cliamp with Jellyfin selected:

```bash
cliamp --provider jellyfin
```

Or set the provider in configuration:

```toml
provider = "jellyfin"
```

The provider shows a flat album list:

```text
Artist - Album Title (Year)
```

Select an album to load its tracks.

## How it works

cliamp authenticates with a configured token or the supplied username and password. It resolves the active Jellyfin user, lists music library views, gets albums from those views, then gets tracks for the selected album. Playback uses Jellyfin's authenticated audio endpoint and streams through the cliamp HTTP pipeline.

## Known limitations

- **Album list is flat**: Artist drill-down is not available.
- **No scrobbling/write-back**: cliamp does not report plays to Jellyfin.
- **Token-based access**: Store the API token safely.

### Plex Media Server

URL: https://docs.cliamp.stream/docs/cliamp/plex-media-server

Use cliamp to stream music from Plex Media Server, including any library served by PlexAmp. Streaming uses the Plex HTTP API. You do not need extra software.

> **Quick start:** Run `cliamp setup`. Enter the server URL and `X-Plex-Token`. The TUI checks the token and writes the `[plex]` block. Manual steps follow.

## Prerequisites

- Plex Media Server running and reachable on your network (or remotely)
- At least one music library configured in Plex
- Your `X-Plex-Token` (see below)

## Finding your X-Plex-Token

1. Open Plex Web in a browser and sign in.
2. Browse to an item in the music library.
3. Click the **···** menu → **Get Info** → **View XML**.
4. Copy the `X-Plex-Token` query parameter value from the XML page URL.

You can also follow the [official Plex guide](https://support.plex.tv/articles/204059436-finding-an-authentication-token-x-plex-token/).

## Configuration

Add a `[plex]` section to `~/.config/cliamp/config.toml`:

```toml
[plex]
url   = "http://192.168.1.10:32400"
token = "xxxxxxxxxxxxxxxxxxxx"
libraries = ["Music", "Jazz"]
```

| Key | Description |
|-----|-------------|
| `url` | Plex Media Server base URL, including port (default `32400`) |
| `token` | `X-Plex-Token` for authentication |
| `libraries` | Optional comma-separated music library names to load. If omitted, cliamp loads all music libraries. Name matching is case-insensitive. |

If you access Plex remotely through `app.plex.tv`, use a direct server URL when remote access is enabled. You can also use the server `plex.direct` URL from the Plex Web address bar.

## Usage

After configuration, **Plex** appears in the cliamp provider list.

The provider shows audio playlists and the music library under two headers:

```text
── Playlists ──
GOOD
All Music
drums

── Albums ──
Artist - Album Title (Year)
```

Select a playlist or album to load its tracks. Smart playlists are included. They resolve to current server content.

Start cliamp with Plex as the default provider:

```bash
cliamp --provider plex
```

Or set it in configuration:

```toml
provider = "plex"
```

## How it works

cliamp calls the Plex HTTP API to list audio playlists (`/playlists`) and music library albums. When you select an entry, cliamp gets its track list from the playlist-items or album-children endpoint. It then creates authenticated streaming URLs in this form:

```
http://<server>:32400/library/parts/<partID>/<timestamp>/file.<ext>?X-Plex-Token=<token>
```

These URLs serve files directly. Plex serves the original file without transcoding. cliamp handles playback through its HTTP streaming pipeline. cliamp can play MP3, FLAC, AAC, OGG, OPUS, WAV, and other supported source formats.

## Troubleshooting

### macOS: `dial tcp ... connect: no route to host`

If cliamp reports `no route to host` for a Plex server on the LAN, but `curl` works with the same URL, macOS likely denies Local Network access to the app. macOS blocks the connection before it sends a packet and reports a routing error.

Fix: Open **System Settings > Privacy & Security > Local Network**. Enable access for the terminal app, such as Terminal, iTerm2, or Ghostty. Then restart cliamp. If the terminal is not listed, turn an entry off and on. Or reset the permission database with `tccutil reset All`, then restart the terminal so macOS prompts again.

## Known limitations

- **No scrobbling**: cliamp does not report play counts to Plex.
- **No playlist write-back**: cliamp cannot create or change Plex playlists.
- **Token is long-lived**: Store it safely. It gives full access to the Plex account.
- **Album list is flat**: Artist drill-down is not available. Search by scrolling or with cliamp search.

### Emby

URL: https://docs.cliamp.stream/docs/cliamp/emby

Use cliamp to stream music from an Emby server through Emby's authenticated HTTP API. The provider pane shows music libraries as a flat album list, like the Jellyfin and Plex providers.

> **Quick start:** Run `cliamp setup`. Select API-key or username+password authentication. The TUI validates `/System/Info` and writes the `[emby]` block. Manual steps follow.

## Prerequisites

- A reachable Emby server
- At least one library with `CollectionType = music`
- An Emby API key or user credentials

## Configuration

Add an `[emby]` section to `~/.config/cliamp/config.toml`:

```toml
[emby]
url = "https://emby.example.com"
user = "alice"
password = "your_password_here"
# optional alternatives:
# token = "xxxxxxxxxxxxxxxxxxxx"
# user_id = "00000000000000000000000000000000"
```

| Key | Description |
|-----|-------------|
| `url` | Base URL of your Emby server |
| `user` | Emby username. Use it for password login and to select the account for an API key. |
| `password` | Emby password for password login |
| `token` | Emby API key. Use it instead of a username and password. |
| `user_id` | Optional Emby user id to skip discovery |

## Usage

After configuration, **Emby** appears in the provider list.

To start cliamp with Emby selected:

```bash
cliamp --provider emby
```

Or set the provider in configuration:

```toml
provider = "emby"
```

The provider shows a flat album list:

```text
Artist — Album Title (Year)
```

Select an album to load its tracks. Press `E` to select Emby.

## How it works

cliamp authenticates with an API key or the supplied username and password. It resolves the active Emby user, lists music library views, gets albums from those views, then gets tracks for the selected album. Playback uses Emby's authenticated download endpoint and streams through the cliamp HTTP pipeline.

## Known limitations

- **Album list is flat**: Artist drill-down is not available.
- **Token-based access**: Store the API key safely.
- **API key user selection**: Emby API keys apply to the server and have no "current user". Without `user`, cliamp selects the first user returned by `/Users`. This is correct for a single-user server. On a multi-user server, set `user_id` in `[emby]` to select an account.

### Lyrion Music Server Integration

URL: https://docs.cliamp.stream/docs/cliamp/lyrion-music-server

Use Cliamp to connect to a [Lyrion Music Server](https://lyrion.org/) (LMS, formerly Logitech Media Server) and stream music from your library. LMS is a self-hosted server for the Squeezebox ecosystem.

> **Quick start:** Run `cliamp setup`. Enter the server URL and optional credentials. The TUI validates the connection and writes the `[lyrion]` block. Manual steps follow.

## Setup

Add a `[lyrion]` block to `~/.config/cliamp/config.toml`:

```toml
[lyrion]
url = "http://nas.local:9000"
```

Port 9000 is the LMS default. It is the web interface port, not the 9090 CLI port.

If the server has password protection enabled (Settings → Advanced → Security), add credentials:

```toml
[lyrion]
url      = "http://nas.local:9000"
user     = "your-username"
password = "your-password"
```

To keep the password out of the file, use `$VAR` interpolation. The configuration supports it for every string value:

```toml
[lyrion]
url      = "http://nas.local:9000"
user     = "your-username"
password = "${LYRION_PASSWORD}"
```

### Environment variables

If there is no `[lyrion]` block, Cliamp uses environment variables. Only the URL is required:

```sh
export LYRION_URL="http://nas.local:9000"
export LYRION_USER="your-username"   # only if password protection is on
export LYRION_PASS="your-password"
```

A configured `[lyrion]` block takes precedence over these variables.

## How It Works

Cliamp queries the library through the LMS JSON-RPC endpoint (`POST /jsonrpc.js`). It plays tracks from the HTTP file endpoint (`/music/<track_id>/download`). Playback uses Cliamp's audio engine.

Lyrion has no dedicated shortcut key. Press `Esc` to open the provider list and select it. Or set it as the startup provider with `cliamp --provider lyrion` or `provider = "lyrion"` in `config.toml`.

Use the arrow keys to browse playlists. Press Enter to load one.

**Press `N` to open the artist/album browser.** The provider pane lists only server *saved playlists*. The browser lists music files by artist and album.

Press `Ctrl+F` to search the library through the server. Use it from the playlist view or browser.

## Limitations

Cliamp is **not** a Squeezebox player. It reads the library from LMS and plays files itself. It does not register as an LMS endpoint. This has three effects:

- **No play history in LMS.** LMS records play counts and "last played" for a player that plays a track. Cliamp does not drive an LMS player, so listening with Cliamp leaves no record on the server. This is expected behavior.
- **No synchronization or multi-room.** Cliamp cannot join an LMS sync group. Other LMS controllers cannot see or control Cliamp. For this feature, run a Squeezebox player such as [squeezelite](https://github.com/ralph-irving/squeezelite).
- **No server-side transcoding.** Cliamp downloads the original file and decodes it locally. A format that Cliamp cannot decode cannot play, even if LMS could transcode it. Install `ffmpeg` to decode more formats.

### Tracks added by server plugins

LMS plugins that add streaming services, such as Spotty for Spotify, add their tracks to the library with local files. LMS serves only *file-backed* tracks through the endpoint that Cliamp uses. LMS accepts a download request for a plugin track but might not send audio. Playback then hangs.

**Cliamp hides these by default.** It also hides a saved playlist that a plugin imported. Such a playlist contains only plugin tracks and would otherwise open empty. This avoids unusable entries on a server with a large Spotty library.

To show them as unplayable entries that cliamp skips during playback:

```toml
[lyrion]
url             = "http://nas.local:9000"
show_unplayable = true
```

Set `LYRION_SHOW_UNPLAYABLE=true` for the same behavior with environment configuration.

An *album* that contains only plugin tracks still appears in the browser and opens empty. Cliamp filters playlists because the server reports their origin in the same response. Classifying albums would need one extra request per album.

To play these services, use the Cliamp Spotify, Qobuz, or Tidal provider. Each connects directly to its service protocol.

## Security

With credentials, Cliamp uses HTTP Basic authentication. The LMS web interface uses the same scheme. Plain HTTP sends reusable credentials with every request. Use it only on a trusted LAN. If the server is available outside the network, put it behind HTTPS and use an `https://` URL.

## Troubleshooting

**The provider does not appear.** Cliamp creates the provider only when a URL is configured. Check that `[lyrion]` sets `url`, or that the shell that starts Cliamp exports `LYRION_URL`.

**"authentication failed".** The server rejected the credentials. Check the username and password in the LMS web interface. If the server has no password protection, remove `user` and `password`. Do not leave them blank.

**Connection refused or timed out.** Check the port. LMS serves its web UI and this API on 9000 by default. Open `http://your-server:9000` in a browser to test it.

**Tracks appear but will not play.** Cliamp might not decode the file format. Install `ffmpeg` and try again.

**A playlist or artist is missing.** If it comes from a server plugin instead of local files, cliamp hides it by default. Set `show_unplayable = true` to show it. Showing it does not make it playable.

### Audiobookshelf

URL: https://docs.cliamp.stream/docs/cliamp/audiobookshelf

Use cliamp to play audiobooks and podcasts from a self-hosted [Audiobookshelf](https://www.audiobookshelf.org/) server. Browse authors and books, list podcast shows, and sync listening positions with the server.

> **Quick start:** Run `cliamp setup`. Select API-key or username+password authentication. The TUI validates the connection and writes the `[audiobookshelf]` block. Manual steps follow.

## Prerequisites

- A reachable Audiobookshelf server
- An Audiobookshelf API key, or a username and password

## Configuration

Add an `[audiobookshelf]` section to `~/.config/cliamp/config.toml`:

```toml
[audiobookshelf]
url = "https://abs.example.com"
token = "your-api-key"
# or authenticate with credentials instead of a key:
# user = "listener"
# password = "secret"
# Restrict cliamp to these libraries (default: all):
# libraries = ["Audiobooks", "Podcasts"]
```

| Key | Description |
|-----|-------------|
| `url` | Base URL of your Audiobookshelf server |
| `token` | API key. Create one in the Audiobookshelf web UI under Settings → Users → API Keys. Use this instead of a username and password. |
| `user` | Username for password-based login, used when `token` is not set |
| `password` | Password for password-based login |
| `libraries` | Optional list of library names to restrict cliamp to (default: all) |

Set `token` to authenticate immediately. Set `user` and `password` to sign in on first use.

## Usage

After configuration, **Audiobookshelf** appears in the provider list. Press `B` to select it, or start cliamp with it selected:

```bash
cliamp --provider audiobookshelf
# or the shorter alias
cliamp --provider abs
```

Or set the provider in configuration:

```toml
provider = "audiobookshelf"
```

The provider pane has two sections:

```text
── Audiobooks ──
...every book...
── Podcasts ──
...every podcast show...
```

Select a book to queue one track for each audio file. Select a podcast show to queue one track for each episode, newest first.

Press `N` to open the browse overlay. Browse Authors, Books, then tracks. This provider uses "Authors" and "Books" instead of Artists and Albums. In the album list, cycle through By Title (default), Recently Added, and By Author.

Press `Ctrl+F` to search the configured libraries. cliamp expands each matching book or podcast show into tracks, up to the search-result limit. If the server cannot return tracks for an item, cliamp skips the item. Shorter partial results are not an error.

## Track titles

If a file contains one chapter, cliamp uses the chapter name as its title. Otherwise, it uses the embedded title, then the file name. It uses the book author as the artist and the book title as the album. Podcast episodes use the episode title.

## Progress and resume

cliamp reports the listening position when a track starts, about every 15 seconds during playback, and when a track ends. A book reports its position on the full book timeline. A podcast episode reports its own position. cliamp marks a book or episode finished only when the reported position is within 5 seconds of its total duration. Thus, finishing the last file of a multi-file book finishes the book. Finishing an earlier file does not.

Load a book or podcast show from the provider pane (`B`). cliamp selects the in-progress file or episode and starts at its saved position. For a podcast show, it resumes the newest in-progress episode. An item with no saved progress, or one marked finished, starts at the beginning. If the saved position is past the end of the target file, cliamp starts the file at the beginning. When you play a file again later in the session, cliamp uses the position then reported by the server. This resume behavior applies only to the provider pane. It does not apply when you queue a book or show from the `N` browse overlay.

## How it works

cliamp authenticates with the configured token or username and password. It lists libraries, optionally filters them with `libraries`, then lists their books and podcast shows. Playback uses the Audiobookshelf item-file endpoint and cliamp's buffered download pipeline. Jellyfin, Emby, Plex, and Navidrome stream URLs use the same pipeline. `ffmpeg`-backed formats work the same way.

The buffered pipeline downloads the full stream into memory during playback. It makes no partial-range requests. A book stored as one large file, such as one `.m4b` for the full book, uses memory proportional to its size. Resuming far into that book waits until the download reaches the saved position. Per-chapter files avoid both limits because each file is smaller.

## Troubleshooting

- **Empty provider pane**: Check `url` and either `token` or `user`/`password` in `[audiobookshelf]`.
- **No audio**: Confirm that the server serves the item file endpoint. A proxy or reverse-proxy configuration error is a common cause.
- **Missing chapter titles**: This is expected when a file covers several chapters. cliamp then uses the embedded title or file name.

### Headless Daemon Mode

URL: https://docs.cliamp.stream/docs/cliamp/headless-daemon-mode

Run cliamp without a TUI. The daemon listens on the same Unix socket as the
interactive player. Playback, library, and V2 remote commands work, but cliamp
does not render a terminal UI. Use this mode to control playback through IPC
from a status bar, script, hotkey daemon, or cron job.

```sh
cliamp --daemon                              # no TUI, IPC only
cliamp -d                                    # short form
cliamp --daemon --auto-play --playlist Lofi  # start playing on launch
cliamp --daemon ~/Music --auto-play          # auto-play a directory
```

Send `SIGINT` or `SIGTERM` to stop the daemon. cliamp saves the resume position on a graceful shutdown.

## What works

The daemon exposes the same runtime, library, job, and event IPC interface as the TUI. See [Remote Control](https://whiterose.org.contextowl.co/docs/remote-control-ipc) for the list:

- Playback: `play`, `pause`, `toggle`, `stop`, `next`, `prev`
- Position: `seek`, `volume`, `speed`
- Playback modes: `shuffle`, `repeat`, `mono`
- Library: `load "Name"`, `queue /path/to.mp3`
- Audio: `eq <preset>`, `eq --band N <dB>`, `device <name|list>`
- Status: `status`, `status --json`

## What doesn't

UI-only commands return an error in headless mode:

- `theme`: no UI is available for themes
- `vis`: no visualizer is running

The daemon still enables MPRIS on Linux and NowPlaying on macOS when the platform service is available. You can also bind media keys directly to `cliamp` subcommands. See [Hyprland](#hyprland).

## Use cases

### Background music daemon

Start cliamp once at login, for example with `~/.config/systemd/user/cliamp.service` or desktop-environment autostart. Keep it running. Control it from any terminal:

```sh
cliamp toggle      # play/pause from anywhere
cliamp next
cliamp volume -3
```

Use this minimal systemd user unit:

```ini
[Unit]
Description=cliamp headless music player

[Service]
ExecStart=%h/.local/bin/cliamp --daemon --auto-play --playlist "Lofi"
Restart=on-failure

[Install]
WantedBy=default.target
```

```sh
systemctl --user enable --now cliamp.service
```

### Waybar / Polybar / i3blocks status modules

Poll `cliamp status --json` at an interval. Render the fields that you need.

**Waybar** (`~/.config/waybar/config`):

```jsonc
"custom/cliamp": {
  "exec": "cliamp status --json | jq -r 'if .state == \"playing\" then \"  \" + (.track.title // \"\") else \"\" end'",
  "interval": 2,
  "on-click": "cliamp toggle",
  "on-click-right": "cliamp next",
  "on-scroll-up": "cliamp volume +3",
  "on-scroll-down": "cliamp volume -3"
}
```

**Polybar**:

```ini
[module/cliamp]
type = custom/script
exec = cliamp status --json | jq -r '.track.title // ""'
interval = 2
click-left = cliamp toggle
click-right = cliamp next
```

#### Radio stream metadata

A radio station playlist entry only has the station name. During playback,
`.track` reports the station now-playing metadata. The station sends this data
inline as SHOUTcast/Icecast ICY metadata:

| Field | Description |
|-------|-------------|
| `title` | Current song from the ICY tag. Before it arrives, this is the station name. |
| `artist` | Current artist when the ICY tag uses `"Artist - Title"` |
| `station` | Station name. Present only after a song replaces `title`. |
| `stream_title` | Raw, unsplit ICY value |

A status bar can show the station and song together:

```sh
cliamp status --json | jq -r '(.track // {}) | if .station then (if .artist then "\(.station): \(.artist) - \(.title)" else "\(.station): \(.title)" end) else (.title // "") end'
```

### Hotkeys (window manager / sxhkd / Hyprland)

Bind media keys directly to IPC subcommands.

**Hyprland** (`~/.config/hypr/hyprland.conf`):

```ini
bind = , XF86AudioPlay,  exec, cliamp toggle
bind = , XF86AudioNext,  exec, cliamp next
bind = , XF86AudioPrev,  exec, cliamp prev
bind = , XF86AudioRaiseVolume, exec, cliamp volume +3
bind = , XF86AudioLowerVolume, exec, cliamp volume -3
```

**sxhkd**:

```
XF86AudioPlay
    cliamp toggle

XF86AudioNext
    cliamp next
```

### Sleep / wake timers via cron

```cron
# Start lofi playback at 8am on weekdays
0 8 * * 1-5  /home/me/.local/bin/cliamp --daemon --auto-play --playlist Lofi >/dev/null 2>&1 &

# Stop at 6pm
0 18 * * *   pkill -TERM -f 'cliamp --daemon'
```

### Scripted playlists

Build a queue from a script:

```sh
cliamp --daemon --auto-play &
sleep 1                                  # let the socket bind
for f in $(find ~/Music/Albums/Daft\ Punk -name '*.flac' | sort); do
  cliamp queue "$f"
done
```

### Remote control over SSH

The socket is at `~/.config/cliamp/cliamp.sock`, and the CLI accesses it locally. Get a shell on the host with SSH or tmux session attach to control playback:

```sh
ssh kitchen-pi cliamp toggle
ssh kitchen-pi cliamp status --json
```

### Embedded / kiosk audio

Run this mode on a Pi or small Linux computer without a display. The daemon needs no terminal allocation. It needs working ALSA, PipeWire, or PulseAudio output.

```sh
cliamp --daemon --auto-play http://radio.cliamp.stream/lofi/stream
```

## Notes

- The daemon and TUI share one Unix socket. Only one cliamp instance can run for a user. A second instance cannot bind to the socket.
- This version of headless mode does not load Lua plugins. They need UI hooks that this mode does not enable.
- Headless mode does not preload the next track for gapless playback. Small gaps between tracks are expected.

### Remote Control (IPC)

URL: https://docs.cliamp.stream/docs/cliamp/remote-control-ipc

Control cliamp locally from a terminal, script, status bar, or GUI.

cliamp listens on `~/.config/cliamp/cliamp.sock` with `0600` permissions. It
uses newline-delimited JSON over a local Unix socket. To use SSH, run the client
command on the host that owns the socket.

## Quick Start

```sh
cliamp status --json
cliamp next
cliamp remote state
cliamp remote events runtime.state runtime.job
```

IPC supports version 2 only. Clients must send a V2 envelope with each request.
See [Upgrading IPC Clients To V2](https://whiterose.org.contextowl.co/docs/upgrade-ipc-clients-to-v2) when you migrate a raw
socket integration.

## Version 2

V2 responses use the request `id` and always include `"version":2`.

```json
{"version":2,"id":"state","method":"state.get"}
{"version":2,"id":"play","method":"operation.submit","operation":"play","params":{}}
{"version":2,"id":"queue","method":"operation.submit","operation":"queue.enqueue","params":{"index":4,"if_revision":18}}
```

Use these methods:

| Method | Purpose |
| --- | --- |
| `capabilities` | List available operation names and parameter hints |
| `state.get` | Read the runtime snapshot |
| `spectrum.get` | Read current visualizer bands |
| `operation.submit` | Start a runtime or library operation |
| `job.get` | Read an operation job by `job_id` |
| `job.cancel` | Request cancellation of an active job |
| `subscribe` | Start a server-to-client event stream |

`operation.submit` returns a job immediately. A job can become `queued`,
`running`, `succeeded`, `failed`, or `canceled`. Its final record contains the
operation result and the snapshot from the committed operation.

```json
{
  "version": 2,
  "id": "play",
  "ok": true,
  "job": {
    "id": "8f0d...",
    "operation": "play",
    "state": "queued"
  }
}
```

Fast operations can finish before the client requests `job.get`. Slow work,
such as provider access, URL resolution, downloads, lyrics, and saved playlist
writes, remains asynchronous.

## Runtime Snapshot

`state.get` returns a snapshot with the active audio track, logical playlist
track, playback state, position, duration, seekability, modes, EQ, visualizer,
theme, stream error, and two revisions.

```json
{
  "version": 2,
  "id": "state",
  "ok": true,
  "snapshot": {
    "revision": 18,
    "playlist_revision": 7,
    "state": "playing",
    "track": {"title":"Song","path":"/music/song.flac"},
    "logical_track": {"title":"Song","path":"/music/song.flac"},
    "position": 42.5,
    "duration": 183,
    "seekable": true,
    "play_next_total": 2
  }
}
```

`revision` changes when meaningful runtime state changes. `playlist_revision`
changes when the live playlist or play-next list changes. Position-only playback
ticks do not create events. Send `if_revision` with destructive live-playlist or
play-next operations to reject stale GUI actions with the `conflict` error code.

`track` keeps `provider_meta`, embedded playback flags, bookmark state, and
directory-source state. A GUI can send a provider result through `track.play`,
`track.queue`, `playlist.add`, `playlist.add_many`, or `playlist.replace`
without losing provider identity.

## Operations

Run `cliamp remote capabilities` to get the current machine-readable list.

| Group | Operations |
| --- | --- |
| Playback | `play`, `pause`, `toggle`, `stop`, `next`, `prev`, `volume`, `volume.adjust`, `seek`, `seek.absolute`, `speed`, `speed.adjust`, `shuffle`, `repeat`, `mono`, `eq`, `device` |
| Appearance | `theme`, `vis` |
| Live playlist | `queue`, `queue.list`, `queue.play`, `queue.enqueue`, `queue.remove`, `queue.move`, `queue.clear`, `track.play`, `track.queue` |
| Play-next | `playnext.list`, `playnext.remove`, `playnext.move`, `playnext.clear` |
| Sources | `load`, `url.load`, `save`, `lyrics`, `history`, `history.clear` |
| Providers | `provider.list`, `provider.playlists`, `provider.tracks`, `provider.load`, `provider.search`, `provider.artists`, `provider.artist_albums`, `provider.albums`, `provider.album_tracks`, `provider.load_album`, `provider.favorite`, `provider.catalog` |
| Saved playlists | `playlist.create`, `playlist.rename`, `playlist.delete`, `playlist.add`, `playlist.add_many`, `playlist.replace`, `playlist.remove`, `playlist.bookmark` |
| Plugins | `plugin.call`, `plugin.commands` |

`queue.*` applies to the live playlist. `playnext.*` applies only to the
play-next list. They use separate zero-based indexes.

Request provider list responses with `offset` and `limit` when the provider
supports paging. Use `playlist.replace` to save a GUI-created order, sort, or
deduplication result as one operation when the provider supports playlist saving.

## Events

Subscribe with an exact topic list. The acknowledgement is V2. Later lines use
the shared event envelope, so plugin and runtime events use the same form.

```json
{"version":2,"id":"events","method":"subscribe","topics":["runtime.state","runtime.job"]}
```

Core retained topics are `runtime.state`, `runtime.playback`,
`runtime.playlist`, and `runtime.settings`. `runtime.job` is temporary and
contains final job records. Plugin topics keep their `plugin.*` names.

If a client cannot keep up, it receives `system.overflow` with
`{"resync_required":true}` before the stream closes. Reconnect and request
`state.get` before you accept more changes.

## Spectrum Stream

`cliamp visstream` uses V2 `spectrum.get` internally. It outputs one plain
NDJSON frame at 30 FPS by default for status-bar and visualizer integrations.
Use `--fps` to set a rate from 1 through 60. GUI clients can request one current
frame with `spectrum.get`.

## CLI V2 Client

```sh
cliamp remote state
cliamp remote capabilities
cliamp remote call queue.enqueue --params '{"index":4,"if_revision":18}' --wait
cliamp remote job JOB_ID
cliamp remote cancel JOB_ID
cliamp remote events runtime.state runtime.job
```

`remote call` prints the V2 response as JSON and can submit every listed
operation. Use it in scripts and to validate a GUI integration.

Named CLI commands such as `cliamp volume`, `cliamp seek`, `cliamp load`, and
`cliamp plugins call` use V2 jobs internally. `volume` sets an absolute dB
value. `seek` is relative to the current position. V2 subscriptions read
`plugin.*` topics and runtime events.

## Headless Mode

```sh
cliamp --daemon --auto-play --playlist Lofi
```

The daemon exposes the same playback, queue, provider, saved-playlist, job,
snapshot, and event APIs. It has no TUI theme or visualizer selection. It does
not load Lua plugins. Use `capabilities` instead of assuming that each
interactive-only operation is available.

## Errors And Limits

V2 errors use stable codes: `invalid_version`, `invalid_request`,
`invalid_params`, `unknown_operation`, `not_found`, `conflict`, `unavailable`,
`canceled`, and `internal_error`. Runtime failures can include a `detail` string
with a provider, device, or plugin diagnostic.

Frames are limited to 1 MiB. Use paging for large provider or playlist results.
Jobs are process-local, bounded, and retained for 15 minutes after completion.
cliamp cancels them during an orderly server shutdown. They are not available
after a restart.

### Upgrading IPC Clients To V2

URL: https://docs.cliamp.stream/docs/cliamp/upgrade-ipc-clients-to-v2

Update raw Unix-socket clients to V2. Named `cliamp` commands already use V2,
so scripts that use them need no changes.

## Quick Migration

Replace each unversioned command with a V2 envelope. Each V2 request has
`version: 2` and a request `id`.

```json
{"version":2,"id":"next","method":"operation.submit","operation":"next","params":{}}
```

The response returns a job at once. Read `job.id`. Then wait for a terminal
`runtime.job` event or call `job.get`.

```json
{"version":2,"id":"job","method":"job.get","job_id":"JOB_ID"}
```

## Command Mapping

| Previous request | V2 request |
| --- | --- |
| `{"cmd":"status"}` | `{"version":2,"id":"state","method":"state.get"}` |
| `{"cmd":"bands"}` | `{"version":2,"id":"bands","method":"spectrum.get"}` |
| `{"cmd":"next"}` | `{"version":2,"id":"next","method":"operation.submit","operation":"next","params":{}}` |
| `{"cmd":"volume","value":-5}` | `{"version":2,"id":"volume","method":"operation.submit","operation":"volume","params":{"value":-5}}` |
| `{"cmd":"seek","value":30}` | `{"version":2,"id":"seek","method":"operation.submit","operation":"seek","params":{"value":30}}` |
| `{"cmd":"queue","path":"/music/song.flac"}` | `{"version":2,"id":"queue","method":"operation.submit","operation":"queue","params":{"path":"/music/song.flac"}}` |
| `{"cmd":"provider.search","provider":"local","query":"ambient"}` | `{"version":2,"id":"search","method":"operation.submit","operation":"provider.search","params":{"provider":"local","query":"ambient"}}` |

`volume` sets an absolute dB value. `seek` uses the current playback position.
Use `seek.absolute` for an absolute position.

## State And Results

`state.get` returns data in the V2 `snapshot` field. It replaces the old
top-level status object. It includes the active playback track, logical
playlist track, playback state, position, modes, EQ, theme, device, and
playlist revisions.

Mutation and provider operations return a job. A terminal job has:

- `state`: `succeeded`, `failed`, or `canceled`
- `result`: operation-specific data such as tracks, devices, lyrics, or output
  paths
- `snapshot`: the runtime state after the accepted operation
- `error`: stable `code` and `message`, with an optional diagnostic `detail`

Use `if_revision` for destructive live-playlist and play-next mutations. A
stale revision fails with `conflict`. cliamp does not apply the stale GUI action.

## Events

Replace the old subscription request with a V2 subscription. The
acknowledgement is a V2 response. Event lines keep the shared event envelope.

```json
{"version":2,"id":"events","method":"subscribe","topics":["runtime.state","runtime.job","plugin.example.playback"]}
```

The core retained topics are `runtime.state`, `runtime.playback`,
`runtime.playlist`, and `runtime.settings`. `runtime.job` is transient. It
reports terminal jobs. Plugin topics remain `plugin.*`.

If a stream receives `system.overflow`, reconnect. Call `state.get` before you
submit another mutation.

## Spectrum Clients

`cliamp visstream` keeps its one-frame-per-line NDJSON output. It now uses V2
`spectrum.get` internally. Its parser contract does not change.

Raw clients can issue `spectrum.get` at a bounded frame rate. Use one request
and response at a time on each connection.

## Client Checklist

- Send only V2 envelopes. Unversioned requests fail with `invalid_version`.
- Correlate every response with its `id`.
- Use `state.get` for direct state reads.
- Use `operation.submit` plus jobs for control, library, and provider work.
- Subscribe to `runtime.job` instead of assuming an operation has finished.
- Query `capabilities` at startup, especially in daemon mode where theme,
  visualizer selection, and plugins are unavailable.

See [Remote Control](https://whiterose.org.contextowl.co/docs/remote-control-ipc) for the full V2 operation list and error
contract.

### Community Plugins

URL: https://docs.cliamp.stream/docs/cliamp/community-plugins

These plugins are maintained by the community. To add a plugin, open a PR.

| Plugin | Description | Author |
|--------|-------------|--------|
| [cliamp-lastfm](https://github.com/tetsuo76/cliamp-lastfm) | Last.fm scrobbling | [@tetsuo76](https://github.com/tetsuo76) |
| [cliamp-plugin-led-burst](https://github.com/AlexZeitler/cliamp-plugin-led-burst) | Stereo LED matrix visualizer | [@AlexZeitler](https://github.com/AlexZeitler) |
| [cliamp-plugin-block-burst](https://github.com/AlexZeitler/cliamp-plugin-block-burst) | Stereo LED block matrix visualizer | [@AlexZeitler](https://github.com/AlexZeitler) |
| [cliamp-plugin-block-burst](https://github.com/AlexZeitler/cliamp-plugin-vu-meter) | Analog multi VU meter style visualizer | [@AlexZeitler](https://github.com/AlexZeitler) |
| [cliamp-plugin-nightrider](https://github.com/HANCORE-linux/cliamp-plugin-nightrider) | Nightrider style visualizer | [@HANCORE-linux](https://github.com/HANCORE-linux) |
| [cliamp-plugin-tubeamp](https://github.com/8bit64k/cliamp-plugin-tubeamp) | Vacuum-tube amplifier visualizer | [@8bit64k](https://github.com/8bit64k) |
| [cliamp-plugin-nova](https://github.com/8bit64k/cliamp-plugin-nova) | Concentric-ring spectrum visualizer | [@8bit64k](https://github.com/8bit64k) |
| [cliamp-plugin-mandelbrot](https://github.com/mikkel-bergmann/cliamp-plugin-mandelbrot) | Zooming psychedelic Mandelbrot set visualizer with braille rendering and bass reactivity | [@mikkel-bergmann](https://github.com/mikkel-bergmann) |
| [cliamp-plugin-gpodder-sync](https://github.com/sollymay/cliamp-plugin-gpodder-sync) | gpodder.net subscription, progress and download sync | [@sollymay](https://github.com/sollymay) |
| [cliamp-plugin-discord-rpc](https://github.com/fazaimron27/cliamp-plugin-discord-rpc) | Discord Rich Presence | [@fazaimron27](https://github.com/fazaimron27) |
| [herdr-cliamp](https://github.com/coryshaw1/herdr-cliamp) | Floating cliamp for the [herdr](https://herdr.dev) multiplexer that keeps playing when hidden, with now-playing and transport keybinds | [@coryshaw1](https://github.com/coryshaw1) |

### Lua Plugins

URL: https://docs.cliamp.stream/docs/cliamp/lua-plugins

cliamp uses Lua 5.1 plugins. Plugins can handle playback events, such as scrobbling, notifications, and status-bar output. They can also add visualizers. Each plugin runs in an isolated VM. A plugin crash does not affect other plugins or the player.

Store plugins in `~/.config/cliamp/plugins/`. Create the directory:

```
mkdir -p ~/.config/cliamp/plugins
```

cliamp runs a plugin only after you approve its exact contents. Existing and manually copied plugins start as untrusted. Approve one with `cliamp plugins trust <name>`.

## Plugin manager

```sh
cliamp plugins                          # show help
cliamp plugins list                     # list installed plugins
cliamp plugins install <source>         # install a plugin
cliamp plugins trust <name>             # approve installed plugin contents
cliamp plugins remove <name>            # remove a plugin
```

The install and trust commands show the source, SHA-256, declared permissions, and implicit file-system and network access before the prompt. In a non-interactive environment, use `--yes` only after you review the same content independently. cliamp stores approvals in `plugins/.trust.json`. Editing a plugin changes its hash and disables it until you approve it again. cliamp rejects unknown permission names.

### Install sources

| Format | Example |
|--------|---------|
| GitHub | `user/repo` |
| GitHub with tag | `user/repo@v1.0` |
| GitLab | `gitlab:user/repo` |
| GitLab with tag | `gitlab:user/repo@v1.0` |
| Codeberg | `codeberg:user/repo` |
| Codeberg with tag | `codeberg:user/repo@v1.0` |
| Direct URL | `https://example.com/plugin.lua` |

### Naming convention

Name plugin repositories `cliamp-plugin-<name>`. Put the `<name>.lua` entry point in the repository root. cliamp removes the `cliamp-plugin-` prefix during installation. For example, `cliamp-plugin-soap-bubbles`, which contains `soap-bubbles.lua`, installs as `soap-bubbles`.

```sh
cliamp plugins install bjarneo/cliamp-plugin-lastfm
cliamp plugins install bjarneo/cliamp-plugin-lastfm@v1.0
cliamp plugins install gitlab:user/my-visualizer
cliamp plugins install codeberg:user/my-plugin
cliamp plugins install https://example.com/my-plugin.lua
cliamp plugins remove lastfm
```

## Quick start

### Now-playing file for Waybar, Polybar, and similar bars

```lua
-- ~/.config/cliamp/plugins/now-playing.lua
local p = plugin.register({
    name = "now-playing",
    type = "hook",
    description = "Write now-playing to /tmp for status bars",
})

p:on("track.change", function(track)
    cliamp.fs.write("/tmp/cliamp-now-playing", track.artist .. " - " .. track.title)
end)

p:on("playback.state", function(ev)
    if ev.status == "paused" then
        cliamp.fs.write("/tmp/cliamp-now-playing", "paused")
    end
end)

p:on("app.quit", function()
    cliamp.fs.remove("/tmp/cliamp-now-playing")
end)
```

### Desktop notification on track change

```lua
-- ~/.config/cliamp/plugins/notify.lua
local p = plugin.register({
    name = "notify",
    type = "hook",
})

p:on("track.change", function(track)
    local title = track.artist .. " - " .. track.title
    os.execute('notify-send "cliamp" "' .. title .. '"')
end)
```

`os.execute` is not available in the sandbox. Use `cliamp.http` for public HTTP endpoints. cliamp blocks private, loopback, link-local, multicast, and unspecified addresses. For local automation, write to an allowed file for a watcher to read. You can also declare the permission-gated `exec` capability.

### Webhook

```lua
-- ~/.config/cliamp/plugins/webhook.lua
local p = plugin.register({
    name = "webhook",
    type = "hook",
})

local url = p:config("url")

p:on("track.change", function(track)
    if not url then return end
    cliamp.http.post(url, {
        json = { title = track.title, artist = track.artist, album = track.album }
    })
end)
```

```toml
# config.toml
[plugins.webhook]
url = "https://example.com/hook"
```

## Plugin structure

### Single file

```
~/.config/cliamp/plugins/myplugin.lua
```

### Directory with init.lua

```
~/.config/cliamp/plugins/myplugin/
    init.lua
    helpers.lua
```

The directory name is the plugin name. cliamp loads only `init.lua` automatically.

## Registration

Each plugin must call `plugin.register()`. cliamp silently skips files that do not call it.

```lua
local p = plugin.register({
    name        = "myplugin",           -- required
    type        = "hook",               -- "hook" or "visualizer"
    version     = "1.0.0",             -- optional
    description = "What it does",       -- optional
})
```

The returned `p` object provides these methods:

| Method | Description |
|--------|-------------|
| `p:on(event, callback)` | Subscribe to a playback event |
| `p:config(key)` | Read a config value from `[plugins.myplugin]` in config.toml |
| `p:publish(topic, payload, options)` | Publish a namespaced event to local IPC subscribers |

## Plugin event pub/sub

Plugins can publish JSON-compatible values to external programs that connect to
Cliamp's owner-only IPC socket. cliamp puts each topic below the installed plugin
name. For example, `myplugin.lua` that publishes `"playback"` uses the topic
`plugin.myplugin.playback`. The name provides one topic segment. cliamp replaces
each character other than a letter, digit, `_`, or `-` with `_`. Therefore,
`my.plugin.lua` uses the `plugin.my_plugin.*` prefix. Publishing `"playback"`
from that plugin uses `plugin.my_plugin.playback`. It cannot collide with topics
from a plugin named `my`.

This conversion loses information, so namespaces are unique for a session. If
`my.plugin.lua` and `my_plugin.lua` are both installed, the first loaded plugin
(plugins load in name order) owns the `plugin.my_plugin.*` prefix. In the other
plugin, `p:publish()` returns `nil, err` and names the owner. Rename one plugin
to publish from both. Subscribers must specify complete topics, not prefixes.

```lua
p:publish("playback", {
    status = cliamp.player.state(),
    title = cliamp.track.title(),
}, { retain = true })
```

With `retain = true`, Cliamp keeps the latest value in memory and sends it to
new subscribers immediately. Cliamp discards retained values when it exits. It
does not save event data to disk. Publishing does not block. cliamp disconnects
a subscriber that cannot keep up instead of blocking the player.

Open `cliamp.sock` and send one NDJSON request to subscribe:

```json
{"version":2,"id":"events","method":"subscribe","topics":["plugin.myplugin.playback"]}
```

After `{"version":2,"id":"events","ok":true}`, the connection becomes a
server-to-client event stream:

```json
{"event":"plugin.myplugin.playback","seq":42,"time":1786685741,"retained":true,"data":{"status":"playing","title":"Track"}}
```

Subscriptions use exact topic matches and accept at most 32 topics. They are
for streaming only. Use another IPC connection for normal commands. Sending
more bytes on a subscription closes it. Payloads can be at most 64 KiB. cliamp
converts them with the nesting and cycle rules of
[`cliamp.json`](#cliampjson). Topic segments can contain letters, digits, `.`,
`_`, and `-`. `p:publish()` needs no permission. IPC is local to the same user,
and the `status` command already exposes playback metadata.

## Events

Use `p:on(event, callback)` to subscribe to events. Callbacks run in goroutines and time out after 5 seconds.

### Available events

| Event | Callback argument | When |
|-------|-------------------|------|
| `track.change` | `{title, artist, album, genre, year, path, duration, stream}` | New track starts |
| `track.scrobble` | Same + `{played_secs}` | Track played >= 50% or >= 4 min |
| `playback.state` | `{status, title, artist, album, path, duration, stream, position}` | Any playback state change (play, pause, stop, seek, volume, track transition) |
| `player.seek` | `{position, duration}` (seconds) | A seek completes |
| `player.volume` | `{db}` | Volume changes |
| `player.eq` | `{bands, preset}` | An EQ band or preset changes |
| `player.mode` | `{shuffle, repeat}` | Shuffle toggled or repeat mode cycled |
| `queue.change` | `{count, index, queued}` | Playlist or play-next queue changes |
| `app.start` | `{}` | After all plugins loaded |
| `app.quit` | `{}` | Before shutdown |

In `playback.state`, `status` is `"playing"`, `"paused"`, or `"stopped"`. In `player.mode`, `repeat` is `"Off"`, `"All"`, or `"One"`, matching `cliamp.player.repeat_mode()`. In `player.eq`, `bands` is an array of 10 dB values.

cliamp sends `player.*` and `queue.change` events by comparing state after each UI update. They cover every source, including a keypress, IPC, MPRIS, or another plugin.

## Plugin object methods

The object from `plugin.register(...)` provides these methods in addition to `:on()` and `:config()`:

### `p:bind(key, [description,] callback)` - keyboard binding (requires `permissions = {"keymap"}`)

```lua
local p = plugin.register({
    name = "my-plugin",
    type = "hook",
    permissions = {"keymap"},
})

-- Listed in the Ctrl+K overlay under "— plugins —":
p:bind("x", "Extract chapters", function(key) ... end)

-- Not listed (hidden binding):
p:bind("ctrl+e", function(key) ... end)
```

Returns `true` on success. Returns `false, reason` when cliamp's core UI owns the key or the plugin lacks the `keymap` permission. Pass a description as the middle argument to show the binding in the `Ctrl+K` keymap overlay. Omit it for an internal-only binding.

Use Bubbletea's `msg.String()` form for key strings: lowercase letters and the `ctrl+`, `shift+`, or `alt+` prefixes. For example: `"x"`, `"ctrl+e"`, and `"shift+f1"`. Key strings are case-insensitive.

Plugin keys work only in the main view. Overlays such as the file browser, theme picker, and keymap capture their own input. The core reserves every key in `docs/keybindings.md`. Trying to bind one logs a warning and returns `false`.

Use `p:unbind(key)` to release a binding.

### `p:command(name, callback)` - shell-invokable command

```lua
p:command("run", function(args)
    -- args is an array of strings passed after the command name
    return "done: " .. args[1]
end)
```

The callback can return a string. The CLI client prints it. Invoke commands from the shell with `cliamp plugins call <plugin-name> <command> [args...]`. cliamp sends the command to the running player over IPC. Commands need no separate permission because the user starts them.

List registered commands with `cliamp plugins commands`. A command can run for up to 5 minutes before it times out.

## Lua API

All APIs are in the global `cliamp` table.

### cliamp.player (read-only)

```lua
cliamp.player.state()         --> "playing" | "paused" | "stopped"
cliamp.player.position()      --> number (seconds)
cliamp.player.duration()      --> number (seconds)
cliamp.player.volume()        --> number (dB, -30 to +6)
cliamp.player.speed()         --> number (ratio, 1.0 = normal)
cliamp.player.mono()          --> boolean
cliamp.player.repeat_mode()   --> "Off" | "All" | "One"
cliamp.player.shuffle()       --> boolean
cliamp.player.eq_bands()      --> table of 10 dB values
```

### cliamp.track (read-only)

```lua
cliamp.track.title()          --> string
cliamp.track.artist()         --> string
cliamp.track.album()          --> string
cliamp.track.genre()          --> string
cliamp.track.year()           --> number
cliamp.track.track_number()   --> number
cliamp.track.path()           --> string
cliamp.track.is_stream()      --> boolean
cliamp.track.duration_secs()  --> number
```

### cliamp.queue

You can read the playlist without permission. To change it, declare `permissions = {"control"}`. All indices are 0-based, as in `cliamp.queue.current()`.

```lua
-- read (no permission)
cliamp.queue.list()        --> array of {title, artist, album, path, index, queued}
cliamp.queue.count()       --> number of tracks
cliamp.queue.current()     --> 0-based index of the current track

-- mutate (requires "control")
cliamp.queue.add(path)         -- resolve a file/dir/URL and append
cliamp.queue.jump(index)       -- make index current and play it
cliamp.queue.remove(index)     -- remove the track at index
cliamp.queue.move(from, to)    -- reorder a track
```

`add` accepts every input that the CLI accepts: a local file or directory, an
HTTP stream, an M3U/PLS URL, or a YouTube/yt-dlp URL. cliamp resolves it off the
UI thread. A slow URL does not block playback.

### cliamp.http

```lua
-- GET
local body, status = cliamp.http.get("https://api.example.com/data", {
    headers = { Authorization = "Bearer token" }
})

-- POST with JSON
local body, status = cliamp.http.post("https://api.example.com/scrobble", {
    json = { artist = "Radiohead", track = "Everything In Its Right Place" }
})

-- POST with form body
local body, status = cliamp.http.post(url, {
    headers = { ["Content-Type"] = "application/x-www-form-urlencoded" },
    body = "key=value&foo=bar"
})
```

The timeout is 5 seconds. The response body limit is 1 MB.

### cliamp.fs

```lua
cliamp.fs.write(path, content)    -- overwrite file
cliamp.fs.append(path, content)   -- append to file
cliamp.fs.read(path)              --> string (max 1 MB)
cliamp.fs.remove(path)            -- delete file
cliamp.fs.exists(path)            --> boolean
cliamp.fs.mkdir(path)             -- create directory (recursive)
cliamp.fs.listdir(path)           --> {names}, err
```

You can write only to the system temp directory (`/tmp/` on Unix), `~/.config/cliamp/`, `~/.local/share/cliamp/`, and `~/Music/cliamp/`. You can read from any path. On Windows, when `HOME` is unset, the config directory resolves to `%APPDATA%\cliamp`.

### cliamp.json

```lua
local tbl = cliamp.json.decode('{"key": "value"}')
local str = cliamp.json.encode({ key = "value" })
```

cliamp encodes tables to a depth of 64 levels. A deeper table or a cyclic
reference becomes `null`; it does not fail. `p:publish()` and `cliamp.store`
use the same conversion.

### cliamp.store

This is a persistent key/value store for each plugin. Strings, numbers,
booleans, and tables survive restarts. No permission is required. Each plugin
can access only its own namespace, so it cannot read another plugin's keys.

```lua
cliamp.store.set(key, value)   -- value: string|number|boolean|table
cliamp.store.get(key)          --> value or nil
cliamp.store.delete(key)
cliamp.store.keys()            --> sorted array of keys
cliamp.store.clear()
```

cliamp stores this data in `~/.local/share/cliamp/plugins/<name>/store.json`
with owner-only mode (0600). Use it for play counts, offline scrobble queues,
resume positions, and saved settings. Do not use it for large data.

```lua
local counts = cliamp.store.get("counts") or {}
counts[cliamp.track.path()] = (counts[cliamp.track.path()] or 0) + 1
cliamp.store.set("counts", counts)
```

### cliamp.crypto

```lua
cliamp.crypto.md5("hello")                  --> hex string
cliamp.crypto.sha256("hello")               --> hex string
cliamp.crypto.hmac_sha256("secret", "msg")  --> hex string
```

### cliamp.log

```lua
cliamp.log.info("loaded successfully")
cliamp.log.warn("missing config key")
cliamp.log.error("request failed: " .. err)
cliamp.log.debug("response: " .. body)
```

cliamp writes logs to `~/.config/cliamp/plugins.log`. Each line has a timestamp and the `[plugin-name]` prefix.

### cliamp.player control (requires permissions)

Plugins that declare `permissions = {"control"}` can control the player:

```lua
local p = plugin.register({
    name = "my-controller",
    type = "hook",
    permissions = {"control"},
})

cliamp.player.next()              -- skip to next track
cliamp.player.prev()              -- go to previous track
cliamp.player.play_pause()        -- toggle play/pause
cliamp.player.stop()              -- stop playback
cliamp.player.set_volume(-5)      -- set volume in dB (-30 to +6)
cliamp.player.set_speed(1.25)     -- set playback speed (0.25 to 2.0)
cliamp.player.seek(30)            -- seek to 30 seconds
cliamp.player.toggle_mono()       -- toggle mono output
cliamp.player.set_eq_preset("Rock") -- switch to built-in preset (sets bands + UI label)
cliamp.player.set_eq_preset("Metal", {6,4,1,-1,-2,2,4,6,6,5}) -- custom preset with bands
cliamp.player.set_eq_band(1, 6)   -- set EQ band 1 to +6 dB (bands 1-10, -12 to +12)
```

If a plugin does not declare `permissions = {"control"}`, these functions log a warning and do nothing.

### cliamp.notify

```lua
cliamp.notify("Song Title")                -- notification with title only
cliamp.notify("Song Title", "Artist Name") -- notification with title and body
```

This sends a desktop notification through `notify-send`. It works with mako, dunst, and other notification daemons.

### cliamp.exec (requires permissions)

Plugins that declare `permissions = {"exec"}` can start subprocesses from a configurable binary allowlist. The default allowlist is `yt-dlp`, `ffmpeg`. Add binaries in `config.toml`:

```toml
[plugins]
allowed_binaries = "ffprobe, curl"   # merged with defaults
```

```lua
local p = plugin.register({
    name = "my-downloader",
    type = "hook",
    permissions = {"exec"},
})

local handle, err = cliamp.exec.run("yt-dlp", {"--dump-json", url}, {
    on_stdout = function(line) ... end,   -- optional, called per line
    on_stderr = function(line) ... end,   -- optional
    on_exit   = function(code) ... end,   -- optional, fires exactly once
    cwd       = "/tmp/work",              -- optional; must be in write allowlist
    timeout   = 300,                       -- optional seconds, hard cap 1800
})

handle:cancel()                           -- terminate the process
handle:alive()                            -- --> boolean
```

**Safety rules:**

- The binary must be in the allowlist. Argv is argv. No shell or expansion is used.
- `args` must be a flat array of strings. cliamp rejects nested tables and non-strings.
- The subprocess environment contains only `PATH`, `HOME`, and `LANG`. cliamp does not pass parent-environment secrets.
- Output is limited to 4 MiB per process, for stdout and stderr together. cliamp silently drops later lines.
- Each plugin can run up to 4 processes at one time.
- cliamp kills every plugin-owned process when the plugin unloads and when cliamp exits.
- Negative `on_exit` codes indicate cancellation or timeout (`-1`), or a start failure (`-2`).

Without `permissions = {"exec"}`, `cliamp.exec.run` returns `nil, "exec permission required"`.

### cliamp.message

```lua
cliamp.message("Scrobble Sent")        -- show for default duration
cliamp.message("Syncing Library", 5)   -- show for 5 seconds
```

This shows a temporary message in the status bar at the bottom of the UI. The
duration is optional and uses seconds. Omit it to use the default TTL. cliamp
limits durations above 60 seconds.

### cliamp.sleep

```lua
cliamp.sleep(2.5)  -- block for 2.5 seconds (max 10)
```

This blocks the plugin's Lua VM. Other hooks for the same plugin wait until the sleep ends. Use `cliamp.timer.after()` for a non-blocking delay.

### cliamp.timer

```lua
-- Run once after 5 seconds
local id = cliamp.timer.after(5.0, function()
    cliamp.log.info("timer fired")
end)

-- Run every 30 seconds
local id = cliamp.timer.every(30.0, function()
    -- periodic task
end)

-- Cancel
cliamp.timer.cancel(id)
```

## Configuration

Put plugin-specific configuration in `config.toml` under `[plugins.<name>]`:

```toml
[plugins.lastfm]
api_key = "abc123"
api_secret = "secret"
session_key = "sk-xxx"

[plugins.webhook]
url = "https://example.com/hook"
```

Read it in Lua:

```lua
local api_key = p:config("api_key")   --> "abc123" or nil
```

### Disabling plugins

Disable one plugin:

```toml
[plugins.webhook]
enabled = false
```

To disable several plugins:

```toml
[plugins]
disabled = webhook, discord-rpc
```

## Visualizer plugins

Plugins with `type = "visualizer"` add visualizer modes to the `v` key cycle with the built-in modes.

```lua
-- ~/.config/cliamp/plugins/simple-bars.lua
local p = plugin.register({
    name = "simple-bars",
    type = "visualizer",
})

-- Called every frame (~20 FPS during playback).
-- bands: table of 10 numbers (0.0-1.0), indices 1-10
-- frame: monotonic counter
-- rows: available terminal rows (changes in fullscreen mode)
-- cols: available terminal columns
-- Must return a multi-line string.
function p:render(bands, frame, rows, cols)
    local lines = {}
    local chars = { " ", "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█" }

    for row = 5, 1, -1 do
        local line = ""
        for i = 1, 10 do
            local level = bands[i]
            local threshold = (row - 1) / 5
            if level > threshold then
                line = line .. "██████ "
            else
                line = line .. "       "
            end
        end
        table.insert(lines, line)
    end

    return table.concat(lines, "\n")
end
```

### Visualizer callbacks

| Callback | Signature | Required |
|----------|-----------|----------|
| `p:render(bands, frame, rows, cols)` | Returns string | Yes |
| `p:init(rows, cols)` | Setup when selected | No |
| `p:destroy()` | Cleanup when deselected | No |

`render` has a 10 ms limit for each frame. If it exceeds the limit, cliamp reuses the previous frame to prevent UI delay.

## Sandbox

For security, plugins have restricted access. The sandbox removes unsafe standard-library functions and limits file-system access.

### Removed functions

| Removed | Replacement |
|---------|-------------|
| `os.execute`, `os.remove`, `os.rename`, `os.exit`, `os.setlocale`, `os.tmpname` | Use `cliamp.fs`, `cliamp.http`, or permission-gated `cliamp.exec` |
| `io` module (all of it) | Use `cliamp.fs` |
| `dofile`, `loadfile`, `load`, `loadstring`, `require`, `module`, `package`, `debug` | Not available |

### Kept functions

You can use `os.time()`, `os.date()`, `os.clock()`, and `os.getenv()`.

### File system restrictions

**Reads:** You can read from any path, up to 1 MB for each read.

**Writes/removes/mkdir** work only in these directories:

- `/tmp/` (and the system temp directory)
- `~/.config/cliamp/`
- `~/.local/share/cliamp/`
- `~/Music/cliamp/`

Writing outside these directories raises a Lua error. cliamp blocks directory traversal (`..`).

### Isolation

- Each plugin has its own Lua VM. A plugin cannot access another plugin's state or variables.
- A plugin crash does not affect other plugins or the player.
- Use `cliamp.http` for public network access. Raw socket access is not available. cliamp blocks private, loopback, link-local, multicast, and unspecified destinations after DNS resolution and through redirects.
- `os.execute` is not available. Permission-gated `cliamp.exec` can start only configured allowed binaries.

## Debugging

Check `~/.config/cliamp/plugins.log` for plugin output and errors:

```
2025-03-29 14:30:01 [now-playing] info: Now playing: Everything In Its Right Place
2025-03-29 14:30:01 [webhook] error: track.change handler error: connection refused
```

Use `cliamp.log.debug()` during development.

### Creating a Provider

URL: https://docs.cliamp.stream/docs/cliamp/creating-a-provider

Put providers in `external/<name>/`, for example `external/jellyfin/`. A
provider is a Go package. It implements the base `playlist.Provider` interface
and can implement capability interfaces from the `provider/` package. The UI
uses type assertions at run time to detect capabilities and enable features.

Use these providers as examples:

- `external/navidrome/`: Subsonic API, browsing, scrobbling
- `external/plex/`: Plex Media Server, search, album tracks
- `external/spotify/`: Spotify, search, playlist management, custom streaming
- `external/mixcloud/`: public catalog, browse-entry shortcuts, creator jumps,
  genre search and local genre favorites
- `external/radio/`: internet radio, favorites
- `external/local/`: local TOML playlist files
- `external/audiobookshelf/`: Audiobookshelf, sectioned playlists, resume

## Base Interface (required)

Every provider must implement `playlist.Provider`:

```go
type Provider interface {
    Name() string
    Playlists() ([]playlist.PlaylistInfo, error)
    Tracks(playlistID string) ([]Track, error)
}
```

This interface provides a name, a playlist list, and tracks for a playlist. It
is enough for basic playback.

## Capability Interfaces (optional)

Implement any of these interfaces to enable more UI features. All interfaces
are in `provider/interfaces.go`.

| Interface | What it enables | Methods |
|---|---|---|
| `Searcher` | Track search overlay | `SearchTracks(ctx, query, limit)` |
| `ArtistBrowser` | Hierarchical artist browsing | `Artists()`, `ArtistAlbums(id)` |
| `TrackArtistResolver` | Jump from a highlighted provider track to its artist/creator with `N` | `ArtistForTrack(track)` |
| `BrowseEntryProvider` | Add non-playable shortcuts into the provider playlist pane | `BrowseEntries()`; each entry can set `AfterID`, `AfterSection`, and `OpenInPlaylist` |
| `GenreBrowser` | Hierarchical category browsing with provider-defined sort views | `Genres()`, `GenreSortTypes()`, `GenreTracks(genreID, sortType)` |
| `GenreFavoriteToggler` | Favorite/unfavorite categories with `f` in the genre browser | `ToggleGenreFavorite(genreID)` |
| `GenreSearcher` | Search beyond the initially loaded category catalogue | `SearchGenres(ctx, query, limit)` |
| `AlbumBrowser` | Paginated album browsing with sort | `AlbumList(sort, offset, size)`, `AlbumSortTypes()` |
| `AlbumTrackLoader` | Album track listing | `AlbumTracks(albumID)` |
| `PlaybackReporter` | Playback reporting at track start and finish | `CanReportPlayback(track)`, `ReportNowPlaying(track, position, canSeek) error`, `ReportScrobble(track, elapsed, duration, canSeek) error` |
| `PlaylistWriter` | Add track to playlist | `AddTrackToPlaylist(ctx, playlistID, track)` |
| `PlaylistCreator` | Create new playlist | `CreatePlaylist(ctx, name)` |
| `PlaylistDeleter` | Remove playlists/tracks | `DeletePlaylist(name)`, `RemoveTrack(name, index)` |
| `CustomStreamer` | Custom URI decode pipeline | `URISchemes()`, `NewStreamer(uri)` |
| `FavoriteToggler` | Favorite toggling | `ToggleFavorite(id)` |
| `Closer` | Cleanup on shutdown | `Close()` |
| `Authenticator` | Interactive sign-in flow | `Authenticate() error` (in `playlist` package) |
| `ResumeTarget` | Server-side resume position | `ResumeTarget(playlistID, tracks)` |
| `TrackPosition` | Server-side position for one track, read on every play | `CanTrackPosition(track)`, `TrackPosition(track)` |
| `ProgressReporter` | Interim position updates while playing, in addition to `PlaybackReporter`'s start/finish reports | `ReportProgress(track, position) error` |
| `BrowseLabeler` | Relabel the browse overlay's two levels (e.g. Authors/Books instead of Artists/Albums) | `BrowseLabels()` |

## Steps

### 1. Create the package

Create `external/<name>/provider.go`:

```go
package jellyfin

import (
    "context"

    "github.com/bjarneo/cliamp/playlist"
    "github.com/bjarneo/cliamp/provider"
)

// Compile-time interface checks.
var (
    _ provider.Searcher         = (*Provider)(nil)
    _ provider.AlbumTrackLoader = (*Provider)(nil)
)

type Provider struct {
    baseURL string
    token   string
}

func New(baseURL, token string) *Provider {
    return &Provider{baseURL: baseURL, token: token}
}

func (p *Provider) Name() string { return "Jellyfin" }

func (p *Provider) Playlists() ([]playlist.PlaylistInfo, error) {
    // Fetch playlists from your server's API.
    return nil, nil
}

func (p *Provider) Tracks(playlistID string) ([]playlist.Track, error) {
    // Fetch tracks for a playlist.
    return nil, nil
}

func (p *Provider) SearchTracks(ctx context.Context, query string, limit int) ([]playlist.Track, error) {
    // Search the server's catalog.
    return nil, nil
}

func (p *Provider) AlbumTracks(albumID string) ([]playlist.Track, error) {
    // Fetch tracks for an album.
    return nil, nil
}
```

### 2. Return tracks

When you create `playlist.Track` values:

- **`Path`**: Set the playable URL or file path. For HTTP streams, use a full URL.
  For a custom URI scheme, for example `spotify:track:xxx`, implement `CustomStreamer`.
- **`Stream: true`**: Set this for HTTP URLs. The player then uses the streaming
  pipeline.
- **`ProviderMeta`**: Add provider-specific metadata in a string map with
  namespaced keys. cliamp uses this metadata for features such as scrobbling:

```go
playlist.Track{
    Path:         "https://my-server/stream/123",
    Title:        "Song Title",
    Artist:       "Artist Name",
    Stream:       true,
    ProviderMeta: map[string]string{"jellyfin.id": "123"},
}
```

### 3. Add configuration

Add a configuration struct to `config/config.go`:

```go
type JellyfinConfig struct {
    URL   string `toml:"url"`
    Token string `toml:"token"`
}
```

Add the field to the top-level `Config` struct. Then add a TOML section:

```toml
[jellyfin]
url = "https://jellyfin.example.com"
token = "your-api-key"
```

### 4. Register in main.go

Register the provider in the `run()` function in `main.go`:

```go
if cfg.Jellyfin.URL != "" && cfg.Jellyfin.Token != "" {
    jfProv := jellyfin.New(cfg.Jellyfin.URL, cfg.Jellyfin.Token)
    providers = append(providers, ui.ProviderEntry{
        Key: "jellyfin", Name: "Jellyfin", Provider: jfProv,
    })
}
```

If the provider needs a custom audio pipeline, such as Spotify `spotify:` URIs,
register a streamer factory:

```go
if cs, ok := myProv.(provider.CustomStreamer); ok {
    for _, scheme := range cs.URISchemes() {
        p.RegisterStreamerFactory(scheme, cs.NewStreamer)
    }
}
```

If the provider needs the buffered download pipeline for stream URLs, such as
Navidrome Subsonic endpoints, register a URL matcher:

```go
p.RegisterBufferedURLMatcher(jellyfin.IsStreamURL)
```

### 5. Add a `--provider` flag value

In the `main.go` help text, add the provider key to the `--provider` line. Users
can then set it as the default.

## What the UI Does Automatically

Do not change the UI code. The UI uses the interfaces your provider implements
to do the following:

- Show the browse overlay (`N`) when any registered provider implements
  `ArtistBrowser`, `AlbumBrowser`, or `GenreBrowser`
- Add `BrowseEntryProvider` routes to the provider pane without exposing them
  as playable playlists to IPC or other provider users. `AfterID` puts a route
  after one list item. `AfterSection` is its section fallback. cliamp omits a
  route that extends a missing section. `OpenInPlaylist` replaces the main
  playlist with its non-empty final result instead of opening the browser track
  screen
- Jump from a highlighted track to its artist or creator when the source
  provider implements both `TrackArtistResolver` and `ArtistBrowser`
- Add genre lists and sort views for `GenreBrowser`, the `f` action for
  `GenreFavoriteToggler`, and provider-side category search for `GenreSearcher`
- Show the search overlay ("F") when a registered provider implements `Searcher`
- Enable add-to-playlist in search results when the searched provider implements `PlaylistWriter`
- Report playback at track start and finish when `PlaybackReporter` is implemented. Log failures that the provider returns.
- Run interactive authentication on first use when `Authenticator` is implemented
- Put the cursor on the active track and start at its stored position when `ResumeTarget` is implemented
- Send the listening position every 15 seconds while a track plays when `ProgressReporter` is implemented
- Set the browse overlay levels to your own nouns when `BrowseLabeler` is implemented
- Call `Close()` during shutdown when `Closer` is implemented

The "N" and "F" shortcuts work with any active provider. They use the first
registered provider with the required capability.

### Quickshell Now-Playing Widget (Omarchy)

URL: https://docs.cliamp.stream/docs/cliamp/quickshell-now-playing-widget-omarchy

The bundled Quickshell integration was removed in cliamp 2.0.

## Demo

### my title

URL: https://docs.cliamp.stream/docs/demo/my-title

Briefly describe the task this guide helps the reader accomplish.

## Prerequisites

- What the reader needs before starting
- Access, tools, or accounts required

## Steps

1. Do the first thing.
2. Do the next thing, and note what to expect.
3. Finish the task.

## Result

Describe what success looks like and where to go next.

![](/uploads/white-rose/demo/c9dddd3f94e93b120b14856e67c62659.mp4)

## Wahoo

### Quick Start

URL: https://docs.cliamp.stream/docs/wahoo/quick-start

Create, test, and upgrade a Wahoo application.

> **Work in progress:** Do not use Wahoo in production yet.

## Requirements

Install Go 1.25 or later, Node.js 22 or later, npm, Docker, and GPG when you install release binaries.

## Create An Application

Run this from a Wahoo checkout:

```bash
go run ./cmd/wahoo new --local ./acme
```

The command creates a core application, writes `.wahoo/project.json`, runs `go mod tidy`, and asks about the three browser-facing modules.

```text
Add authentication route stubs? [y/N]:
Add an SSE endpoint? [y/N]:
Add a WebSocket endpoint? [y/N]:
```

Use `--modules` for all module selection in automation:

```bash
go run ./cmd/wahoo new --local --modules auth,openapi,jobs ./acme
go run ./cmd/wahoo new --local --yes ./acme
```

`--local` vendors the current framework checkout so the generated Docker build does not depend on a host path.

## Modules

```bash
wahoo modules
wahoo add ./acme openapi jobs
```

| Module | Adds |
| --- | --- |
| `auth` | `501` account route stubs. |
| `sse` | A bounded event hub and a `501` stream route. |
| `websocket` | A `501` WebSocket route. |
| `openapi` | An application-owned OpenAPI 3.1 document at `/openapi.json`. |
| `jobs` | A separate `cmd/worker` and queue integration seam. |
| `uploads` | A `501` upload route. |
| `mail` | A `501` mail route. |
| `audit` | A `501` audit-event route. |
| `webhooks` | A `501` webhook route. |
| `entitlements` | A `501` entitlement route. |
| `billing` | A `501` billing route. |

The modules do not select a provider or expose a live integration. Replace an HTTP stub only after authorization, limits, storage, and operational policy exist.

## Start And Test

```bash
cd acme
npm ci --prefix web
npm run dev --prefix web
```

Open `http://localhost:8080`. The Vite and SSR worker listen on loopback port `4173` during local development.

```bash
npm test --prefix web
npm run typecheck --prefix web
npm run build --prefix web
npm run test:ssr --prefix web
go test ./...
go vet ./...
```

## Docker

```bash
docker build -f Dockerfile.example -t acme .
docker run --rm -p 8080:8080 acme
```

The image uses pinned base digests, a non-root runtime user, and `tini`. The Node supervisor stops the container if either the Go process or private SSR worker exits.

## Upgrade

Commit the application first. Check an upgrade without writes, then apply it to the target release tag.

```bash
wahoo upgrade ./acme --check --to vX.Y.Z
wahoo upgrade ./acme --apply --to vX.Y.Z
go mod tidy
go test ./...
```

`upgrade --apply` changes only the Wahoo dependency and `.wahoo/project.json`. It never rewrites `app/`, `web/`, migrations, or the lockfile.

### Realtime

URL: https://docs.cliamp.stream/docs/wahoo/realtime

Wahoo provides bounded Server-Sent Events (SSE) and WebSocket primitives. Generated realtime routes return `501 Not Implemented` until the application adds policy.

> **Work in progress:** Do not use Wahoo in production yet.

## SSE Topics

Use a topic for tenant- or subject-scoped events. Authorize the request before you select the topic handler.

```go
events := realtime.NewHub(
    realtime.WithMaxClients(100),
    realtime.WithMaxStreamAge(10*time.Minute),
)

topic, err := events.Topic("tenant:ten_123")
if err != nil {
    return err
}
runtime.Handle("GET /events", authenticated(topic))

events.PublishTo("tenant:ten_123", realtime.Event{
    ID:   "evt_123",
    Name: "project.updated",
    Data: []byte(`{"project_id":"prj_123"}`),
})
```

The hub has a default 1000-client limit, 15-minute stream lifetime, 25-second heartbeats, one buffered event per client, and slow-client eviction. Event data is copied before delivery. SSE clears the normal HTTP write deadline for the selected long-lived response.

`Publish` is global. Use it only for intentionally global events. The hub is local to one Go process. Publish through a shared system when you run more than one instance, then deliver to each instance's authorized local clients.

## Required Application Policy

1. Authenticate the session before the SSE handler attaches.
2. Resolve and authorize the tenant before selecting a topic.
3. Apply per-principal and per-IP connection limits.
4. Publish only tenant-scoped data.
5. Bound event payload size before you publish it.

## WebSockets

`realtime.WebSocket` keeps the request-host same-origin behavior from `coder/websocket`, sets a 1 MiB message limit, and applies a 15-minute connection context. It does not authenticate, rate limit, serialize writes, or provide shared fanout.

```go
runtime.Handle("GET /ws", authenticated(realtime.WebSocket(handleSocket, &websocket.AcceptOptions{
    OriginPatterns: []string{"app.example.com"},
})))
```

Do not use `realtime.Echo()` in a public service. Do not expose internal errors through WebSocket close reasons.

## Test

```bash
go test -race ./...
```

Test authorization before connection setup, tenant isolation, client limits, idle timeouts, message-size limits, and write serialization.

### Authentication

URL: https://docs.cliamp.stream/docs/wahoo/authentication

Wahoo provides password, opaque-token, session, and CSRF primitives. Generated account routes return `501 Not Implemented` until the application supplies storage, mail, cookies, authorization, and rate limits.

> **Work in progress:** Do not use Wahoo in production yet.

## Provided API

| API | Use it to |
| --- | --- |
| `auth.HashPassword` | Create a bcrypt hash after a 12-character minimum check. |
| `auth.VerifyLogin` | Verify credentials with a dummy bcrypt check for absent users. Storage failures are returned. |
| `auth.NewToken` | Create a URL-safe opaque token. |
| `auth.TokenHash` | Hash an opaque token before storage. |
| `auth.AuthenticateSession` | Validate token hash, expiry, and revocation through an application `SessionStore`. |
| `auth.NewCSRFToken` | Create a token for an application-owned CSRF design. |
| `auth.VerifyCSRFToken` | Compare CSRF tokens in constant time. |

Do not store raw passwords, session tokens, reset tokens, or CSRF tokens.

## Session Store

Implement only the lookup needed by the framework primitive:

```go
type SessionStore interface {
    FindSessionByTokenHash(context.Context, string) (*auth.Session, error)
}
```

```go
rawToken, err := auth.NewToken(32)
if err != nil {
    return err
}
hash, err := auth.TokenHash(rawToken)
// Store hash, user ID, expiry, and revocation time.

session, err := auth.AuthenticateSession(r.Context(), sessions, rawToken, time.Now())
```

The application must create, rotate, revoke, and persist sessions. It must set a secure, `HttpOnly`, `SameSite` cookie. Use `Secure: false` only for local HTTP development.

## Login And Reset

A login handler must normalize email, rate limit attempts, return the same credential failure for absent and incorrect users, create a new session, write an audit event, and set a secure cookie.

A password-reset flow must always return the same public response, store only a single-use token hash, use a short expiry, revoke sessions after a successful reset, and write an audit event.

## CSRF

Use a server-side synchronizer token or signed double-submit token for browser mutations. Also validate `Origin` or `Referer`. CORS does not prevent CSRF.

## OAuth And MFA

Keep OAuth and MFA behind application provider interfaces. OAuth requires state, nonce, and PKCE. Use WebAuthn or TOTP for MFA, hash recovery codes, and require short-lived step-up state for sensitive actions.

### Production

URL: https://docs.cliamp.stream/docs/wahoo/production

Wahoo is work in progress. Do not use it in production yet.

## Build And Test

Run these commands from the application root:

```bash
npm ci --prefix web
npm test --prefix web
npm run typecheck --prefix web
npm run build --prefix web
npm run test:ssr --prefix web
go test ./...
go test -race ./...
go vet ./...
go build -o bin/app .
```

The generated lockfile pins frontend dependencies. Do not use `npm install` in CI or Docker builds.

## Runtime

The Go server owns public HTTP. The Node SSR worker binds only to `127.0.0.1:4173`. In production, `NODE_ENV=production` makes SSR worker failures fail closed instead of serving a development fallback.

The generated Docker image runs `tini` and a Node supervisor. The supervisor stops the container if either Go or the SSR worker exits. Its health check requires both `GET /healthz` and private worker readiness.

```bash
docker build -f Dockerfile.example -t acme .
docker run --rm -p 8080:8080 acme
```

Use separate web and worker workloads when background work has independent scaling or retry requirements.

## Visible Security Policy

`internal/config` sets a basic response-header policy and 1 MiB JSON body limit. Review and extend it for the application. Wahoo does not infer TLS, HSTS, trusted proxies, CORS, cookie settings, CSRF policy, or distributed rate-limit storage.

Use `server.RateLimit` with an application-defined key and shared limiter in multi-instance production. `ratelimit.Memory` is bounded and process-local only.

## Health And Readiness

`GET /healthz` confirms that Go accepts requests. `GET /readyz` calls an application-owned readiness function with a 250 ms context deadline. Add bounded database and dependency checks before your deployment uses it.

## Realtime, Webhooks, And Integrations

Do not expose generated realtime, upload, mail, audit, webhook, entitlement, or billing stubs. Add authentication, tenant authorization, rate limits, payload limits, provider adapters, and idempotency first.

Webhook signature verification proves authenticity and bounded freshness only. Store delivery IDs atomically and process each provider event idempotently.

## CI

Wahoo CI runs Go tests, race tests, vet, generated-project tests, frontend tests/typechecking/build, Docker build, runtime health/readiness, OpenAPI, fail-closed routes, and SSR-worker-loss behavior. The `verify` check is required on `main`.

## Release Verification

The installer requires an explicit release tag and GPG. It verifies a signed `checksums.txt` before extraction.

```bash
curl --fail --location --silent --show-error https://raw.githubusercontent.com/bjarneo/wahoo/v0.4.0/install.sh --output /tmp/wahoo-install.sh
WAHOO_VERSION=v0.4.0 sh /tmp/wahoo-install.sh
```

Use a versioned installer URL. Do not pipe a mutable branch into a shell.

### Application Foundations

URL: https://docs.cliamp.stream/docs/wahoo/application-foundations

Wahoo provides explicit application foundations for request handling, configuration, sessions, tenant authorization, and rate limits.

> **Work in progress:** Do not use Wahoo in production yet.

## Start

Generated applications load visible runtime policy from `internal/config`.

```go
runtime.Use(
    server.SecurityHeaders(configuration.SecurityHeaders),
    server.MaxBodyBytes(configuration.JSONBodyLimit),
)
```

The generated configuration uses a 1 MiB JSON limit and a small response-header policy. Review it before deployment. Wahoo does not infer CORS, trusted proxies, TLS, HSTS, or CSRF policy.

## JSON APIs

Use the bounded JSON decoder for public API handlers.

```go
var input createProjectInput
if err := api.DecodeJSON(w, r, &input, 1<<20); err != nil {
    _ = api.WriteDecodeError(w, r, err)
    return
}
if fields := api.Validate(input); len(fields) > 0 {
    _ = api.WriteError(w, r, http.StatusBadRequest, "invalid_request", "check the request fields", fields...)
    return
}
```

The decoder requires `application/json`. It rejects unknown fields, trailing JSON values, and bodies over the selected limit. Error responses include the request ID when the request passed through `server.Server`.

## Sessions And CSRF

Store only `auth.TokenHash(rawToken)`, never the raw session token. Use `auth.AuthenticateSession` to check token hash, expiry, and revocation through an application store.

```go
session, err := auth.AuthenticateSession(r.Context(), sessions, rawToken, time.Now())
```

Use `auth.NewCSRFToken` and `auth.VerifyCSRFToken` only as primitives. The application must set secure cookies, select a CSRF pattern, rotate sessions, and revoke sessions at logout.

## Tenant Authorization

Resolve the authenticated subject and tenant in application middleware. Do not infer them from request headers.

```go
ctx := authz.WithScope(r.Context(), authz.Scope{
    SubjectID: "usr_123",
    TenantID:  "ten_123",
})
if err := authz.Require(ctx, authorizer, "project.read"); err != nil {
    // Map the error to the application response.
}
```

Every protected repository query must accept and constrain by the resolved tenant ID.

## Rate Limits

Use `server.RateLimit` with an application-defined key. The built-in `ratelimit.Memory` implementation bounds its key count and is safe only for one process.

```go
limiter, err := ratelimit.NewMemory(ratelimit.Policy{Limit: 10}, 10000)
runtime.Use(server.RateLimit(limiter, func(r *http.Request) string {
    return authenticatedUserID(r)
}))
```

Use a shared limiter for a multi-instance deployment. Do not trust forwarded client IP headers until the application defines trusted proxies.

## Database Readiness

Wahoo does not choose a database driver or migration format. Implement `database.Migrator` in the application and use bounded `database.Ready` checks for `/readyz`.

## Observe Requests

`server.Config.Observer` receives request ID, method, bounded path, status, bytes, duration, and panic state. Adapt it to the metrics or tracing system used by the application. Keep observers fast and bounded.

### Operations Primitives

URL: https://docs.cliamp.stream/docs/wahoo/operations-primitives

Wahoo provides provider-neutral contracts for operations code. It does not ship a queue, cloud adapter, SMTP client, payment provider, or billing system.

> **Work in progress:** Do not use Wahoo in production yet.

## Jobs

Use `jobs.Runner` with an application queue adapter. It pulls work only when a worker is free, keeps no in-memory backlog, and sets a 5-minute per-job deadline by default.

```go
runner, err := jobs.New(source, handler, jobs.Config{
    Workers:    4,
    JobTimeout: 2 * time.Minute,
})
if err != nil {
    return err
}
return runner.Run(ctx)
```

The queue adapter must define acknowledgement, retry delay, maximum attempts, dead-letter behavior, retention, and transactional outbox handling. Run workers as a workload separate from public HTTP.

## Storage

`storage.Store` defines bounded object operations. The application authorizes opaque object keys and chooses S3, GCS, R2, local storage, or another adapter. Do not expose provider keys or provider ACLs to browsers.

## Mail

`mail.Message` validates recipients and body bounds before an application `mail.Sender` sends it. Queue and retry mail from an application job handler. Do not add unbounded attachments to the mail path.

## Audit Events

`audit.Event` stores a bounded, immutable business event. Include the actor, target, outcome, and Wahoo request ID. The application owns retention, redaction, storage transactions, and audit-log access rules.

## Webhooks

Use `webhook.Verifier` to verify raw payload HMAC-SHA256 signatures with a bounded body and freshness window.

```go
body, err := verifier.ReadBody(r.Body)
if err != nil {
    return err
}
_, err = verifier.Verify(r.Header.Get("Webhook-Signature"), body)
```

Verification proves authenticity and bounded freshness. The application must atomically record provider delivery IDs and process events idempotently to prevent replay.

## Entitlements And Billing

`entitlement.Decide` evaluates normalized feature grants. `billing.Provider` defines checkout and normalized subscription access. `billing.UsageRecorder` records an idempotent metered event.

```go
checkout, err := provider.CreateCheckout(ctx, billing.CheckoutRequest{
    CustomerID: "cus_123",
    PriceID:    "price_team",
    SuccessURL: "https://app.example.com/billing/success",
    CancelURL:  "https://app.example.com/billing/cancel",
})
```

The application owns provider credentials, checkout authorization, webhook reconciliation, invoices, tax, payment recovery, usage aggregation, and conversion from subscription state to entitlement grants.

### Server and Routes

URL: https://docs.cliamp.stream/docs/wahoo/server-and-routes

Use `server.Server` to configure the public Go server and register routes.

## Create the Server

Create one server during process setup:

```go
runtime := server.New(server.Config{
    Addr:   ":8080",
    Logger: logger,
})
```

The zero values use these defaults:

| Setting | Default |
| --- | --- |
| Address | `:8080` |
| Read timeout | 15 seconds |
| Write timeout | 30 seconds |
| Idle timeout | 60 seconds |
| Shutdown timeout | 15 seconds |
| Logger | `slog.Default()` |

`Run` starts the server. It waits for `SIGINT`, `SIGTERM`, or context cancellation. It then drains active HTTP connections.

```go
if err := runtime.Run(context.Background()); err != nil {
    return err
}
```

## Register Routes

Wahoo uses `http.ServeMux` patterns. Go 1.22 method patterns work without an extra router.

```go
runtime.HandleFunc("GET /healthz", health)
runtime.HandleFunc("POST /api/projects", createProject)
runtime.Handle("GET /events", events)
```

Use `HandleFunc` for a function. Use `Handle` for an `http.Handler`.

Register a page route after you set a renderer:

```go
runtime.SetRenderer(ssr.NewRenderer())
if err := runtime.Page("GET /"); err != nil {
    return err
}
```

The `GET /` pattern handles page paths that do not match a more specific route.

## Return JSON

Use `server.JSON` to set the content type and encode a value:

```go
func health(w http.ResponseWriter, _ *http.Request) {
    _ = server.JSON(w, http.StatusOK, map[string]string{
        "status": "ok",
    })
}
```

Pass `0` as the status to use `200 OK`.

Define a stable error format in the application:

```json
{
  "error": {
    "code": "validation_failed",
    "message": "Check the highlighted fields.",
    "request_id": "..."
  }
}
```

Do not return internal database or provider errors to the browser.

## Return HTML

Use `server.HTML` for a small HTML response:

```go
_ = server.HTML(w, http.StatusOK, "<h1>Ready</h1>")
```

Use the SSR renderer for React pages. `TemplateRenderer` is useful for a small non-React page or a test fixture. It does not replace the React worker.

## Request Behavior

For each request, `Server`:

1. Uses `X-Request-ID` when the client sends one.
2. Creates an ID when the header is absent.
3. Adds `X-Request-ID` to the response.
4. Recovers a panic at the HTTP boundary.
5. Writes a structured completion log entry.

Add application middleware for authentication, authorization, request size limits, rate limits, CORS, and security headers. Wahoo does not add these policies by default.

## Read JSON Safely

The generated application includes `decodeJSON`. It rejects unknown fields:

```go
var input CreateProjectInput
if err := decodeJSON(r, &input); err != nil {
    _ = server.JSON(w, http.StatusBadRequest, errorResponse("invalid JSON"))
    return
}
```

Before you decode a public request, set an HTTP body limit. Validate every field after decoding.

## Test Routes

Use `httptest` for route tests:

```go
request := httptest.NewRequest(http.MethodGet, "/healthz", nil)
response := httptest.NewRecorder()
runtime.ServeHTTP(response, request)

if response.Code != http.StatusOK {
    t.Fatalf("status = %d", response.Code)
}
```

Test status codes, response JSON, cookies, authorization, and error cases.

### React SSR

URL: https://docs.cliamp.stream/docs/wahoo/react-ssr

Wahoo renders React through a private Node worker. Go stays the public server.

## Why Wahoo Uses a Worker

React runs in JavaScript. Go does not run a Vite React bundle by itself. The worker gives React a normal Node environment and lets Go keep control of HTTP, cookies, access checks, and deployment.

## Development Flow

Start the generated application:

```bash
npm install --prefix web
npm run dev --prefix web
```

The script starts Vite on port `4173` and Go on port `8080`. It sets:

```text
WAHOO_SSR_URL=http://127.0.0.1:4173/__wahoo_ssr
```

For a page request, the Go renderer:

1. Parses `WAHOO_SSR_URL`.
2. Adds the original request path and query as the `url` query value.
3. Sends the browser cookie header to the worker.
4. Requests the private `/__wahoo_ssr` route.
5. Returns the worker HTML when the response succeeds.

The Vite worker loads `src/entry-server.tsx`. React renders the `App` component. The browser then hydrates with `src/entry-client.tsx`.

## SSR Files

| File | Function |
| --- | --- |
| `web/src/entry-client.tsx` | Starts browser hydration. |
| `web/src/entry-server.tsx` | Renders the React document. |
| `web/dev-server.mjs` | Runs Vite SSR in development. |
| `web/ssr-server.mjs` | Runs the built SSR entry in production. |
| `internal/ssr/renderer.go` | Calls the private worker from Go. |

## Add Page Data

The starter renders a static page. Add page data in a controlled sequence:

1. Authenticate and authorize in Go.
2. Load the small, safe view model in Go.
3. Send only that view model to the worker.
4. Render the view model in React.
5. Serialize the same safe view model for browser hydration.

Do not send session tokens, password hashes, raw provider payloads, or unrestricted database records to the worker or browser.

Use a request deadline for each worker call. Use a small response size limit. Add these controls before production use.

## Build for Production

Build the frontend from the application root:

```bash
npm run build --prefix web
```

The build creates:

| Path | Content |
| --- | --- |
| `web/dist/assets` | Hashed browser CSS and JavaScript assets. |
| `web/dist/.vite/manifest.json` | Client asset manifest. |
| `web/dist/server/entry-server.js` | Node SSR entry point. |

Go serves `GET /assets/` from `web/dist/assets`. The production worker reads the manifest and inserts the correct asset paths into each document.

Start the worker and Go process from the application root:

```bash
npm run start:ssr --prefix web
WAHOO_SSR_URL=http://127.0.0.1:4173/__wahoo_ssr go run .
```

Do not expose port `4173` to the public network.

## Fallback Shell

If `WAHOO_SSR_URL` is unset or the worker request fails, the generated renderer returns a development client shell. This supports Go-only local work.

Do not use this fallback as a production recovery method. It references development modules. Treat a missing SSR worker as a deployment error for public pages.

## Add Streaming Later

The starter uses `renderToString`. Use streaming only after you measure a page that needs it.

To add streaming:

1. Replace `renderToString` with a React streaming API.
2. Make the worker send a chunked response.
3. Stream the worker response through Go.
4. Set a render timeout and error boundary.
5. Test client hydration and cancellation.

Keep the first implementation small. SSR correctness matters more than streaming speed.

### Wahoo Documentation

URL: https://docs.cliamp.stream/docs/wahoo/wahoo-documentation

Wahoo is a Go, React, and Tailwind SaaS framework. Go owns public HTTP. React renders through a private Node SSR worker.

> **Work in progress:** Do not use Wahoo in production yet. APIs and templates can change.

## Start

```bash
go run ./cmd/wahoo new --local ./acme
```

The command creates a core application with explicit configuration, health/readiness routes, a private SSR boundary, strict JSON helpers, and a project metadata file.

## What Wahoo Provides

- Go HTTP lifecycle, request IDs in context, panic recovery, bounded logs, middleware, and request observations.
- Explicit security-header, body-limit, and rate-limit middleware contracts.
- Strict bounded JSON decoding with a stable error envelope.
- Password, opaque-token, session, CSRF, and tenant-authorization primitives.
- Migration/readiness contracts without a database driver lock-in.
- Bounded SSE/WebSocket transports with scoped event topics.
- Provider-neutral jobs, storage, mail, audit, webhook, entitlement, billing, and usage contracts.
- OpenAPI, worker, Docker supervisor, release installer, and conservative upgrade tooling.

## Modules

| Module | State |
| --- | --- |
| `auth`, `sse`, `websocket` | Browser-facing `501` stubs until application policy exists. |
| `openapi` | Serves an application-owned OpenAPI 3.1 document. |
| `jobs` | Adds a separate worker command that requires a queue adapter. |
| `uploads`, `mail`, `audit`, `webhooks`, `entitlements`, `billing` | Provider-neutral `501` integration seams. |

## Application Responsibilities

- Database driver, migrations, repositories, and backups.
- Cookie lifecycle, session storage, CSRF design, OAuth, and MFA.
- Tenant resolution, domain authorization, and shared rate-limit storage.
- Queue, object storage, mail, payment, and billing providers.
- Webhook replay protection, idempotency, audits, monitoring, and incident response.

## Guides

| Guide | Use it to |
| --- | --- |
| [Quick Start](quick-start.md) | Create, test, add modules, and upgrade a project. |
| [Application Foundations](application-foundations.md) | Configure APIs, sessions, tenants, readiness, and observations. |
| [Operations Primitives](operations-primitives.md) | Add jobs, storage, mail, audits, webhooks, and entitlements. |
| [Server and Routes](server-and-routes.md) | Register routes and return HTML or JSON. |
| [React SSR](react-ssr.md) | Run the private React renderer. |
| [Realtime](realtime.md) | Add authenticated realtime transports. |
| [Authentication](authentication.md) | Implement account and session flows. |
| [Production](production.md) | Build, secure, verify, and deploy the application. |

## omadji

### Introduction

URL: https://docs.cliamp.stream/docs/omadji/introduction

Omadji is a Linux desktop app that reviews and copies DJI camera media. It helps you check a card, select media, copy files, and verify the result.

![Omadji reviewing DJI camera media](/uploads/white-rose/omadji/5490b0a2c8d14e3af20276872e6a8d24.png)

## What You Can Do

- Review MP4, JPEG, and DNG media on a mounted DJI card.
- Preview video from a local LRF proxy when it is available.
- Inspect video and photo metadata.
- Copy selected files and verify each copy with xxHash64.
- Delete selected originals only after confirmation.
- Use Light, Dark, or Omarchy color modes.

## Before You Start

You need a Linux desktop, a mounted DJI storage card, and enough free space at the copy destination. Install `ffprobe` for video inspection and `xxhsum` for copy verification.

## Next Steps

1. [Install Omadji](/docs/omadji/install-omadji).
2. [Copy media safely](/docs/omadji/copy-media-safely).
3. Read [Media and metadata support](/docs/omadji/media-and-metadata-support).

### Install Omadji

URL: https://docs.cliamp.stream/docs/omadji/install-omadji

Omadji is a Qt 6 application for Linux. It installs in your user directory. You do not need root access.

## Requirements

Install these tools before you build Omadji:

- Qt 6.8 or later with Core, Gui, Qml, Quick, Quick Controls, Multimedia, and Concurrent.
- CMake 3.21 or later.
- A C++20 compiler.
- FFmpeg, which provides `ffprobe`.
- xxHash, which provides `xxhsum`.

## Build

Run this command from the project directory:

```bash
make build
```

The executable is `build/omadji`.

To start the build output, run:

```bash
make run
```

## Install

Install Omadji in `~/.local`:

```bash
make install
```

This installs the executable, desktop entry, and application icon. Start the installed app with:

```bash
omadji
```

If the command is not available, add `~/.local/bin` to your `PATH` and start a new shell.

## Remove

Remove the installed files:

```bash
rm ~/.local/bin/omadji
rm ~/.local/share/applications/omadji.desktop
rm ~/.local/share/icons/hicolor/256x256/apps/omadji.png
```

Build output stays in the project `build` directory. Remove it when you no longer need it.

### Copy Media Safely

URL: https://docs.cliamp.stream/docs/omadji/copy-media-safely

Use Omadji to review a DJI card before you copy its media.

## 1. Connect the Card

Mount the DJI card on your Linux system. Start Omadji. The source panel shows the card name, capacity, used space, and free space.

If the card does not appear, click `REFRESH`. See [Configuration and troubleshooting](/docs/omadji/configuration-and-troubleshooting) if the card is still not found.

## 2. Review Media

Use the All, Video, and Photo tabs to filter the card contents. Use the text and date filters to reduce the list.

Select a card to add it to the copy set. Select a range with Shift and a second selection. Use `SELECT ALL` to select all visible items.

For a video, use the preview button to play its LRF proxy. For a photo, use the view button to open the image. Select an item to show its details in the inspector.

## 3. Select a Destination

The destination panel shows the current destination path and its free space. Click `CHOOSE FOLDER...` to set a different destination.

Make sure the destination has enough free space for the selected media. The footer shows the size of the current selection.

## 4. Copy and Verify

Keep `VERIFY XXH64` selected to verify every copied original file. Click `COPY` to start the transfer.

Omadji does not overwrite an existing file with the same name. It reports that the file is already in the destination.

The footer shows the transfer state and result. Do not disconnect the card while the transfer is in progress.

## 5. Optional Eject

Select `EJECT AFTER COPY` before you start the transfer if you want Omadji to eject the source card after a successful copy and verification.

The app uses `udisksctl` to eject the card. The desktop environment can ask for permission.

## Delete Files

`DELETE` removes the selected original files from the card. For video files, Omadji also removes matching LRF, THM, and SCR files.

Delete only after you verify the copied files. The delete dialog asks for confirmation. This action cannot be undone.

### Media and Metadata Support

URL: https://docs.cliamp.stream/docs/omadji/media-and-metadata-support

Omadji finds media recursively on the mounted DJI card.

## Media Types

| Type | Extension | Use in Omadji |
| --- | --- | --- |
| Video original | `.MP4` | Copy and inspect |
| Video proxy | `.LRF` | Preview support |
| JPEG photo | `.JPG`, `.JPEG` | View, copy, and inspect |
| DNG photo | `.DNG` | Copy and list |
| Subtitle sidecar | `.SRT` | Detect as telemetry sidecar |
| Video sidecar | `.THM`, `.SCR` | Remove with deleted video |

Omadji copies selected original media. It does not copy LRF, THM, SCR, or SRT sidecars as selected media.

## Live Webcam Preview

Click `WEBCAM` in the top bar to open a live preview. Omadji lists UVC webcams that Qt Multimedia can detect and prefers a device named DJI or Osmo when one is connected.

To use a DJI camera, connect it by USB and set its USB connection mode to Webcam. Select the DJI device from the camera list. Click `RESTART` after you change a camera mode or device.

The webcam preview does not record video or audio. It stops the camera stream when you close the popup.

## Video Inspection

Omadji uses `ffprobe` to show video duration, resolution, frame rate, bit rate, codec, and profile.

For supported DJI Osmo Action 4 MP4 files, Omadji reads embedded DJI metadata. The inspector can show ISO, shutter time, white balance, fixed aperture, and motion telemetry.

Osmo Action 4 files do not record exposure value in the embedded metadata. Omadji shows `Not recorded` for this field.

## JPEG Inspection

Omadji reads standard JPEG EXIF data without an external EXIF program. The inspector can show:

- Camera model.
- ISO sensitivity.
- Exposure time.
- Aperture.
- Exposure bias.
- White balance mode.
- Pixel dimensions.

Some camera files can omit fields. Omadji shows `Unavailable` when the file has no value for a field.

## Video Preview

Omadji uses the matching `.LRF` file as the preview source. It does not decode the original MP4 for preview.

If no LRF file is available, the card still shows the video. The preview action is unavailable.

### Configuration and Troubleshooting

URL: https://docs.cliamp.stream/docs/omadji/configuration-and-troubleshooting

## Color Mode

Click the mode button in the top bar to change the color mode.

### Omarchy

`OMARCHY` uses the active Omarchy palette for app surfaces. Omadji reads this file when it is available:

```text
~/.local/state/omarchy/current/theme/colors.toml
```

It updates the surface colors after a theme change. Text, controls, borders, selection, and status colors use Omadji's fixed palette for readable contrast.

### Light and Dark

`LIGHT` and `DARK` use built-in palettes. Omadji saves the selected mode in the Qt application settings.

![Dark mode](/uploads/white-rose/omadji/05a6b46c8360646726731a438e360163.png)

## Card Is Not Found

Do these steps:

1. Make sure the card is mounted.
2. Open the card in your file manager. Confirm that you can read its `DCIM` directory.
3. Click `REFRESH` in Omadji.
4. Confirm that the card contains supported media files.

Omadji searches mounted storage volumes. It does not mount a card itself.

## No Video Preview

Check that the card has a matching `.LRF` proxy file. Omadji uses the proxy for video preview.

Also confirm that Qt Multimedia can play H.264 or H.265 files on your system. Install the media codecs for your distribution when necessary.

## Copy Verification Fails

Omadji uses `xxhsum` for xxHash64 verification. Install the xxHash package for your distribution, then repeat the copy.

Do not delete card files if verification fails. Check the destination storage, reconnect the card, and copy the affected files again.

## Video Details Are Unavailable

Install FFmpeg so that `ffprobe` is available on your `PATH`:

```bash
ffprobe -version
```

If the command fails, install the FFmpeg package from your distribution.

## Eject Does Not Work

Omadji calls `udisksctl` for ejection. Confirm that the tool is available:

```bash
udisksctl --version
```

The desktop environment can require authentication. Close other programs that use the card, then try the transfer without automatic ejection and eject the card from the desktop environment.
