# Quikcast: configuration guide for AI agents

This file is the complete documentation for configuring **Quikcast**, a self-hosted audio streaming server (an Icecast/SHOUTcast-style server written in Rust). It is written for AI agents that need to produce, edit, validate or troubleshoot a Quikcast configuration without any other context. It is generated by `docs/scripts/build-ai-md.mjs` from the project's own docs (`docs/guide`, `docs/reference`) and example configs (`config/`); where this file and the code disagree, the code wins.

## How to use this file

1. Read **"Core facts"** and **"Agent workflow"** below first. They are enough for most tasks.
2. Use the **"Task recipes"** to find the smallest config for what the user wants.
3. Look up exact keys, defaults and ranges in **Part 5 (Configuration reference)** or **Appendix A** (one TOML file listing every option with its default).
4. Always finish by running `quikcast --config <file> --check`.

## Core facts

- **Configuration is one TOML file** (max 128 KiB), passed with `--config PATH` or the `QUIKCAST_CONFIG` environment variable. There is no built-in default location; the service that the install script sets up uses `/etc/quikcast/quikcast.toml`.
- **Unknown keys are rejected at startup.** A typo is an error, never silently ignored. Do not invent keys; only use keys that appear in this file.
- **Root keys first.** `listen`, `admin_listen` and `log_filter` must come before the first `[table]` header, or TOML assigns them to that table.
- **`*_file` paths resolve relative to the config file's directory**, not the working directory. `~` and `$VARIABLES` are not expanded.
- **Secrets live in files**, referenced with `secret_file`/`token_file`/`password_file`. Secrets are 16-512 bytes; one final newline is stripped. Generate one with `openssl rand -hex 16 > secrets/radio-source`. Inline `secret = "..."` exists but prefer files. For every credential setting, set **exactly one** of the file or inline form.
- **Use a distinct secret per scope** (each mount, the HLS ingest credential, the management token, signing keys). The HLS secret must differ from every mount secret.
- **Usernames** are 1-64 ASCII graphic bytes, no whitespace or `:`. The default source username is `source`.
- **Two listeners.** `listen` (default `127.0.0.1:8000`) is public: listeners, encoders, HLS. `admin_listen` (default `127.0.0.1:9090`) is private and **must be a loopback address** unless `[management] allow_remote = true` is set (which also needs a token; see Part 5): it serves `/health/live`, `/health/ready`, `/metrics`, the management API and the HLS ingest API. In Docker set `listen = "0.0.0.0:8000"` and keep `admin_listen` on loopback; never publish the admin port.
- **A mount** is a stream path such as `/radio.mp3` fed by one encoder at a time. Paths start with `/`, have no trailing `/`, use only letters, digits and `/ . _ - ~`, are case-sensitive and canonical, and must not be `/` or sit under the reserved prefixes `/api`, `/admin`, `/internal`, `/health`, `/metrics`, `/hls`, `/ui`, `/console`. Nested paths such as `/stations/jazz` are fine; there is no parent/child relationship between `/stations` and `/stations/jazz`. 1 to `limits.max_mounts` static mounts (default 64, max 1024).
- **Mounts need credentials** (`secret_file` or `secret`) unless `[sources]` supplies usable global source credentials.
- **Playlist files.** Appending `.m3u`, `.pls` or `.xspf` to a mount path (for example `/stations/jazz.m3u`) returns a one-entry playlist pointing at the stream. See "Playlist files" in Part 2.
- **Reloading.** `kill -HUP <pid>` reloads policy, proxy, credential, fallback, relay and HLS CORS/auth settings atomically; a failed reload keeps the old config. Adding or removing a `[[mounts]]` also reloads: a new stream appears without touching the others, and a removed one disconnects its encoder and listeners. Listening addresses, a mount's `listener_limit`, enabling/disabling `[tls]`, every `[limits]` value and HLS capacity settings need a **restart**. Full table: "What can be reloaded" in Part 5.
- **Logs** go to standard output, which must be a terminal, pipe or socket (not a regular file). `QUIKCAST_LOG` overrides `log_filter`.

## Agent workflow

1. **Clarify the goal** only if needed: which stream path(s), where encoders connect from, whether TLS is terminated by Quikcast or a proxy, whether listeners are public, signed or restricted.
2. **Start from the smallest config** that works (recipes below), then add features one table at a time.
3. **Create the secret files** the config references (`mkdir secrets && openssl rand -hex 16 > secrets/radio-source`). Never print or commit secret contents.
4. **Validate**: `quikcast --config quikcast.toml --check`. It parses the file, reads every secret, list, certificate and database, and prints `<file>: configuration ok` (exit 0) or the exact failing setting (exit 1). It never starts the server and never prints secrets. Fix and re-run until it passes.
5. **Apply**: restart, or `kill -HUP` if only reloadable settings changed.
6. **Verify**: `curl http://127.0.0.1:9090/health/ready` (should print `ready`), `curl http://127.0.0.1:9090/metrics`, and connect a test encoder (see Part 1, "Connect an encoder", and the FFmpeg test-tone command in the quickstart).

## Minimal config

```toml
[[mounts]]
path = "/radio.mp3"
secret_file = "secrets/radio-source"
```

Everything else has defaults (listens on `127.0.0.1:8000`, admin on `127.0.0.1:9090`). An encoder connects to `http://HOST:8000/radio.mp3` with username `source` and the secret as password; listeners play the same URL.

## Task recipes

Each recipe is a fragment to merge into the config. Details and all options are in the referenced parts.

| Goal | Add this | Read |
|---|---|---|
| Public radio on a LAN/internet host | `listen = "0.0.0.0:8000"` (root key, before any table) | Part 3, "HTTPS and proxies" |
| Native HTTPS | `[tls]` with `cert_file` and `key_file` (PEM). Omit to terminate TLS in a proxy. With the install script: `qc tls --domain NAME`. | Part 3 |
| Behind a reverse proxy / CDN, real client IPs | `[trusted_proxies]` with `ips = [...]`, or `providers = ["cloudflare"]`, or `proxy_protocol = true` | Part 3 |
| Backup stream when the encoder drops | On the mount: `fallback = "/backup.mp3"` (another configured mount; chains up to 8) | Part 2, "Backup streams" |
| Rebroadcast someone else's stream | `[[relays]]` with `mount`, plus `url`, `urls` or `upstreams` (exactly one). The mount must exist under `[[mounts]]` and is then owned by the relay (no encoder). Max 64 relays. | Part 2, "Relay another station" |
| Copy every stream of another Quikcast server | `[primary]` (list sharing, with a replica password) on the server with encoders; `[replica]` (`primary` address, password) on the other. No `[[mounts]]` needed on the replica. | Part 2, "Primary and replica" |
| Browser/app friendly HLS | `[hls]` with `secret_file` (differs from mount secrets); an encoder pushes segments to the admin-side ingest API | Part 2, "HLS", and the HLS ingest API |
| Limit who can listen (IP, user agent, country) | Global `[access]` and/or per-mount `[mounts.access]` (ANDed) | Part 3, "Limit who can listen" |
| Expiring private links | Per mount `[mounts.listener_auth]` with `type = "signed_url"` and `secret_file` | Part 3, "Signed, expiring links" |
| Restrict which IPs may connect encoders | `[mounts.source_access]` (IP only; credentials still apply) | Part 3 |
| Let encoders create mounts on demand | `[sources]` with `allow_dynamic_mounts = true` plus `username` and `secret_file`/`secret` | Part 2, "Streams and mounts" |
| Management API (automation) | `[management]` with exactly one of `token_file` / `token`. Without it every `/api` request is rejected. | Part 5, "Management API" |
| Operator web console | `[console]` (alias `[ui]`; use one spelling per file) with `enabled = true`, `mode`, `username`, `password_file`; `secure_cookie = true` behind HTTPS | Part 4, "Operator console" |
| Public "is the station live?" page | `[console]` with `enabled = true` and `mode = "public"` (or `"both"`). It lists every mount, including encoder-created ones, unless `public_mounts` names some (configured mounts only) or is `[]`. | Part 4, "Operator console" |
| Handle more listeners / tune memory | `[limits]` (restart). Startup rejects combinations whose memory budgets do not fit; the message says how much. | Part 5, "Capacity and limits" |
| Deploy in Docker/Dokploy | Start from Appendix C; `listen = "0.0.0.0:8000"`, admin stays loopback | Part 4, "Deploy on Dokploy" |

## Common mistakes

- Putting `listen`/`admin_listen`/`log_filter` after a `[table]` header.
- Setting both `secret` and `secret_file` (or neither) on a mount, HLS, `[sources]` or `[management]`.
- Using paths relative to the shell instead of the config file.
- A non-loopback `admin_listen` without `[management] allow_remote = true` and a token (rejected at startup).
- A `[[relays]]` `mount` that does not match a `[[mounts]]` `path` exactly.
- A `fallback` that names a mount that is not configured.
- Reusing one secret for several mounts or for HLS.
- An empty `ip_allow_file` (an allow list with no rules would admit everyone, so it is rejected; an empty deny file is fine).
- Testing a country allow list from `127.0.0.1`: private addresses have no country and fail the allow list.
- Expecting `kill -HUP` to change `[limits]` or a mount's `listener_limit`; those need a restart. Removing a `[[mounts]]` entry on reload disconnects its encoder and listeners.
- Redirecting stdout to a regular file (use a pipe, `tee`, systemd or Docker).
- Forgetting that a mount is `404` for listeners until an encoder is connected; Quikcast does not serve silence.

## Command line, in brief

```text
quikcast [--config PATH] [--check]      # --check validates and exits; -h/--help; -V/--version
```

Signals: `SIGHUP` reload (all or nothing), `SIGTERM`/`SIGINT` graceful shutdown. Exit code `0` success, `1` error. Full detail in Part 5, "Command line and signals".

## Installing and managing on Linux (install script and `qc`)

On Linux, the install script installs `quikcast` and a helper called `qc` into `/usr/local/bin`:

```text
curl -fsSL https://rpstatic.streamafrica.net/quikcast/install.sh | sh                 # binary + qc
curl -fsSL https://rpstatic.streamafrica.net/quikcast/install.sh | sh -s -- --service # also a systemd service, user and starter config
```

With `--service` the configuration is `/etc/quikcast/quikcast.toml` and secrets are in `/etc/quikcast/secrets/`. Prefer `qc` to hand-editing there: every change is made on a copy, validated with `--check`, and only then saved (the previous file is kept as `quikcast.toml.bak`).

| Command | What it does |
|---|---|
| `qc setup`, `qc menu`, `qc info`, `qc doctor` | Guided setup, a menu, a one-screen summary, a health check that explains problems |
| `qc listen ADDR` | Set the public address, for example `0.0.0.0:8000` |
| `qc tls --domain NAME` (repeatable), `qc tls --cert F --key F`, `qc tls off` | HTTPS with a free Let's Encrypt certificate (one certificate for all names; needs certbot), or your own |
| `qc console on [--status-page]`, `qc console off` | The operator console and the optional public status page |
| `qc management on [--ip ADDR]... [--any-ip --yes] [--local] [--port N]`, `qc management off` | The management API: private to this machine, or reachable from the given IPs, with its own token and HTTPS when available |
| `qc password [reset encoder\|console\|management\|all]` | Show or replace the encoder, console and management secrets |
| `qc config`, `qc check` | Edit the config safely; validate it |
| `qc update [--restart]`, `qc rollback`, `qc version` | Update, undo an update, show versions |
| `qc status\|start\|stop\|restart\|reload`, `qc logs [-f]` | Control the service. Changing the address, HTTPS or remote management needs a restart; most other settings apply with `qc reload`. |

## Table of contents

- Part 1: Getting started: What is Quikcast?, Install, Quickstart, Connect an encoder
- Part 2: Streaming: Streams and mounts, Backup streams (fallback), Relay another station, Primary and replica servers, HLS for browsers and apps, Icecast-compatible admin API
- Part 3: Security: Limit who can listen, Signed, expiring links, HTTPS and proxies
- Part 4: Running it: Operator console, Monitoring, Production checklist, Deploy on Dokploy, Troubleshooting
- Part 5: Reference: Configuration reference, Command line and signals, Management API, HLS ingest API, Metrics, Capacity and limits, Glossary
- Part 6: Client libraries: Client libraries, PHP client
- Appendix A: config/quikcast.reference.toml (every option, commented)
- Appendix B: config/quikcast.example.toml (short starting point)
- Appendix C: config/quikcast.docker.toml (container starting point)

Internal cross-references in the pages below read `(see "Page title")` and point at another page in this file.

---

# Part 1: Getting started

## What is Quikcast?

Quikcast is a server that sends live audio from an **encoder** (the software that captures your show) to many **listeners** (people with a player). If you have used Icecast or SHOUTcast, you know the idea. Quikcast does the same job with one small program and one configuration file.

```mermaid
flowchart LR
  E["Your encoder<br/>BUTT, Liquidsoap, FFmpeg"] -->|audio| Q["Quikcast<br/>mount: /radio.mp3"]
  U["Another station"] -.->|relay| Q
  Q -->|audio| P1["Browser"]
  Q -->|audio| P2["Phone app"]
  Q -->|audio| P3["VLC"]
```

### The four words you need

| Word | What it means |
|---|---|
| **Source** or **encoder** | The program that sends audio *to* Quikcast, such as BUTT or Liquidsoap. |
| **Mount** | One stream, identified by a URL path like `/radio.mp3`. An encoder feeds a mount; listeners play it. |
| **Listener** | Anyone playing a mount. |
| **Relay** | Quikcast pulling a stream *from* somewhere else and publishing it on one of your mounts. |

The full list is in the "Glossary".

### What you get

- **All the common formats.** MP3, AAC, Opus, Vorbis (Ogg) and FLAC.
- **Backups.** If a source drops, new listeners can be sent to a backup mount automatically.
- **Relays.** Rebroadcast an Icecast or SHOUTcast stream, with backup upstreams if the first one fails. Audio-only HLS upstreams are supported but experimental (see "Relay another station").
- **HLS.** Serve the segmented streams that browsers and phone apps prefer.
- **Access control.** Allow or block listeners by IP, country or player, or use expiring links your own app signs.
- **HTTPS.** Built in, with certificate renewal on a config reload. Or put a proxy in front.
- **A console and an API.** A web console for live status and a public status page, plus a JSON API and Prometheus metrics for automation.
- **Safe to operate.** Memory use is bounded, a slow listener can never slow down others, and a bad config change is refused instead of half-applied.

### What it does not do

- **It does not encode or mix audio.** Quikcast forwards audio that is already encoded. Use BUTT, Liquidsoap or FFmpeg to produce it.
- **It is not an auto-DJ.** Scheduling, playlists and live-over-automation switching belong in a tool such as Liquidsoap (see below).
- **It does not store history.** Listener statistics live in memory and reset on restart. Scrape the "Metrics" if you want long-term graphs.
- **It has no user accounts.** Access is controlled by passwords, network rules and signed links that your own application issues.

### How it fits with Icecast and Liquidsoap

If you are coming from Icecast, encoders connect the same way, so BUTT, Liquidsoap and FFmpeg settings carry over. Configuration is different: Quikcast uses TOML, and unknown or misspelled settings are rejected at startup instead of being silently ignored.

If you use Liquidsoap, keep it. Liquidsoap decides what plays (playlists, a live DJ taking over, jingles) and Quikcast delivers the result to your audience.

### Where next?

1. Install Quikcast (see "Install")
2. Run the quickstart (see "Quickstart")
3. Connect your real encoder (see "Connect an encoder")

## Install

The install script sets up the single program, `quikcast`. The console and the country database are built in, so there is nothing else to install.

### Requirements

Quikcast is one program with no database and no other runtime.

**Supported systems.** Linux on x86_64 or arm64 with glibc 2.35 or newer.

<div class="distros">
  <span><img src="/images/distros/ubuntu.svg" alt="" /> Ubuntu <small>22.04 or later</small></span>
  <span><img src="/images/distros/debian.svg" alt="" /> Debian <small>12 or later</small></span>
</div>

Other distributions with glibc 2.35 or newer also work. Alpine (musl) is not supported. Running it as a service needs systemd.

**Minimum resources.**

- **1 vCPU and 512 MB of RAM.** Audio is passed through, not re-encoded. One mount with 1,000 listeners used about a third of a core and 65 MB in testing.
- **50 MB of disk.** The program is about 15 MB.
- **Bandwidth is the real limit.** Each listener downloads the stream's bitrate, so 1,000 listeners on a 128 kbps stream need about 128 Mbps of upload.

For larger audiences see "Capacity and limits".

### Install script (recommended)

One command installs the `quikcast` program and the `qc` helper into `/usr/local/bin`, so you can run `quikcast` from anywhere:

```sh
curl -fsSL https://rpstatic.streamafrica.net/quikcast/install.sh | sh
quikcast --version
```

The script checks that your system is supported, verifies the download against its published SHA-256 checksum, and refuses to install if it does not match. Run it again at any time to update.

To also run Quikcast as a background service that starts on boot, add `--service`:

```sh
curl -fsSL https://rpstatic.streamafrica.net/quikcast/install.sh | sh -s -- --service
```

On a first install from a terminal, the script offers to run `qc setup`, a guided setup that asks who should reach your stream and sets up HTTPS if you want it. Scripts and CI never get a prompt.

That creates a `quikcast` system user, a starter configuration in `/etc/quikcast/quikcast.toml` with the "Operator console" already on, generated passwords for encoders and for the console in `/etc/quikcast/secrets/`, and a systemd service, then starts it. Show the passwords with `qc password`. An existing configuration is never overwritten. The server listens on `127.0.0.1:8000` until you change `listen`.

| Option | What it does |
|---|---|
| `--version X.Y.Z` | Install a specific version instead of the latest. |
| `--service` | Set up the systemd service and starter configuration (needs systemd and root). |
| `--listen ADDR` | Public address for a new configuration, such as `0.0.0.0:8000`. The default only accepts connections from the machine itself. |
| `--domain NAME` | Serve HTTPS on port 443 with a free Let's Encrypt certificate. Repeat it, or separate names with commas, for one certificate covering several names. Needs `certbot`, DNS pointing at the server and port 80 free. Accepts the Let's Encrypt terms, renews automatically and reloads Quikcast. |
| `--email ADDR` | Contact address for Let's Encrypt, with `--domain`. |
| `--tls-cert FILE`, `--tls-key FILE` | Serve HTTPS on port 443 with your own certificate and key. |
| `--prefix DIR` | Install into `DIR` instead of `/usr/local/bin`. |
| `--restart` | Restart the service after installing. |

`--listen`, `--domain` and `--tls-*` are applied with `qc listen` and `qc tls` (below). The previous configuration is kept as `quikcast.toml.bak`, and a change that fails the configuration check is not applied. The service may bind ports below 1024, so 443 works without root.

### Manage Quikcast with `qc`

`qc` is installed next to `quikcast`. Setup commands:

| Command | What it does |
|---|---|
| `qc setup` | Guided setup: service, public address and HTTPS. Safe to run again. |
| `qc listen [ADDR]` | Show or change the public address, such as `0.0.0.0:8000`. |
| `qc tls --domain NAME [--domain NAME2]` | HTTPS on port 443 with one free Let's Encrypt certificate covering every name (needs `certbot`). Renewals are copied in and reloaded automatically. |
| `qc tls --cert FILE --key FILE` | HTTPS with your own certificate. |
| `qc tls off` | Serve plain HTTP again. |
| `qc menu` | A guided menu for everything below. |
| `qc info` | One-screen summary of this server. |
| `qc management [on \| off]` | Set up the management API for panels and scripts. Asks who may connect (this machine, specific IPs, or anyone), whether to use HTTPS, and generates its own token. |
| `qc console [on \| off]` | Show, enable or disable the web dashboard. `on --status-page` also publishes a small public status page. |
| `qc password [reset encoder\|console\|all]` | Show or replace the encoder and console passwords. |
| `qc config` | Edit the configuration; it is checked before it is saved. |
| `qc doctor` | Check the install and explain what is wrong, such as an address that only accepts local connections or a blocked port. |

Quikcast serves a single certificate, so several domains share one certificate that lists all of them. Every name must point at this server, and port 80 must be free while the certificate is requested. `qc tls` also keeps the console's cookie and public address in step with HTTPS. Changing the address or turning HTTPS on or off needs a restart: add `--restart` or run `qc restart`. Every change keeps the previous file as `quikcast.toml.bak`.

Updating and running:

| Command | What it does |
|---|---|
| `qc update` | Install the latest version. Your running station keeps playing until you restart it. |
| `qc update --restart` | Update and restart the service. |
| `qc rollback` | Go back to the previous version. |
| `qc version` | Show the installed and the latest version. |
| `qc check [CONFIG]` | Validate a configuration (default `/etc/quikcast/quikcast.toml`). |
| `qc status`, `start`, `stop`, `restart` | Control the service. |
| `qc reload` | Apply configuration changes without dropping listeners. |
| `qc logs [-f]` | Show the service log. |
| `qc uninstall [--purge]` | Remove Quikcast. `--purge` also deletes `/etc/quikcast`. |

An update replaces the program file but does not restart a running server, because a restart disconnects listeners. Apply it with `qc restart` when you are ready, or drain first (see "Production checklist").

### Check your install

Write a small config and let Quikcast validate it without starting:

```sh
quikcast --config quikcast.toml --check
```

It prints `configuration ok` when all is well. The "Quickstart" walks through the file.

## Quickstart

A working radio station on your own machine in about five minutes. You need Quikcast installed (see "Install"). The test tone uses [FFmpeg](https://ffmpeg.org/); to use BUTT instead, skip to "Connect an encoder".

### 1. Make a folder and a password

Your encoder needs a password to broadcast. Quikcast reads it from a file, so it never sits in your config.

```sh
mkdir quikcast && cd quikcast
mkdir secrets
openssl rand -hex 16 > secrets/radio-source
```

That makes a random 32-character password. Anything from 16 to 512 bytes works.

### 2. Write the config

Create `quikcast.toml`:

**quikcast.toml**

```toml
[[mounts]]
path = "/radio.mp3"
secret_file = "secrets/radio-source"
```

That's the whole file: one **mount**, a stream at `/radio.mp3`, and where its password lives. Everything else has a default, including listening on `127.0.0.1:8000`.

> **Note: Paths are relative to the config file**
>
> `secrets/radio-source` is looked up next to `quikcast.toml`, wherever you start the program from.

### 3. Check it, then start it

```sh
quikcast --config quikcast.toml --check
# quikcast.toml: configuration ok

quikcast --config quikcast.toml
```

`--check` reads every file your config mentions and reports any problem without starting the server. Use it before every change.

Look for the log line `quikcast accepting connections`, and leave this window open.

### 4. Send some audio

In a second terminal, from the same folder, play a 440 Hz test tone into your mount:

```sh
ffmpeg -re -f lavfi -i "sine=frequency=440" \
  -c:a libmp3lame -b:a 128k -content_type audio/mpeg -f mp3 \
  "icecast://source:$(cat secrets/radio-source)@127.0.0.1:8000/radio.mp3"
```

The username is `source` (the default), and the password is the contents of your secret file.

### 5. Listen

Open this in a browser, VLC, or any media player:

```text
http://127.0.0.1:8000/radio.mp3
```

You should hear the tone.

### 6. Look around

Quikcast also runs a private admin address, only reachable from your own machine:

```sh
curl http://127.0.0.1:9090/health/ready
curl http://127.0.0.1:9090/metrics | head
```

`/health/ready` answers `200` when the server is accepting work. `/metrics` is for monitoring tools.

### What just happened?

```mermaid
sequenceDiagram
  participant F as FFmpeg (encoder)
  participant Q as Quikcast
  participant P as Your player
  F->>Q: connects to /radio.mp3 with the password
  Q-->>F: accepted, you own this mount
  P->>Q: GET /radio.mp3
  Q-->>P: live audio
```

FFmpeg authenticated as the owner of `/radio.mp3` and sent audio, and Quikcast passed it to your player. If you stop FFmpeg the stream ends; players reconnect when the encoder returns.

### Next steps

- Use a real encoder: "Connect an encoder"
- Add more streams or a backup: "Streams and mounts", Backup streams (see "Backup streams (fallback)")
- Make it reachable from the internet safely: "HTTPS and proxies"
- See every setting: "Configuration reference"

## Connect an encoder

An **encoder** captures your microphone, mixer or playlist, compresses it and sends it to Quikcast. Anything that can broadcast to Icecast works, with the same few settings.

### The values you need

| Setting | Value | Where it comes from |
|---|---|---|
| Server type | Icecast | Quikcast speaks the Icecast source protocol. |
| Host | Your server's address, for example `127.0.0.1` | The machine running Quikcast. |
| Port | `8000` | Your `listen` setting. |
| Mount or mountpoint | `/radio.mp3` | The `path` of the mount. |
| Username | `source` | The mount's `username` (default `source`). |
| Password | The contents of the mount's secret file | `secret_file`. |

> **Tip: Which format?**
>
> The file extension in the mount name does not choose the format. What your encoder sends decides it. See the supported formats (see "Streams and mounts"). MP3 and AAC work almost everywhere.

### BUTT

[BUTT](https://danielnoethen.de/butt/) (broadcast using this tool) is a popular free encoder.

1. Open **Settings → Main → Server → ADD**.
2. Fill in:
   - **Name:** anything, for example `Quikcast`
   - **Type:** `Icecast`
   - **Address:** your server address
   - **Port:** `8000`
   - **Password:** your source password
   - **Icecast mountpoint:** `/radio.mp3`
   - **Icecast user:** `source`
3. Under **Audio**, pick the codec (MP3 at 128 kbit/s is a good start) and your input device.
4. Close the settings and press the **play** button.

### Liquidsoap

[Liquidsoap](https://www.liquidsoap.info/) is the usual choice when you want playlists or a live DJ taking over from automation. It decides what plays; Quikcast delivers it.

```ruby
radio = playlist("/music")

output.icecast(
  %mp3(bitrate=128),
  host="127.0.0.1",
  port=8000,
  user="source",
  password="REPLACE_WITH_YOUR_PASSWORD",
  mount="/radio.mp3",
  radio
)
```

### FFmpeg

Good for testing, or for streaming a file on a loop:

```sh
ffmpeg -re -stream_loop -1 -i music.mp3 -c:a copy \
  -content_type audio/mpeg -f mp3 \
  "icecast://source:YOUR_PASSWORD@127.0.0.1:8000/radio.mp3"
```

For other formats change the content type to the one in the supported formats (see "Streams and mounts") table.

### Updating the song title

MP3 and AAC listeners can see "now playing" text. Most encoders send it for you. You can also send it yourself with the source password:

```sh
curl -u source:YOUR_PASSWORD \
  "http://127.0.0.1:8000/api/metadata?mount=/radio.mp3&mode=updinfo&song=Artist+-+Title"
```

Icecast-compatible software that sets titles itself (Liquidsoap's `output.icecast`, BUTT, Mixxx) sends the same request to `/admin/metadata` or the older `/admin/metadata.xsl`, with the source username and password. Quikcast accepts both on the streaming port. `artist` and `title` are combined as "artist - title" when `song` is missing.

If your software sends titles in a legacy character set, add `&charset=ISO-8859-1` (or set `charset` on the mount, see "Configuration reference") and Quikcast converts it to UTF-8.

Ogg and FLAC streams carry titles inside the audio itself, so this call does not apply to them.

### What if it does not connect?

An error such as `401`, `403`, `404`, `409` or `415` has a known cause. See "Troubleshooting".

---

# Part 2: Streaming

## Streams and mounts

A **mount** is one stream: a URL path, a password for the encoder that feeds it, and optionally its own listener limit and access rules. One server can run many.

### Add more streams

Each `[[mounts]]` block adds a stream:

```toml
[[mounts]]
path = "/main.mp3"
secret_file = "secrets/main-source"

[[mounts]]
path = "/talk.mp3"
secret_file = "secrets/talk-source"
listener_limit = 100
```

Listeners play `http://your-server:8000/main.mp3` and `http://your-server:8000/talk.mp3`. You can have up to 64 mounts by default; raise `limits.max_mounts` (see "Configuration reference") (and `retained_audio_budget`) for more.

You can add or remove a `[[mounts]]` block while the server runs: edit the file and send `SIGHUP` (see "Production checklist"). New streams are available at once and others are not interrupted. Removing a block **disconnects that stream's encoder and listeners**, and the log names it. A reload is refused, and the old configuration kept, if the new path is already used by an encoder-created stream or the memory limits no longer fit.

> **Tip: Use a different password per mount**
>
> Give each stream its own secret file. Then a leaked password only lets someone take over that one stream.

### Path rules

- Start with `/`, with no trailing `/`. Nested paths such as `/stations/jazz` are fine.
- Letters, digits and `/ . _ - ~` only. Paths are case-sensitive.
- `/api`, `/admin`, `/internal`, `/health`, `/metrics`, `/hls`, `/ui` and `/console` are reserved.

### Playlist files

Add `.m3u`, `.pls` or `.xspf` to any mount path to get a playlist that points at the stream. `/stations/jazz.m3u` returns a one-entry playlist for `/stations/jazz`, ready to open in VLC, iTunes or a phone.

- The stream URL is built from the request's `Host` header, using `https` when TLS is enabled. A request without a usable `Host` gets `400`.
- Playlists follow the mount's access rules and signed-URL auth. A valid `expires` and `sig` on the playlist URL are carried into the stream URL inside it, so the same signed link works for both.
- A mount literally named `/jazz.m3u` takes priority over the playlist rule.

### One source per mount

One encoder per mount. A second one is refused with `409`, so a forgotten test encoder can never replace your real show. When the encoder disconnects, its listeners are disconnected too, and players reconnect when the next session starts.

For a *live DJ takes over from the playlist* workflow, see "What is Quikcast?".

### Limit listeners

By default every mount can have up to 10,000 listeners, within the server-wide limit. Cap one mount with `listener_limit`:

```toml
[[mounts]]
path = "/small.mp3"
secret_file = "secrets/small-source"
listener_limit = 25   # 0 means no per-mount cap
```

Server-wide and default limits live under `[limits]`; see "Capacity and limits".

### Let encoders create streams on demand

Sometimes you do not know the stream names ahead of time, for example when each presenter gets their own mount. Turn on dynamic mounts and give them a shared credential:

```toml
[sources]
allow_dynamic_mounts = true
username = "source"
secret_file = "secrets/dynamic-source"

[sources.defaults]
name = "Community Radio"
genre = "Various"
```

Now an encoder that authenticates with that password can broadcast to any free path, for instance `/dance`. The mount exists while the source is connected and disappears once its last listener leaves. Nothing is written to your config. Mounts you list under `[[mounts]]` always take precedence.

`[sources.defaults]` provides the station name, description, genre and website for any source that does not send its own.

### Station name and genre

For listed mounts, your encoder (BUTT, Liquidsoap) sends the name, genre and song title. Quikcast passes them to players that ask for them. You do not configure these per mount in the config file.

### Supported formats

| Format | Content type the encoder sends | Notes |
|---|---|---|
| MP3 | `audio/mpeg` | Works everywhere. |
| AAC (ADTS) | `audio/aac`, `audio/aacp` | AAC-LC, HE-AAC and HE-AACv2. |
| Ogg Vorbis, Opus, Ogg FLAC | `audio/ogg`, `application/ogg` | Titles travel inside the stream. |
| FLAC | `audio/flac` | Native FLAC, for lossless streams. |

Quikcast does not convert between formats: each listener gets exactly what the encoder sent.

## Backup streams (fallback)

What should happen when your main encoder drops? With a **fallback**, listeners who connect while the main stream is down are sent to a backup stream automatically, instead of seeing an error.

```mermaid
flowchart LR
  L["Listener asks for /live.mp3"] --> A{"/live.mp3<br/>has a source?"}
  A -- yes --> S1["Play /live.mp3"]
  A -- no --> B{"/automation.mp3<br/>has a source?"}
  B -- yes --> S2["Play /automation.mp3"]
  B -- no --> E["404"]
```

### Set it up

Add `fallback` to the mount people use, naming another mount:

```toml
[[mounts]]
path = "/live.mp3"
fallback = "/automation.mp3"
secret_file = "secrets/live-source"

[[mounts]]
path = "/automation.mp3"
secret_file = "secrets/automation-source"
```

Listeners keep the address `/live.mp3`; there is no redirect. Run your always-on playlist into `/automation.mp3` and your live show into `/live.mp3`.

### How it behaves

- **Choosing a stream.** Each new listener gets the first mount in the chain that currently has a working source. If none do, they get a `404`.
- **Coming back.** When the main stream returns, MP3 and AAC listeners on the backup move back to it at a safe point in the audio, without reconnecting. Other formats stay on the backup until they reconnect.
- **Same format, any configuration.** Quikcast moves a listener between mounts that carry the same format (MP3 to MP3, AAC to AAC). It does not compare AAC profile, sample rate, channels or SBR, so AAC-LC, HE-AAC and HE-AACv2 mounts can back each other up. The move happens at a whole-frame boundary, and the listener's player sees a new stream configuration mid-stream. Most players recover at once; a player that cannot may glitch or go quiet until it reconnects. HE-AAC is signalled implicitly in ADTS, so Quikcast cannot tell HE-AAC at 44.1 kHz from AAC-LC at 22.05 kHz, and moves between those two are the likeliest to make a decoder complain. For the cleanest failovers keep a mount and its fallback on the same encoder settings. MP3 and AAC never swap listeners, and `audio/aacp` listeners are not moved.
- **When the backup itself drops.** Its listeners are disconnected and reconnect, at which point the chain is evaluated again.
- **Limits.** A listener served by the backup counts against the backup's limit, not the main stream's.
- **When a mount is full.** A listener arriving at a mount at its `listener_limit` is refused, even if its fallback is healthy, unless you set `fallback_when_full` (below).
- **Chains.** A chain can be up to eight mounts long. Unknown targets, loops and chains that are too long are rejected at startup.

### Overflow when a mount is full

A fallback also works for overflow. With `fallback_when_full = true`, listeners who arrive once the mount is at its `listener_limit` are served by the fallback instead of being refused:

```toml
[[mounts]]
path = "/live.mp3"
fallback = "/overflow.mp3"
fallback_when_full = true
listener_limit = 500
secret_file = "secrets/live-source"

[[mounts]]
path = "/overflow.mp3"
secret_file = "secrets/overflow-source"
```

The 501st listener of `/live.mp3` hears `/overflow.mp3`. A typical overflow mount is a relay (see "Relay another station") of the main stream from another server, so the extra listeners cost the main server nothing.

- It applies to each mount in a chain separately: if `/overflow.mp3` is also full and also has `fallback_when_full`, listeners move on to the next mount.
- The listener counts against the mount that serves it, so `/overflow.mp3` has its own `listener_limit`.
- If every mount that could serve is full, the listener gets the usual "server full" answer (503), not "not found".
- When a slot opens on `/live.mp3`, MP3 and AAC listeners on the overflow move back to it, like after an outage.
- It only covers a mount's own `listener_limit`. The server-wide `limits.max_listeners` still applies to everyone.
- To send overflow listeners to another server instead, see "Primary and replica servers". If both are set, the redirect to replicas applies first, once a mount has `redirect_after` listeners.

> **Warning: Players must support the backup's format**
>
> Quikcast never converts audio. If your main stream is MP3 and your backup is Ogg, a player that cannot play Ogg will not hear the backup. Use the same format and a similar bitrate.

### Fallback and relays together

A relay can feed the backup. For example, pull another station into `/automation.mp3` so your listeners hear it when your live show is off. See "Relay another station".

### Why not "live over automation" switching?

Fallback reacts to a stream being *absent*. It does not interrupt a playing stream because another source appeared. For a DJ who takes over from a running playlist, see "What is Quikcast?".

## Relay another station

A **relay** makes Quikcast pull an existing stream from somewhere else (an Icecast or SHOUTcast stream, or an audio-only HLS playlist) and publish it on one of your mounts. People use relays to rebroadcast a partner station, build an edge server closer to listeners, or keep a backup feed warm.

```mermaid
flowchart LR
  O["Origin stream<br/>https://origin.example/live"] -->|Quikcast pulls| R["Relay"]
  R --> M["Your mount<br/>/remote.mp3"]
  M --> L1["Listeners"]
  M --> L2["Listeners"]
```

### Set up a relay

A relay needs two things: a mount to publish on, and a `[[relays]]` block saying where to pull from.

```toml
[[mounts]]
path = "/remote.mp3"
secret_file = "secrets/remote-local"   # still required, see note below

[[relays]]
mount = "/remote.mp3"
url = "https://origin.example/live"
```

Listeners now play `http://your-server:8000/remote.mp3`.

> **Note: The relay owns the mount**
>
> While a relay is configured for a mount, no encoder can connect to it, even if the relay is stopped. The mount still needs a password in its own block because the relay publishes through it.

### Add backup upstreams

List more than one upstream with `upstreams`. If the first fails, Quikcast moves to the next straight away:

```toml
[[relays]]
mount = "/remote.mp3"
upstreams = [
  { url = "https://primary.example/live" },
  { url = "https://backup.example/live" },
]
```

How failover works:

1. The first entry is the **primary**. A failure moves to the next entry immediately.
2. After the last entry fails, Quikcast waits (1 second, doubling up to 60) and starts again from the primary.
3. A working backup stays in use until it fails. There is no automatic return to the primary.
4. Each switch is a new stream generation. Listeners reconnect to it and see the new source's audio format.

You can list up to 8 upstreams.

### Upstreams that need a password

If the origin requires a login, give a username and a password file. Relay passwords can be shorter than local ones, since they must match whatever the origin gave you.

```toml
[[relays]]
mount = "/remote.mp3"
username = "partner"
secret_file = "secrets/partner-password"
upstreams = [
  { url = "https://partner.example/live" },
  { url = "https://mirror.example/live", username = "other", secret_file = "secrets/mirror-password" },
]
```

The top-level `username` and `secret_file` are the default for every upstream that does not set its own. Credentials are never sent to a different host than the one you configured, even across redirects.

### Redirects

Many stream URLs redirect to a CDN. Allow Quikcast to follow them with `max_redirects` (0 to 8, default 0):

```toml
[[relays]]
mount = "/boxradio.mp3"
url = "https://stream.example/abc123"
max_redirects = 3
```

### Connect only when someone listens

By default a relay connects at startup and stays connected. Set `on_demand = true` to pull the upstream only while there are listeners, which saves bandwidth and avoids holding connections to origins that charge per connection or limit concurrent clients.

```toml
[[relays]]
mount = "/remote.mp3"
url = "https://origin.example/live"
on_demand = true
idle_timeout_ms = 30000   # disconnect after 30 s with no listeners
wake_wait_ms = 8000       # how long the first listener waits for audio
```

How it behaves:

1. The relay starts idle. Nothing connects to the origin yet.
2. The first listener to request the mount wakes the relay. That listener's request is held, up to `wake_wait_ms`, until audio arrives, then starts playing. If the origin is slow or down, they get the usual "not found" response and can retry.
3. Everyone who joins while it is connected shares the one upstream connection.
4. When the last listener leaves, the relay waits `idle_timeout_ms` and then disconnects. A listener who returns in that window finds the stream still running.

The first listener waits a few seconds for the origin to connect. Keep `idle_timeout_ms` at or above `wake_wait_ms`. If the mount has a fallback (see "Backup streams (fallback)"), a waking listener is served the fallback straight away, and MP3 and AAC listeners move back to the relay once it is live.

An on-demand relay shows `state: stopped` and `stopped_reason: idle` while waiting. A relay stopped through the management API stays stopped until you reconnect it; listeners do not wake it.

### Control a relay while running

Relays are managed through the "Management API" (you need `[management]` enabled):

| Action | Request |
|---|---|
| See all relays | `GET /api/relays` |
| See one relay | `GET /api/relays/radio.mp3` |
| Reconnect (starts at the primary) | `POST /api/relays/radio.mp3` |
| Stop and stop retrying | `DELETE /api/relays/radio.mp3` |

Set `enabled = false` on a relay to have it start stopped.

### Relay an HLS stream

> **Warning: HLS relays are not reliable yet**
>
> Treat this as **experimental**. HLS packaging varies a lot between stations: some streams will not work, a working one can stop when the station changes its packaging, and you may hear gaps, repeated or skipped audio, or reconnects. Use an Icecast or SHOUTcast URL when one exists, and do not depend on an HLS relay for anything that must stay on air.

Many stations publish only HLS (a `.m3u8` playlist of small audio segments). Point a relay at the playlist and Quikcast republishes it on your mount as an ordinary continuous stream.

```toml
[[mounts]]
path = "/hls-station.aac"
secret_file = "secrets/hls-station-local"

[[relays]]
mount = "/hls-station.aac"
url = "https://stream.example/live/index.m3u8"
max_redirects = 3     # HLS segments are often redirected to a CDN
```

There is nothing to switch on: a relay recognises a playlist by its content type or a `.m3u8` address.

How it works:

1. **Pick a variant.** If the address is a master playlist with several bitrates, Quikcast follows an **audio-only** variant, the highest bitrate by default. Set `hls_variant = "lowest"` to save bandwidth. Variants with video are never chosen.
2. **Join near the live edge.** It fetches the newest two segments first, then keeps polling the playlist (about every half segment length) for new ones.
3. **Unwrap the audio.** Each segment is stripped down to plain AAC or MP3 audio and published to the mount. Nothing is decoded or re-encoded.

| Segment type | Supported |
|---|---|
| Packed AAC or MP3 (`.aac`, `.mp3`) | Yes |
| MPEG-TS with AAC or MP3 (`.ts`) | Yes |
| Fragmented MP4 with AAC-LC, HE-AAC or HE-AACv2 (`.m4s` with an init section) | Yes |
| Encrypted segments (`EXT-X-KEY`), byte ranges, FLAC or ALAC in MP4, video-only variants | No |

> **Warning: Expect some delay**
>
> HLS is built from segments, so a relayed HLS stream plays roughly **10 to 30 seconds behind** the source, depending on how long each segment is. That is a property of HLS, not of Quikcast.

Good to know:

- **It must be a live stream.** A playlist that ends (`#EXT-X-ENDLIST`) counts as the upstream finishing, so the relay backs off and retries, like any other upstream that disconnects.
- **Stalls and errors.** An expired segment (404) is skipped. Three failed fetches in a row make the relay fail over to the next upstream. If no new audio arrives for the longer of `audio_timeout_ms` and three segment lengths, the relay treats the upstream as stalled.
- **Credentials stay home.** As with redirects (see Upstreams that need a password), they go only to the host that served the playlist, never to a CDN serving its segments.
- **Song titles are not carried over.** HLS timed metadata is ignored, so the mount shows no track titles and no station name.
- **One format per generation.** If the upstream switches codec (AAC to MP3, say), the relay starts a new generation so listeners get the right content type.
- **Size limits.** Playlists up to 128 KiB (1,024 segments) and segments up to 1 MiB. Larger playlists or segments fail the relay.
- **No quality switching.** The relay follows one variant for the whole connection. It does not adapt to bandwidth.
- **Gaps are possible.** If the relay falls behind the upstream's live window, or a segment expires before it is fetched, that audio is skipped.
- **Add a backup.** List a second upstream (ideally a plain Icecast or SHOUTcast URL) so the relay can fail over. See Add backup upstreams.

### What a relay can pull

- **Protocols:** HTTP and HTTPS upstreams that answer with a normal `200`. Older SHOUTcast v1 servers answer with a non-standard `ICY 200 OK` status line, which Quikcast also accepts, so relay them like any other URL.
- **Formats:** MP3, AAC, Ogg Vorbis, Opus, Ogg FLAC, native FLAC (`audio/flac`) and audio-only HLS. Nothing is converted: listeners get what the upstream sends.
- **Certificates:** HTTPS upstreams are always verified against the public certificate authorities. There is no switch to disable verification, add a private CA or use client certificates.
- **Timeouts and backoff** are tunable per relay. See the "Configuration reference".

### Safety rules

- **A public upstream cannot point Quikcast at your private network.** If a public server redirects a relay, or an HLS playlist references a segment, to a private or local address (`127.0.0.1`, `10.x`, `192.168.x`, `169.254.x`, cloud metadata and similar), Quikcast refuses with `destination_not_allowed` and tries the next upstream. An upstream you configured yourself on a private address is trusted, along with anything it redirects to inside that network.
- **Never relay a stream to itself.** Quikcast rejects obvious loops with its own address, but it cannot see loops that pass through a proxy. Keep your topology a tree.

## Primary and replica servers

Run more than one Quikcast server and let the others copy the first one's streams. The **primary** is the server your encoders connect to. A **replica** asks the primary which streams it has and relays each one, so listeners can use whichever server is closest, and you add capacity by starting another replica.

```mermaid
flowchart LR
  E["Encoders"] --> P["Primary<br/>radio.example.com"]
  P -->|"stream list + audio"| R1["Replica<br/>eu.example.com"]
  P -->|"stream list + audio"| R2["Replica<br/>us.example.com"]
  R1 --> L1["Listeners"]
  R2 --> L2["Listeners"]
```

This is Icecast's master and slave idea. To relay one or two known streams, use a relay (see "Relay another station") instead. Use a replica when a server should follow *every* stream of another, including streams added later, without editing its config.

### 1. Set up the primary

Add a `[primary]` section to the primary's config. It protects the stream list with a password that only your replicas know:

```toml
[primary]
username = "replica"
secret_file = "secrets/replica-password"
```

Make the password at least 16 characters, like a mount password:

```sh
openssl rand -base64 24 > secrets/replica-password
```

That is the whole change. The primary now answers `GET /api/streams` on its public address, but only with that password. It shares every publicly playable mount except:

- mounts protected by signed links (see "Signed, expiring links"), because a replica could not play them
- mounts that are themselves copies made by a replica, so two servers can never copy each other in a loop

To share only some streams, name them:

```toml
[primary]
secret_file = "secrets/replica-password"
share = ["/radio.mp3", "/jazz.mp3"]
```

### 2. Set up a replica

On the other server, add a `[replica]` section with the primary's address and the same password:

```toml
[replica]
primary = "https://radio.example.com"
username = "replica"
secret_file = "secrets/primary-password"
```

The replica needs no `[[mounts]]` of its own. Within a few seconds of starting, every stream on the primary appears at the **same path**: `https://radio.example.com/radio.mp3` is also `https://eu.example.com/radio.mp3`.

`primary` is the server's address only, with no path. The replica reads the stream list and relays the audio over that same public address.

### How it behaves

- **Streams follow the primary.** The replica checks the list every `refresh_secs` (30 by default). A new stream gets a mount and a relay. A stream that leaves the list is removed, and its listeners are disconnected.
- **Relays connect on demand.** A replica connects to the primary for a stream only while someone is listening, then disconnects after a while, so 40 streams do not mean 40 open connections. The first listener of a quiet stream waits a moment. See "Relay another station"; set `on_demand = false` to keep every relay connected.
- **A primary that goes down does not take the replica down.** If the list cannot be read, the replica keeps the streams it has and logs a warning once. It carries on when the primary returns.
- **Your own mounts win.** If the replica already has a `[[mounts]]` entry with the same path, that mount is left alone and the primary's stream with that path is not copied.
- **They are normal relays.** Replicated streams show under Relays and Mounts in the console (see "Operator console") and in the management API like any other relay.
- **Listeners count on the replica.** The primary sees one connection per stream, not one per listener, so its load stays flat as you add replicas.

### Send listeners to replicas

A primary can redirect listeners to its replicas, as Icecast does, so audio no longer flows through the primary. Turn it on in two places.

On each replica, say what its own public address is. The replica then announces itself, and the streams it carries, to the primary every time it checks the list:

```toml
[replica]
primary = "https://radio.example.com"
secret_file = "secrets/primary-password"
public_url = "https://eu.example.com"
```

On the primary, choose when to redirect:

```toml
[primary]
secret_file = "secrets/replica-password"
redirect_after = 200
```

With `redirect_after = 200`, the first 200 listeners of each mount connect to the primary. Everyone after that gets an HTTP `302` to a replica that carries the mount, taking turns between replicas. `redirect_after = 0` sends every listener to the replicas, which is the way to keep the primary for encoders and replicas only. A listener the primary has no room for (a full `listener_limit` or the global limit) is redirected too, whatever the number.

What to know:

- **Nothing changes until a replica announces itself.** If no replica is available for a mount, listeners are served by the primary as before.
- **Replicas drop out when they go quiet.** A replica that misses two checks in a row stops receiving listeners, so a replica that is down is not handed out.
- **Replicas are never redirected.** Their own audio requests are marked, so a replica always gets its stream from the primary.
- **Players must follow redirects.** Browsers, VLC, FFmpeg and most apps do. A few very old players do not, so test the ones your listeners use. Keep `redirect_after` above zero if you are unsure.
- **Signed-link mounts are never redirected**, because replicas do not carry them.
- **`public_url` is just an address**, like `primary`: no path. It must be reachable by your listeners, not only by the primary.
- **Metrics.** `listeners_redirected_total` counts every redirect.

### Limits and sizing

| Setting | Default | Meaning |
|---|---|---|
| `refresh_secs` | `30` | How often the stream list is checked (5 to 3600). |
| `on_demand` | `true` | Connect to the primary only while someone listens. |
| `max_streams` | `16` | The most streams to copy (1 to 48). |
| `only` | all | Copy only these paths, for example `["/radio.mp3"]`. |

Every copied stream is one mount and one relay on the replica, so the usual limits apply: at most `limits.max_mounts` (64 by default) mounts and 64 relays in total, and `limits.relay_allocation_budget` (see "Configuration reference") must have room for the relays (2 MiB each, 32 MiB by default, which is enough for 16). If the primary has more streams than fit, the replica copies the first ones in alphabetical order and logs a warning. Raise `max_streams` and the budget together if you need more.

### Security

- The stream list needs the replica password. Without it the primary answers `401`. The password is a separate secret from encoder, management and console passwords.
- Use HTTPS between the servers. A replica verifies the primary's certificate, and the password is only sent to the primary's own address.
- Streams are relayed over the primary's public listener, so the primary's access rules (see "Limit who can listen") apply to the replica like any other listener. If you restrict listeners by IP or country, allow your replicas' addresses.

### Check that it works

On the replica, list the discovered streams:

```sh
curl -s -H "Authorization: Bearer $TOKEN" http://127.0.0.1:9090/api/relays
```

Replicated streams appear as relays whose origin is the primary. If nothing appears, look at the replica's log:

| Log line | Meaning |
|---|---|
| `the primary rejected the replica username or password` | The `username` or password does not match the primary's `[primary]` section. |
| `the primary has no [primary] section` | The primary answered `404`. Add `[primary]` there and reload it. |
| `could not reach the primary` | The address, port or TLS is wrong, or a firewall is in the way. |

> **Note: A replica needs its config file**
>
> A replica applies stream changes by reloading its configuration file, so it must be started with `--config` (or `QUIKCAST_CONFIG`), as in every normal setup.

## HLS for browsers and apps

**HLS** (HTTP Live Streaming) splits audio into small files plus a playlist. Browsers and phone apps handle it well, and it passes through CDNs and strict networks that block long-lived connections. Your normal mount stream keeps working alongside it.

> **Tip: Looking to relay someone else's HLS stream?**
>
> This page is about **serving** HLS from Quikcast. To pull an existing HLS station into one of your mounts as a normal stream, see "Relay another station".

> **Warning: HLS needs a producer**
>
> Quikcast **serves** HLS but does not **create** it. Something else must encode the segments and either write them to a directory Quikcast serves, or upload them through the private ingest API (FFmpeg plus a small script, or your own application). Quikcast validates uploads, keeps them in memory, writes the playlists and serves them. It never re-encodes.

```mermaid
flowchart LR
  P["Your producer<br/>(FFmpeg + script)"] -->|"upload segments<br/>private ingest API"| Q["Quikcast<br/>in-memory store"]
  Q -->|"/hls/radio/master.m3u8"| B["Browsers and apps"]
```

### 1. Turn HLS on

```toml
[hls]
username = "hls"
secret_file = "secrets/hls-ingest"
cors_origin = "https://player.example.com"
```

- The ingest password **must be different** from every mount password.
- `cors_origin` lets a website on that exact origin play your HLS in a browser. Leave it out if you only serve apps.

Everything else has defaults. See "Configuration reference" for capacity settings.

### 2. Publish a stream

A producer makes these calls with HTTP Basic authentication (the HLS username and password) to the **private admin address** (`admin_listen`, default `127.0.0.1:9090`) under `/internal/v1/hls/`. Players use the public address. Run the producer on the same machine, or reach the admin port through an SSH tunnel; never expose it to the internet.

| Step | Request |
|---|---|
| Create the stream | `PUT /internal/v1/hls/streams/radio` |
| Create a rendition (one quality level) | `PUT /internal/v1/hls/streams/radio/renditions/aac` with a JSON description |
| Upload each segment | `PUT .../renditions/aac/segments/0`, `.../1`, and so on |
| Publish the playlist | `PUT .../renditions/aac/publication` |
| Publish the master playlist | `PUT /internal/v1/hls/streams/radio/master` |

#### A complete example you can run

This `bash` and `curl` script makes three 2-second AAC segments with FFmpeg, uploads them and publishes the playlists.

```sh
HLS=http://127.0.0.1:9090/internal/v1/hls/streams
PW=$(cat secrets/hls-ingest)
c() { curl -s -u "hls:$PW" "$@"; }                       # authenticated curl
gen() { sed -E 's/.*"generation":"([0-9]+)".*/\1/'; }     # pull the generation out of a reply

# Make three test segments (replace with your real encoder output)
for n in 0 1 2; do
  ffmpeg -loglevel error -y -f lavfi -i "sine=frequency=$((440 + n * 220)):duration=2" \
    -c:a aac -b:a 128k -f mpegts seg$n.ts
done

# 1. Create the stream. Keep the generation it returns.
SG=$(c -X PUT $HLS/radio | gen)

# 2. Create a rendition (one quality level).
RG=$(c -X PUT $HLS/radio/renditions/aac \
  -H 'Content-Type: application/json' -H "X-HLS-Generation: $SG" \
  -d '{"target_duration":2,"window_segments":6,"bandwidth":128000,"codecs":"mp4a.40.2"}' | gen)

# 3. Upload the segments.
for n in 0 1 2; do
  c -X PUT $HLS/radio/renditions/aac/segments/$n \
    -H "X-HLS-Generation: $SG" -H "X-HLS-Rendition-Generation: $RG" \
    -H "X-HLS-Duration-Ms: 2000" -H "Content-Type: video/mp2t" --data-binary @seg$n.ts
done

# 4. Publish the media playlist, then the master playlist.
c -X PUT $HLS/radio/renditions/aac/publication \
  -H 'Content-Type: application/json' -H "X-HLS-Generation: $SG" -H "X-HLS-Rendition-Generation: $RG" \
  -d '{"expected_revision":0,"segments":[{"sequence":0,"duration_ms":2000},{"sequence":1,"duration_ms":2000},{"sequence":2,"duration_ms":2000}],"end":false}'

c -X PUT $HLS/radio/master \
  -H 'Content-Type: application/json' -H "X-HLS-Generation: $SG" \
  -d '{"expected_revision":0,"renditions":["aac"]}'
```

> **Note: Generations are numbers Quikcast gives you**
>
> Creating a stream or rendition returns a long number such as `7832260401770470567`. Send it back unchanged on later calls; it proves you mean the stream you created, not an older one with the same name.

A real producer keeps uploading new segments and publishing a sliding window (for example the latest six). Every call, header and error is documented in the HLS ingest API reference (see "HLS ingest API").

### 3. Play it

```text
http://your-server:8000/hls/radio/master.m3u8
```

Open it in Safari, VLC, or a web player such as hls.js.

### Serve HLS from a directory

If another program already writes HLS to disk (Liquidsoap's `output.file.hls`, FFmpeg's `hls` muxer, any tool that makes `.m3u8` playlists and segments), Quikcast can serve that directory directly, with no ingest API or producer password.

```toml
[hls]
directory = "/var/lib/radio/hls"
cors_origin = "https://player.example.com"
```

Every subdirectory is one stream, served at the same public address as ingested HLS:

```text
/var/lib/radio/hls/radio/radio.m3u8       ->  /hls/radio/radio.m3u8
/var/lib/radio/hls/radio/radio_12.ts      ->  /hls/radio/radio_12.ts
/var/lib/radio/hls/radio/hq/index.m3u8    ->  /hls/radio/hq/index.m3u8
```

`/hls/radio/master.m3u8` (the name used for ingested streams) also works: it returns `master.m3u8` if the directory has one, and otherwise the muxer's own `radio.m3u8`. Player URLs inside playlists stay relative, so they keep working.

What is served:

- Only regular files with an HLS extension: `.m3u8`, `.ts`, `.m4s`, `.mp4`, `.aac`, `.mp3`. Everything else is a `404`, including `.state_*.json` files and any other file or directory whose name starts with a dot.
- Paths that try to leave the stream (`..`, encoded slashes) are refused. A symlink is followed only if it stays inside the same stream directory, and a stream directory that links outside the root is not served.
- Playlists are read fresh on every request with `Cache-Control: no-cache`. Writing a temporary file and renaming it is safe: a request sees the old file or the new one, never a mix. A file rewritten in place while read is retried, and an empty playlist counts as missing.
- Segments get `Cache-Control: public, max-age=3600` (not `immutable`, since a muxer may reuse a name after a restart). `HEAD`, single byte `Range` requests and `If-None-Match` work as for ingested HLS.
- Files larger than 16 MiB are not served.

The directory must exist and be readable when Quikcast starts, and `--check` reports a problem. Changing `directory` while HLS is on needs a restart (adding or removing `[hls]` itself applies on reload); files and subdirectories can appear and disappear at any time.

Directory streams share everything else with ingested HLS: `cors_origin`, signed links (see "Signed, expiring links") (`[hls.listener_auth."/hls/NAME"]`), the `[access]` rules and the `hls_*` metrics. A stream registered through the ingest API takes precedence over a directory with the same name. When `directory` is set, the ingest `secret` or `secret_file` becomes optional: leave both out and the ingest API is switched off.

#### Counting listeners

HLS has no connection to count, so Quikcast reports **unique client IPs** that fetched a playlist or segment in the last `directory_listener_window_secs` seconds (default 60; set it to a few segment lengths). These are estimates, not connections: a viewer who closes the tab still counts until the window passes, and several people behind one address count once. Counts reset on restart.

They appear in the console's Listeners total, the Listeners page, its HLS page and the listener history, and in `active_listeners` of `GET /api/stats`. The Prometheus `active_listeners` gauge counts connections only.

`GET /api/hls` on the admin address lists each directory stream, and `GET /api/hls/radio/listeners` lists its listener sessions. Fields and session rules are in the "Management API". Behind a proxy, configure `[trusted_proxies]` (see "HTTPS and proxies") so clients are identified by their real address.

### Supported formats

AAC (LC, HE-AAC, HE-AACv2) in MPEG-TS, packed `.aac` or fragmented MP4; packed MP3; and FLAC in fragmented MP4. The exact format and `codecs` combinations are in the HLS ingest API reference (see "HLS ingest API").

Not supported: Ogg or native FLAC in HLS, encryption, video, low-latency HLS and DASH.

### Good to know

- **Ingested HLS lives in memory.** (Directory HLS stays on disk.) Restarting Quikcast clears all HLS content. Your producer must register and upload again.
- **Public URLs are generated for you.** Players only need the master playlist address. Everything else comes from it.
- **Protect a stream** with signed links (see "Signed, expiring links") if it should not be public.
- **Caching is already tuned.** Playlists are `no-cache`; ingested segments are immutable and cached for a year, which is what CDNs want.

## Icecast-compatible admin API

Control panels and monitoring tools built for Icecast read listener counts and listener IPs from Icecast's admin API. Quikcast serves the same API, so it can take Icecast's place as a remote server without losing those numbers.

### Turn it on

Add a credential for the client. The password must be at least 16 characters.

```toml
[icecast_admin]
username = "admin"
password_file = "secrets/icecast-admin"
```

Reload the configuration (send `SIGHUP`, see the CLI reference (see "Command line and signals")) and check it:

```sh
curl -u "admin:$(cat secrets/icecast-admin)" \
  "http://127.0.0.1:8000/admin/listclients?mount=/radio.mp3"
```

### What is served

| Path | Use |
|---|---|
| `/admin/stats` | Totals and per-mount listeners, artist, title, bitrate, listen URL |
| `/admin/listmounts` | Live mounts and listener counts |
| `/admin/listclients?mount=…` | Each listener's IP, user agent, seconds connected and ID |
| `/admin/killclient?mount=…&id=…` | Disconnects one listener |
| `/status-json.xsl` | Public JSON status with no login. Clients use it as a fallback when `/admin/stats` fails |

Listener IDs are numbers, as in Icecast. A title written "Artist - Title" is reported as separate artist and title. Behind a proxy, set up `[trusted_proxies]` (see "Configuration reference") so the IPs reported are the real listeners', not the proxy's.

### Point a client at it

Many Icecast clients log in as the user `admin` with no way to change it, so leave `username` at its default. The password a client sends must match the `[icecast_admin]` password. Because Quikcast requires at least 16 characters, an old short Icecast password will not work; set a new one in the client too.

1. Create the mount in `quikcast.toml` with the source password your encoder or panel will use.
2. In the client, add a remote Icecast server with Quikcast's host and port, the mount, and the admin user and password above.
3. Check that listener counts and the listener list appear.

### Security

`/admin/listclients` exposes listener IP addresses, so treat the credential as sensitive. `/status-json.xsl` is public and shows only counts and titles; use `hide_listener_count` on a mount to report 0. The routes share the public port, as they do in Icecast. If Quikcast is on the internet, have your proxy or firewall allow `/admin/` only from the client's address. Failed logins from one address are throttled with `429`.

### Not supported

`/admin/moveclients`, `/admin/fallbacks` and the per-mount web admin pages are not implemented. Manage mounts in the config file or the "Management API".

---

# Part 3: Security

## Limit who can listen

By default anyone can play your streams. Narrow that with rules on **IP address**, **country** and **player (User-Agent)**. Rules are optional, are checked before a listener connects, and never affect encoders (they have a separate rule set). A refused listener gets a plain `403 Forbidden` that never says which rule matched.

### How rules combine

- A listener must pass **every** category you configure: IP, User-Agent and country.
- A **deny** rule always wins over an allow rule.
- A non-empty **allow** list means "only these". An empty list means "no restriction".
- Global rules (`[access]`) and per-mount rules (`[mounts.access]`) **both** apply. A mount can only add restrictions, never relax the global ones.

### Block addresses

```toml
[access]
ip_deny = ["203.0.113.0/24", "198.51.100.7", "2001:db8:dead::/48"]
```

Entries can be single addresses or CIDR ranges, IPv4 or IPv6.

#### Long blocklists in a file

Keep a growing list out of your config. Put one address or range per line:

**lists/blocked.txt**

```text
# Scrapers
203.0.113.0/24
198.51.100.7

# A noisy network
2001:db8:dead::/48
```

```toml
[access]
ip_deny_file = "lists/blocked.txt"
```

Blank lines and `#` comments are ignored. Edit the file, then send the server a reload (`kill -HUP`) to apply it without a restart. You can combine inline entries and a file; the limit is 10,000 distinct rules together.

> **Warning: An empty allow file is an error**
>
> `ip_allow_file` with no rules would mean "allow everyone", so Quikcast refuses to start (or reload) instead of silently opening the stream. An empty `ip_deny_file` is fine.

### Allow only certain countries

```toml
[access]
countries_allow = ["GH", "NG"]
```

Use two-letter ISO country codes. `countries_deny` works the same way in reverse. A country database is built into Quikcast, so this works with no extra setup. Addresses whose country is unknown (for example private network addresses) fail an allow list but pass a deny list.

> **Tip: Testing from your own machine**
>
> `127.0.0.1` and other private addresses have no country, so they are refused by `countries_allow`. Test from a real network, or temporarily use an IP rule instead.

To use your own MaxMind-format database instead of the built-in one:

```toml
[access]
geoip_database = "/etc/quikcast/GeoLite2-Country.mmdb"
```

### Allow or block certain players

```toml
[access]
user_agent_deny = ["substring:python-requests", "prefix:curl/"]
user_agent_allow = []
```

Rules start with how to match: `exact:`, `prefix:` or `substring:`, followed by the text. Matching is case-sensitive.

> **Warning: User-Agent is easy to fake**
>
> Use it to keep out known bad tools, not as security. Anyone can change what their player says it is.

### Block whole networks

Hosting providers and scrapers change addresses constantly but stay in one network. Block them by **ASN** (autonomous system number) using the ASN database built into Quikcast:

```toml
[access]
asns_deny = [16509, 14061]
```

`asns_allow` works in reverse, and a mount can add its own lists. The built-in database is a snapshot refreshed with each release. For fresher data, or your own, point `asn_database` at a MaxMind-format file with `autonomous_system_number` records, such as GeoLite2-ASN; it replaces the built-in one. Unknown and private addresses pass a deny list and fail an allow list.

### Limit connections per address

One address can otherwise hold as many listener slots as it likes. Cap it:

```toml
[access]
listeners_per_ip = 4        # across every mount

[mounts.access]
listeners_per_ip = 1        # on this mount
```

Extra connections get `429 Too Many Requests`. IPv6 addresses share one budget per /64. This needs correct proxy settings or every listener looks like the proxy. It applies to continuous streams, not HLS.

### Ban an address while it is running

For an abuser you want gone now, without editing a file or reloading, use the "Management API": `POST /api/bans?ip=203.0.113.7&ttl_seconds=3600&kick=true` refuses the address and disconnects its listeners. Bans expire by themselves, are held in memory, and are lost on restart. For a permanent block use `ip_deny_file`.

### Different rules per stream

Put the same fields under a mount:

```toml
[[mounts]]
path = "/members.mp3"
secret_file = "secrets/members-source"

[mounts.access]
ip_allow = ["10.0.0.0/8", "192.168.0.0/16"]
```

This stream is only reachable from the private network, while other mounts stay public (subject to any global rules).

### Limit who can broadcast

Separately from listeners, you can restrict which addresses may connect an *encoder* to a mount. The password is still required.

```toml
[[mounts]]
path = "/radio.mp3"
secret_file = "secrets/radio-source"

[mounts.source_access]
ip_allow = ["203.0.113.10"]
```

`source_access` accepts only IP lists (`ip_allow`, `ip_allow_file`, `ip_deny`, `ip_deny_file`).

### Behind a proxy? Tell Quikcast

Rules look at the listener's address. Behind a proxy that is the proxy's address, so rules would hit the wrong machine. Configure `trusted_proxies` as described in "HTTPS and proxies".

### Check what is applied

With `[management]` (see "Management API") enabled, `/api/server` and `/api/mounts` show the active rule counts, and the metrics include counters for each kind of denial (see "Metrics"). For a closer look, set `log_filter = "quikcast=debug"` to log the reason for each rejection.

## Signed, expiring links

Signed links let **your own application** decide who may listen. Your app creates a link that works for a limited time; Quikcast only checks that it is genuine and not expired. There are no accounts, sessions or callbacks.

Typical uses: members-only streams, paid access, or a "listen now" button that works for an hour.

```mermaid
sequenceDiagram
  participant U as Listener
  participant A as Your website
  participant Q as Quikcast
  U->>A: Open the player page (logged in)
  A->>A: Sign "/members.mp3" with expiry
  A-->>U: Player URL with expires and sig
  U->>Q: GET /members.mp3?expires=...&sig=...
  Q->>Q: Verify signature and expiry
  Q-->>U: Live audio (or 403)
```

### 1. Share a key

Create a secret key that only your application and Quikcast know:

```sh
openssl rand -hex 32 > secrets/members-key
```

Protect the mount with it:

```toml
[[mounts]]
path = "/members.mp3"
secret_file = "secrets/members-source"   # the encoder password, a different secret

[mounts.listener_auth]
type = "signed_url"
secret_file = "secrets/members-key"
max_ttl_seconds = 3600
clock_skew_seconds = 0
```

| Setting | Meaning |
|---|---|
| `max_ttl_seconds` | How far into the future a link may expire. Links asking for longer are refused. Default `86400` (a day), maximum one week. |
| `clock_skew_seconds` | Extra time after expiry that is still accepted, to forgive clocks that disagree. `0`–`60`, default `0`. |

### 2. Sign links in your application

A link needs two query parameters: `expires` (a Unix timestamp in seconds) and `sig` (a signature). The signature is an **HMAC-SHA-256** of this text, using your key:

```text
<path>\n<expires>
```

That's the mount path, a single newline, then the expiry number, with no trailing newline. The result is encoded as **base64url without padding**.

**Node.js**

```js
import { createHmac } from 'node:crypto'

export function signedUrl(base, path, key, ttlSeconds = 3600) {
  const expires = Math.floor(Date.now() / 1000) + ttlSeconds
  const sig = createHmac('sha256', key).update(`${path}\n${expires}`).digest('base64url')
  return `${base}${path}?expires=${expires}&sig=${sig}`
}
```

**Python**

```python
import base64, hashlib, hmac, time

def signed_url(base, path, key, ttl=3600):
    expires = int(time.time()) + ttl
    mac = hmac.new(key, f"{path}\n{expires}".encode(), hashlib.sha256).digest()
    sig = base64.urlsafe_b64encode(mac).rstrip(b"=").decode()
    return f"{base}{path}?expires={expires}&sig={sig}"
```

**PHP**

```php
function signedUrl(string $base, string $path, string $key, int $ttl = 3600): string {
    $expires = time() + $ttl;
    $mac = hash_hmac('sha256', "$path\n$expires", $key, true);
    $sig = rtrim(strtr(base64_encode($mac), '+/', '-_'), '=');
    return "$base$path?expires=$expires&sig=$sig";
}
```

The key is the file's contents **as text**. If you made it with `openssl rand -hex 32`, the key is those 64 hex characters, not their decoded bytes.

### 3. Test your signer

Use this known-good example to check your code. With this key:

```text
0123456789abcdef0123456789abcdef
```

the path `/private-radio` and expiry `1791504000` must produce:

```text
VFu-3J9JLyvyAbZwMz_upmhVy0BouocqUWFd4ADtedY
```

### Rules to remember

- `expires` is a plain number: no sign, spaces or leading zeros. The parameter names are exactly `expires` and `sig`.
- Any problem (bad signature, expired, too far in the future, duplicate parameters) gives the same `403 Forbidden`.
- Other query parameters are ignored and are not signed.
- With `previous_secret_files` or `bind_ip` the same `403` covers a retired key or the wrong address.
- Your server's clock must be right. Quikcast compares against its own clock.
- Don't log full URLs with their query strings in proxies or CDNs.

### Rotate the key

Swapping the key at once would break every link already issued. Roll it over instead:

1. Create the new key and make it `secret_file`. List the old one under `previous_secret_files`.
2. Reload (`kill -HUP`). Links signed with either key now work. Start signing new links with the new key.
3. After the longest link you issued has expired (at most `max_ttl_seconds`), remove the old key and reload again.

```toml
[mounts.listener_auth]
type = "signed_url"
secret_file = "secrets/members-key-2026-11"
previous_secret_files = ["secrets/members-key-2026-05"]
```

Up to four previous keys are accepted. A leaked key stays valid until you remove it, so do not leave old keys listed longer than needed.

### Revoke a single link

If one link leaks, you do not have to rotate the key and break everyone else's. Tell Quikcast to refuse that link, using its `sig` and `expires` values:

```sh
curl -X POST -H "Authorization: Bearer $QUIKCAST_TOKEN" \
  "$QUIKCAST_ADMIN_URL/api/revocations?sig=VFu-3J9JLyvyAbZwMz_upmhVy0BouocqUWFd4ADtedY&expires=1791504000"
```

The link then gets the same `403` as any bad link, on the stream, its playlists and HLS. The entry removes itself when the link would have expired anyway. Revocations are kept in memory, so they reset on restart (a link's life is short, but re-apply them after a restart if one matters) and they do not reach other nodes. A listener already playing is not cut off; use a ban with `kick` (see "Management API") to end the session.

### Bind links to an IP address

A signed link works for anyone who has it. To stop it being shared, add `bind_ip = true`. The link then only plays from the address it was signed for:

```toml
[mounts.listener_auth]
type = "signed_url"
secret_file = "secrets/members-key"
bind_ip = true
```

Sign the listener's address as a third line:

```text
<path>\n<expires>\n<ip>
```

Use the address as text: dotted for IPv4 (`203.0.113.7`), compressed lowercase for IPv6 (`2001:db8::1`). An IPv4-mapped IPv6 address counts as its IPv4 address. With `bind_ip` on, links signed without an address are refused, and the reverse.

> **Warning: Know your trade-offs**
>
> Quikcast checks the address it sees, so behind a proxy configure `trusted_proxies` (see "HTTPS and proxies") first, or every link will be checked against the proxy. Listeners on mobile networks can change address mid-session and will need a fresh link; for that reason, keep `max_ttl_seconds` short. Listeners behind shared NAT share an address.

**Node.js**

```js
const sig = createHmac('sha256', key).update(`${path}\n${expires}\n${listenerIp}`).digest('base64url')
```

### HLS streams

HLS streams can be protected the same way. The identity you sign is the stream's public path, for example `/hls/members`, no matter which playlist or segment is requested. One signature covers the master playlist, every rendition and all segments of that stream.

```toml
[hls.listener_auth."/hls/members"]
type = "signed_url"
secret_file = "secrets/members-key"
```

Sign `/hls/members` and put `expires` and `sig` on the master playlist URL. Quikcast copies them into the playlist entries it generates, so players follow signed links all the way down.

## HTTPS and proxies

Listeners and encoders should reach your station over HTTPS. Either let Quikcast serve it, or put a reverse proxy in front. This page covers both, and how to keep listener addresses accurate behind a proxy.

### Option A: HTTPS directly from Quikcast

> **Tip: Installed with the install script?**
>
> Run `qc tls --domain radio.example.com` (free Let's Encrypt certificate, renewed automatically) or `qc tls --cert FILE --key FILE`, then `qc restart`. See "Install". The steps below are the manual equivalent.

Point Quikcast at a certificate and key in PEM format. A Let's Encrypt `fullchain.pem` and `privkey.pem` are exactly right.

```toml
listen = "0.0.0.0:443"

[tls]
cert_file = "secrets/tls/fullchain.pem"
key_file = "secrets/tls/privkey.pem"
```

- The **admin address stays plain HTTP on localhost**. Only the public listener uses TLS.
- A plain `http://` request to the TLS port is closed without an answer. There is no automatic redirect, so send people to `https://`.
- Encoders must connect with TLS too. BUTT and Liquidsoap have an HTTPS/TLS option for Icecast servers.
- To bind port 443 without running as root on Linux, either use a higher port behind a firewall rule, or grant the binary the capability: `setcap 'cap_net_bind_service=+ep' /usr/local/bin/quikcast`.

#### Renewing certificates

Replace the files, then ask Quikcast to reload:

```sh
kill -HUP "$(pidof quikcast)"
```

New connections use the new certificate straight away and existing listeners are not interrupted. If a file is missing or the key does not match, the reload is refused and the old certificate stays active. Certbot users can add the `kill -HUP` line as a deploy hook.

> **Tip: Turning TLS on or off needs a restart**
>
> Only the certificate files reload. Enabling or disabling `[tls]` changes what the port speaks, so restart for that.

### Option B: A reverse proxy in front

If you already run nginx, Caddy, Traefik or a cloud load balancer, let it handle certificates and forward plain HTTP to Quikcast on localhost.

```toml
listen = "127.0.0.1:8000"   # only the proxy can reach it
```

A live audio stream is a very long download, so a proxy must **not buffer** it and must allow long timeouts.

#### nginx

```nginx
location /radio.mp3 {
    proxy_pass http://127.0.0.1:8000;
    proxy_http_version 1.1;
    proxy_set_header Host $host;
    proxy_set_header Connection "";
    proxy_set_header X-Forwarded-For $remote_addr;

    proxy_buffering off;
    proxy_cache off;
    proxy_request_buffering off;
    proxy_read_timeout 1h;
    proxy_send_timeout 1h;
    client_max_body_size 0;      # encoders upload forever
}
```

Expose only the paths you need: your mounts, `/hls/` if you use HLS, `/` and `/console/` if you serve the status page or console (see "Operator console"), and `/api/metadata` (plus `/admin/metadata` and `/admin/metadata.xsl` for Icecast-style encoders) only if your encoder sends titles that way. **Never** forward `/api` (except that one path), any other `/admin` path, `/internal`, `/health` or `/metrics` to the internet; they are served by the private admin address anyway.

#### Encoders and proxies

Some encoders use the older Icecast `SOURCE` request instead of standard HTTP `PUT`. A plain HTTP proxy may not pass that through. If a particular encoder fails only through the proxy, connect it directly to Quikcast, use a TCP (layer 4) proxy, or switch the encoder to its HTTP `PUT` mode.

### Real listener addresses

Country and IP rules (see "Limit who can listen"), statistics and logs depend on the listener's address. Behind a proxy, Quikcast sees the proxy's address for everyone unless you tell it which proxies to believe.

#### With an HTTP proxy: X-Forwarded-For

List the proxies you control. Quikcast then reads the `X-Forwarded-For` header, but only from those addresses:

```toml
[trusted_proxies]
ips = ["127.0.0.1", "10.0.0.0/8"]
```

Anyone else sending that header is ignored. Quikcast reads the header from right to left and stops at the first address that is not trusted, so a visitor cannot invent their own address. Configure your proxy to *replace* an incoming `X-Forwarded-For` or *append* to it.

#### Serving the console under a path prefix

If your proxy exposes Quikcast at a sub-path (for example `/28000/console`) and strips that prefix before forwarding, have it send `X-Forwarded-Prefix: /28000`. Quikcast then builds the console's links, API calls and session cookie under that prefix. The header is honoured only from the proxies in `trusted_proxies`, and invalid values are ignored (the exact rules are in the `[ui]` reference (see "Configuration reference")). Keep the `Host` header unchanged.

#### Behind Cloudflare

```toml
[trusted_proxies]
providers = ["cloudflare"]
```

Quikcast has Cloudflare's published address ranges built in. A connection that really comes from Cloudflare may then supply the visitor's address in `CF-Connecting-IP`. The ranges are refreshed by upgrading Quikcast.

#### With a TCP load balancer: PROXY protocol

Layer-4 balancers (HAProxy in TCP mode, nginx `stream`, cloud network load balancers) cannot add HTTP headers, but they can send the PROXY protocol header, which carries the real address:

```toml
[trusted_proxies]
ips = ["10.0.0.0/8"]       # the balancer
proxy_protocol = true
```

With this on, every public connection must begin with a PROXY v1 or v2 header, and only the listed addresses may send one. Connections from anywhere else are closed. That includes your own health checks and quick `curl` tests, which must now go through the balancer.

> **Danger: Only trust what you control**
>
> Everything you list under `trusted_proxies` can claim any listener address. Listing a network you do not control lets strangers dodge your IP and country rules.

### Which option should I pick?

| Situation | Pick |
|---|---|
| One server, you want the simplest setup | Quikcast `[tls]` |
| You already run a proxy for other sites | Reverse proxy, with `trusted_proxies.ips` |
| Behind Cloudflare | Cloudflare provider |
| A TCP load balancer or cloud NLB | `proxy_protocol = true` |
| Docker with Traefik or Dokploy | Let it terminate TLS, list its network under `trusted_proxies` |

---

# Part 4: Running it

## Operator console

A web console for watching your station and taking quick actions. It is built into the program, so turning it on is a config change. It is off by default, except when you installed with the install script (see "Install"), which turns it on and generates the password.

### Turn it on

With the install script, run `qc console on` (and `qc password` to see the sign-in). `qc console on --status-page` also publishes the small public status page. By hand, write this:

```toml
[ui]
enabled = true
mode = "private"
username = "admin"
password_file = "secrets/ui-password"
```

You can write the table as `[console]` instead of `[ui]`; they are the same. The password needs at least 15 characters; very simple ones are refused.

```sh
openssl rand -base64 24 > secrets/ui-password
```

Start Quikcast and open `/console` on either address:

- `http://127.0.0.1:9090/console` (the admin address, the safest place to use it)
- `https://your-server/console` (the public address, if you have HTTPS)

> **Warning: Use HTTPS if the console is reachable from the internet**
>
> Sign-in cookies are `Secure` by default, so browsers send them only over HTTPS. Localhost is fine. For throwaway testing over plain HTTP elsewhere, set `secure_cookie = false`.

### Pages

**Overview** shows live sources, listeners, relays and HLS streams, every live mount with its track title, and a listener chart for the last hour, 6 hours or 24 hours. The chart comes from the in-memory listener history (see "Monitoring"), so it resets on restart. The Listeners count includes estimated directory HLS (see "HLS for browsers and apps") listeners. A notice appears at the top only when the server has stopped accepting connections or is shutting down.

**Mounts** lists every stream with its source, now-playing title, listeners, traffic and fallback. Each row has copy and play icons. Open a mount for its track, listen address, listener chart, source and capacity details, and a **Disconnect source** action.

**Relays** shows each relay's state, origin, failures and last error, with a **Reconnect relay** action. Open **Relay diagnostics** for the full per-relay details.

**HLS** lists streams published to Quikcast and directory streams (see "HLS for browsers and apps"). Pick an ingested stream to see its renditions, or a directory stream to see its listener sessions.

**Listeners** shows who is connected to one mount, 100 at a time. Directory HLS streams are in the same list as "HLS name", with their estimated sessions. **Info** opens that listener's exact values; **Disconnect** drops them.

**System** shows server details and **Stop accepting connections**. That is draining (see "Production checklist"): it is one-way, and the server accepts connections again only after a restart.

Disconnecting a source or listener, reconnecting a relay and stopping connections each ask for confirmation. Configuration, passwords and HLS publishing are not in the console on purpose.

The page refreshes every three seconds while visible. Your time range, filters and theme stay put.

#### Test-play a stream

The play icon starts the stream in a player bar at the bottom of the console. It keeps playing as you move between pages. While a mount plays, its play icon becomes a stop icon. The bar has its own stop and play button, a volume meter and a close button.

- The audio goes from your public listener straight to your browser, and your browser must support the format (MP3 and AAC are safest).
- You count as a listener, so you appear in the listener lists and your access rules (see "Limit who can listen") apply.
- Streams protected by signed links (see "Signed, expiring links") cannot be played here, and a mount with no source and no fallback has nothing to play. The icon is disabled and its tooltip says why.

#### Copy the right address

The console guesses the public address from the page you are on and the `listen` port. Behind a reverse proxy, a CDN or another domain, set it:

```toml
[ui]
public_url = "https://radio.example.com"
```

#### Behind a path prefix

If a trusted reverse proxy serves the console under a sub-path and strips it (for example `/28000/console` forwarded as `/console`), it should send `X-Forwarded-Prefix: /28000`. See "HTTPS and proxies". The header is honoured only from addresses in `[trusted_proxies]`.

#### Light and dark theme

The theme menu above Sign out, and in the corner of the status page, switches between System, Light and Dark. System follows your operating system. The choice is remembered in your browser.

### Public status page

A small "is the station live?" page anyone can see, served at `/`:

```toml
[ui]
enabled = true
mode = "public"
```

It lists every mount by default, including streams that encoders create on the fly with dynamic mounts (see "Configuration reference"). To show only some, name them: `public_mounts = ["/radio.mp3"]` (configured mounts only), or `public_mounts = []` to show none. Each live stream shows its codec, the bitrate if the encoder announces one, and how many people are listening (a mount can opt out with `hide_listener_count = true` (see "Configuration reference")). An offline stream appears muted. There are no IP addresses, settings, controls or sign-in, and the server version is shown in the header.

Each live stream has a **Play** button that becomes **Stop** while it plays. One stream plays at a time, with no player bar. The link it plays comes from `public_url` (see "Configuration reference") when set.

`/console/status` returns the same information as JSON, in every mode and without signing in, so you can feed a status widget on your website. It also includes `public_url`, `listen_port` and `tls`.

#### Status page and console together

`mode = "both"` serves the status page at `/` and keeps the sign-in console at `/console`:

```toml
[ui]
enabled = true
mode = "both"
username = "admin"
password_file = "secrets/ui-password"
```

The console used to be at `/ui`. That address, and everything under it, now redirects to `/console`, so old bookmarks and widgets keep working.

### Sign-in protection

- One operator account, separate from the encoder and management credentials.
- Sessions last one hour by default (`session_duration` (see "Configuration reference")), counted from sign-in and kept in memory, so a restart signs everyone out.
- Five attempts per second per address, with protection against bursts.
- Changing the password, username or mode signs everyone out after the next reload.

### Reload and updates

Console settings reload with the rest of the config (`kill -HUP`). The console is part of the binary, so updating it means installing a newer Quikcast.

## Monitoring

Three ways to see what is happening: **health checks** (is it alive?), **metrics** (numbers over time) and **logs** (what happened and why). None needs extra software.

### Health checks

The private admin address (`admin_listen`, default `127.0.0.1:9090`) has two endpoints for load balancers, Docker and uptime monitors:

| Endpoint | Meaning |
|---|---|
| `/health/live` | The process is up. Returns `200`. |
| `/health/ready` | The server is accepting new work. Returns `200`, or `503` while draining (see "Production checklist") or shutting down. |

```sh
curl -fsS http://127.0.0.1:9090/health/ready
```

> **Note: Ready does not mean "on air"**
>
> Readiness only says the server is accepting connections, not that an encoder is connected. To alert on a silent station, watch `active_sources` below.

### Prometheus metrics

`GET /metrics` on the admin address returns standard Prometheus text. Add it to your `prometheus.yml`:

```yaml
scrape_configs:
  - job_name: quikcast
    static_configs:
      - targets: ['127.0.0.1:9090']
```

Because the admin address only listens on localhost, run Prometheus on the same machine, or scrape through an SSH tunnel or a private network. Don't publish the port.

#### Useful numbers

| Question | Metric |
|---|---|
| Is a source connected? | `active_sources` (`active_mounts` is the same number: mounts that currently have a source) |
| How many people are listening? | `active_listeners` (the `/api/stats` field also includes estimated directory HLS listeners) |
| Is audio flowing? | `rate(bytes_served_total[1m])` |
| Are listeners being dropped for being too slow? | `rate(slow_consumers_total[5m])` |
| Are we refusing connections? | `rate(admission_rejections_total[5m])` |
| Did my last reload work? | `config_reload_failures_total` and `config_generation` |
| Is a relay struggling? | `rate(relay_failures_total[5m])`, `relay_cycles_exhausted_total` |
| Are logs being dropped? | `logging_dropped_total` |

The full list is in the metrics reference (see "Metrics").

#### Example alerts

```yaml
groups:
  - name: quikcast
    rules:
      - alert: StationOffAir
        expr: active_sources == 0
        for: 2m
        annotations: { summary: "No encoder connected to Quikcast" }

      - alert: ReloadFailed
        expr: increase(config_reload_failures_total[10m]) > 0
        annotations: { summary: "A Quikcast config reload was rejected" }

      - alert: ListenersBeingDropped
        expr: rate(slow_consumers_total[5m]) > 0.1
        for: 10m
        annotations: { summary: "Listeners are falling behind" }
```

### Live details from the API

For a snapshot of one stream or one listener, use the "Management API". Common reads:

```sh
TOKEN=$(cat secrets/management-token)
curl -H "Authorization: Bearer $TOKEN" http://127.0.0.1:9090/api/stats
curl -H "Authorization: Bearer $TOKEN" http://127.0.0.1:9090/api/mounts
```

#### Listener history

Quikcast keeps the last 24 hours of listener numbers in memory: peak concurrent listeners and new listeners per minute, and an estimate of unique listeners per hour.

```sh
# Server-wide, last 60 minutes
curl -H "Authorization: Bearer $TOKEN" \
  "http://127.0.0.1:9090/api/history?minutes=60"

# One mount
curl -H "Authorization: Bearer $TOKEN" \
  "http://127.0.0.1:9090/api/history?mount=/radio.mp3&minutes=1440"
```

Unique-listener counts are estimates (about 3% error), and listener addresses are never stored. History is lost on restart; for long-term graphs, scrape the metrics into Prometheus. See the API reference (see "Management API") for the format.

### Logs

Quikcast writes one structured line per important event to standard output: sources connecting, listeners joining, reloads, relay failovers and errors.

```text
INFO quikcast::mounts: source admitted mount=/radio.mp3 source_id=1 content_type="audio/mpeg" codec="mp3"
INFO quikcast::mounts: source closed mount=/radio.mp3 bytes_received=86562 disconnect_reason="shutdown"
```

Change how much is logged with `log_filter`, for example:

```toml
log_filter = "quikcast=debug"   # also shows each listener and the reason for each access denial
```

or temporarily with the `QUIKCAST_LOG` environment variable.

> **Warning: Where logs go matters**
>
> Logs are written through a fast, non-blocking buffer. Standard output must be a **terminal, a pipe, or the systemd journal**, something that is actively read. Redirecting straight to a regular file (`> quikcast.log`) is refused at startup. Under systemd or Docker this is automatic. From a shell, pipe through `tee`: `quikcast --config q.toml | tee quikcast.log`.
>
> If the reader stops, Quikcast drops log lines rather than freezing your stream, and counts them in `logging_dropped_total`.

Passwords, tokens and `Authorization` headers are never logged.

## Production checklist

A short list of things to do before you put real listeners on your station, followed by how to run, reload and restart it safely.

### Before you go live

- [ ] **Validate the config:** `quikcast --config quikcast.toml --check`
- [ ] **Use HTTPS**, either built in or via a proxy (see "HTTPS and proxies").
- [ ] **Keep the admin address private.** `admin_listen` must be loopback. Never forward `/api`, `/internal`, `/health` or `/metrics`.
- [ ] **Use unique, random passwords** for each mount, HLS, the management token and the console. Keep them in files readable only by the service user (`chmod 600`).
- [ ] **Set listener limits** that match your server's bandwidth. See "Capacity and limits".
- [ ] **Set up monitoring:** scrape `/metrics` and alert when `active_sources` is 0. See "Monitoring".
- [ ] **Tell Quikcast about your proxy** with `trusted_proxies` if you use one, so rules see real addresses.
- [ ] **Raise the file descriptor limit** above `max_connections` plus about 160 (`LimitNOFILE` in the example below). Details in "Capacity and limits"; watch `open_files` against `open_files_limit` in `/metrics`.
- [ ] **Test a reload** (`kill -HUP`) and a restart on a quiet day.
- [ ] **Back up** `quikcast.toml` and your `secrets/` folder. There is no other state to save.

### Run it as a service

#### systemd

**/etc/systemd/system/quikcast.service**

```ini
[Unit]
Description=Quikcast streaming server
After=network-online.target
Wants=network-online.target

[Service]
User=quikcast
Group=quikcast
ExecStart=/usr/local/bin/quikcast --config /etc/quikcast/quikcast.toml
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
LimitNOFILE=65536
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true

[Install]
WantedBy=multi-user.target
```

```sh
sudo useradd --system --no-create-home --shell /usr/sbin/nologin quikcast
sudo systemctl daemon-reload
sudo systemctl enable --now quikcast
```

Logs go to the journal automatically: `journalctl -u quikcast -f`.

#### Docker

The repository's `docker-compose.yml` is a good starting point. In your own setup remember:

- `listen = "0.0.0.0:8000"` inside the container, and publish only port `8000`.
- Mount your config at `/etc/quikcast/quikcast.toml` and secrets at `/etc/quikcast/secrets/`, read-only.
- The container runs as a non-root user, so secret files must be readable by it.
- Health checks run inside the container against `127.0.0.1:9090`.
- Reload with `docker compose kill -s HUP quikcast`.

### Change settings without stopping

Edit the config (or a secret, certificate or list file), validate it, and send a reload:

```sh
quikcast --config /etc/quikcast/quikcast.toml --check && kill -HUP "$(pidof quikcast)"
```

(With systemd: `sudo systemctl reload quikcast`.)

A reload is **all or nothing**. If anything is wrong the running configuration is kept and the reason is logged. Connected encoders and listeners are not interrupted.

These apply on reload: passwords, certificates, `[trusted_proxies]`, `[access]` and its list files, backups (`fallback`), signed-link keys, relays, `[sources]`, the console, HLS credentials, and turning `[hls]` on or off. You can also add or remove `[[mounts]]` entries: new streams appear without touching the others, and a removed stream disconnects its encoder and listeners. These need a **restart**: `listen`, `admin_listen`, `log_filter`, a mount's `listener_limit`, every `[limits]` value, enabling or disabling `[tls]`, and HLS capacity settings and `directory` while HLS is on. See the full table (see "Configuration reference").

The signal returns immediately and does not say whether it worked. Check the logs, or compare `config_generation` and `config_reload_failures_total` in the metrics.

#### Rotating a password

Change the file, then reload. Connected encoders stay connected; the **next** connection needs the new password.

### Restarting without dropping listeners

A restart disconnects everyone. To make it gentler, **drain** first: the server refuses new listeners and sources while current ones finish. Use **Stop accepting connections** on the console's System page, or the API:

```sh
curl -X POST -H "Authorization: Bearer $(cat secrets/management-token)" \
  http://127.0.0.1:9090/api/server/drain
```

After draining, `/health/ready` returns `503`, so a load balancer stops sending new listeners. When you are ready, stop the process with `SIGTERM` (or Ctrl+C); Quikcast waits up to `shutdown_timeout_ms` for connections to finish. Draining is one-way: to accept traffic again, restart. Relays stop reconnecting while draining, and new encoders are refused.

> **Note: What a restart resets**
>
> All runtime state is in memory: connected sources and listeners, statistics, listener history, relay start/stop choices and everything in HLS. Encoders and players reconnect on their own, and your HLS producer must publish again.

### Upgrading

1. Download the new release and read its notes.
2. Run the **new** binary's `--check` against your existing config.
3. Replace the binary and restart (drain first if you want a gentle stop).

### Sizing

Audio is not re-encoded, so CPU use is low. What grows is outbound bandwidth and memory, both covered in "Capacity and limits".

## Deploy on Dokploy

[Dokploy](https://dokploy.com) is a self-hosted platform that runs Docker apps behind Traefik with automatic HTTPS. This guide deploys Quikcast on it with a domain, your own config and secrets, and a health check, in about 15 minutes (mostly the first build). You need a server with Dokploy, a domain pointing at it, and the Quikcast repository or image.

### How the pieces fit

```mermaid
flowchart LR
  L["Listeners<br/>https://radio.example.com"] --> T["Traefik<br/>(HTTPS)"]
  T -->|"http :8000"| Q["Quikcast container"]
  E["Encoder"] -.->|"https, or direct :8000"| Q
  C["Config + secrets<br/>Dokploy file mounts"] --> Q
```

Traefik terminates HTTPS and forwards plain HTTP to port `8000`. The private admin port (`9090`) stays inside the container: the image's health check uses it, and nothing outside should.

### 1. Create the application

1. In Dokploy, open a **Project** and choose **Create Service → Application**.
2. Under **Provider** pick how Dokploy gets the code:
   - **GitHub / Git:** connect the Quikcast repository, pick the branch, and set **Build Type** to **Dockerfile** with path `./Dockerfile`. The first build compiles Rust and takes several minutes; later builds reuse the dependency cache.
   - **Docker:** if you build the image yourself (`docker build -t ghcr.io/you/quikcast:1 .` and push it), enter that image name instead. This is faster to deploy and avoids compiling on the server.

Do **not** deploy yet. It needs a config first.

### 2. Add the config and secrets

The image starts with an example config that expects a password file, so it fails until you provide one. In the application, open **Advanced → Mounts** and add **File Mounts**.

**File mount 1: the config**

| Field | Value |
|---|---|
| File path | `quikcast.toml` |
| Mount path | `/etc/quikcast/quikcast.toml` |

```toml
listen = "0.0.0.0:8000"        # must be 0.0.0.0 inside a container
admin_listen = "127.0.0.1:9090" # stays private

[trusted_proxies]               # Traefik's address, so listeners show their real IP
ips = ["10.0.0.0/8", "172.16.0.0/12"]

[ui]                            # optional: the web console at /console
enabled = true
mode = "private"
username = "admin"
password_file = "secrets/ui-password"
public_url = "https://radio.example.com"

[[mounts]]
path = "/radio.mp3"
username = "source"
secret_file = "secrets/radio-source"
```

**File mounts 2 and 3: the secrets.** Paths are relative to the config file, so `secrets/radio-source` means `/etc/quikcast/secrets/radio-source`.

| File path | Mount path | Content |
|---|---|---|
| `radio-source` | `/etc/quikcast/secrets/radio-source` | the encoder password (16+ characters) |
| `ui-password` | `/etc/quikcast/secrets/ui-password` | the console password (15+ characters) |

Generate good values on your own machine:

```sh
openssl rand -hex 16     # encoder password
openssl rand -base64 24  # console password
```

> **Tip: No console? Skip it**
>
> Leave out the `[ui]` block and the `ui-password` mount. Everything else works the same.

### 3. Add the domain

Open the **Domains** tab and add:

| Field | Value |
|---|---|
| Host | `radio.example.com` |
| Path | `/` |
| Container port | `8000` |
| HTTPS | on |
| Certificate | Let's Encrypt |

Make sure the domain's DNS record points at your Dokploy server first, or the certificate request fails.

### 4. Deploy

Press **Deploy** and watch the **Logs** tab. You are looking for:

```text
quikcast accepting connections listen=0.0.0.0:8000 admin_listen=127.0.0.1:9090
```

The **Deployments** tab should show a healthy container. The image has its own health check, so Dokploy flags it if the server stops answering.

### 5. Connect an encoder and listen

Use the values from "Connect an encoder":

| Setting | Value |
|---|---|
| Host | `radio.example.com` |
| Port | `443`, with TLS/SSL enabled |
| Mountpoint | `/radio.mp3` |
| Username | `source` |
| Password | the contents of `radio-source` |

Listeners open `https://radio.example.com/radio.mp3`. The console, if you enabled it, is at `https://radio.example.com/console`.

#### If your encoder fails through the domain

Some encoders use the older Icecast `SOURCE` request, which an HTTP proxy such as Traefik may reject. If an encoder works against the server directly but not through the domain, publish the port for encoders only:

1. In **Advanced → Ports** add a port: published `8000`, target `8000`, protocol TCP.
2. Point the encoder at `your-server-ip:8000` over plain HTTP.

Listeners keep using HTTPS through the domain. That direct port is unencrypted, so use a strong encoder password and, if you can, restrict it by firewall to your encoder's address or add `[mounts.source_access]` rules (see "Limit who can listen").

### Run it

#### Change settings

Edit the file mount's content (the config or a secret) and press **Save**, then either:

- **Redeploy.** Simple, but it disconnects everyone briefly. Encoders and players reconnect on their own.
- **Reload without disconnecting.** Open the application's **Terminal** tab and run `kill -HUP 1`. Quikcast is the container's main process, so this applies passwords, access rules, relays and the console settings instantly. Listeners and encoders stay connected. See "Configuration reference".

A file mount only changes inside the container after a redeploy or restart, so if a reload does not pick up your change, redeploy.

#### Check health and metrics

The admin port is private, so use the **Terminal** tab:

```sh
curl -s http://127.0.0.1:9090/health/ready
curl -s http://127.0.0.1:9090/metrics | head
```

#### Size the container

Audio uses little CPU, but bandwidth adds up: 1,000 listeners at 128 kbit/s is about 128 Mbit/s outbound. In **Advanced → Resources** you can cap CPU and memory. Real memory use sits well below `retained_audio_budget`, which is only a startup ceiling, so watch it in Dokploy's monitoring and leave headroom before setting a limit. See "Capacity and limits".

#### Nothing to back up

All runtime state is in memory. Keep a copy of your config and secrets, which live in the file mounts.

### Troubleshooting

| Symptom | Cause and fix |
|---|---|
| Container restarts; logs say `failed to read ... secrets/radio-source` | The secret file mount is missing or its mount path is wrong. It must be `/etc/quikcast/secrets/radio-source` for `secret_file = "secrets/radio-source"`. |
| Logs say `Permission denied` on a secret | The container runs as a non-root user. Check the file's mode on the host copy that Dokploy created and make it readable by others (`chmod 644`). |
| Domain shows `502 Bad Gateway` | The container is not healthy yet, or the domain's container port is not `8000`, or `listen` is not `0.0.0.0:8000`. |
| `404 page not found` from Traefik | The domain is not attached to this application, or DNS points somewhere else. |
| HTTPS certificate error | DNS does not point at the server yet, or ports 80/443 are blocked. Let's Encrypt needs both. |
| Listeners all show the same IP | Add Traefik's network to `[trusted_proxies] ips`. Docker networks are usually `10.0.0.0/8` or `172.16.0.0/12`. |
| Startup says `retained audio budget cannot cover admission reservations` | Your limits need more memory than `retained_audio_budget` allows. Lower `max_listeners` under `[limits]` or raise the budget. See "Capacity and limits". |
| Stream cuts off after a few minutes | A proxy timeout in front of Traefik (a CDN or load balancer). Long-lived audio needs long timeouts and no buffering. |
| Console login loops | Use the HTTPS domain. The session cookie is `Secure`, so browsers drop it over plain HTTP. |

### Compose instead of an application

Prefer **Compose**? Create a Compose service, paste the repository's `docker-compose.yml`, add the same config and secrets as bind mounts or files, and attach the domain with container port `8000`. The application route above is simpler.

## Troubleshooting

Find your symptom, then apply the fix.

> **Tip: Always run the checker first**
>
> ```sh
> quikcast --config quikcast.toml --check
> ```
> It reports the exact setting and file at fault, for example `mounts[1].fallback: unknown fallback mount "/backup"`, without starting the server. Secrets are never printed.

### The server will not start

| Message or symptom | What to do |
|---|---|
| `failed to deserialize configuration ... (schema)` with a line number | A setting is misspelled or has the wrong type (for example text where a number is expected). Unknown settings are rejected on purpose. Fix the line shown. |
| `secret_file: failed to read ...` | The path is wrong or unreadable. Paths are relative to the **config file**, not your current folder. |
| `... exactly one of secret or secret_file` | Set one, not both and not neither. |
| `Address already in use` | Another program (maybe a second Quikcast) uses that port. Stop it or change `listen`. |
| `admin_listen` rejected | It must be a loopback address such as `127.0.0.1:9090`. |
| `retained audio budget cannot cover admission reservations` | Your listener limits need more memory than the budget; the message says how much. Lower `max_listeners` or raise `retained_audio_budget`. See "Capacity and limits". |
| `logging stdout must be a pipe, socket, terminal...` | You redirected output straight to a file. Use `\| tee file.log`, systemd or Docker. |
| `relay ... requires a unique configured local mount` | A `[[relays]]` `mount` must match a `[[mounts]]` `path` exactly. |
| `ip_allow_file ... contains no rules` | An allow list file with no rules would admit everyone. Add an entry, or remove the setting. |

### My encoder cannot connect

| Error | Cause |
|---|---|
| `401 Unauthorized` | Wrong username or password. The default username is `source`. Check for a newline or quotes in the secret file. |
| `403 Forbidden` | The mount has `source_access` rules and the encoder's address is not allowed. Behind a proxy, check `trusted_proxies`. |
| `404 Not Found` | The mount is not defined in `quikcast.toml`, or the path differs from the configured one. Paths are case-sensitive. |
| `409 Conflict` | Another encoder already owns the mount, or a relay does. |
| `415 Unsupported Media Type` | The encoder's content type is not one of the supported formats (see "Streams and mounts") (`audio/mpeg`, `audio/aac`, `audio/ogg`, `audio/flac`). |
| Connection refused or timeout | Wrong host or port. `listen = "127.0.0.1:8000"` only accepts connections from the same machine. |
| Works directly but not through a proxy | See "HTTPS and proxies". |

### Listeners cannot play

| Symptom | Cause and fix |
|---|---|
| `404` for the stream | No source is connected to the mount (or the path is misspelled). Quikcast does not serve silence. Start your encoder. |
| `403 Forbidden` | An access rule (see "Limit who can listen") or a signed-link check (see "Signed, expiring links") refused the request. The response never says which, deliberately. Turn on `quikcast=debug` logging to see the reason. |
| `403` only from your own computer | Testing from `127.0.0.1` against a country allow list: private addresses have no country and fail an allow list. |
| `503` | The server has stopped accepting connections (draining) or is full. Check `max_listeners` and `listeners_per_mount`, and `/api/server`. |
| Stream stops after a while | Listeners who cannot keep up are disconnected. Check `slow_consumers_total`. A slow connection or an underpowered proxy is the usual cause. |
| Works in VLC, not in the browser | The browser may not support the codec (Ogg and FLAC support varies). Try MP3 or AAC, or HLS (see "HLS for browsers and apps"). |
| Everyone shows the same country or IP | You are behind a proxy. Configure `trusted_proxies` (see "HTTPS and proxies"). |

### Relays

| Symptom | What to check |
|---|---|
| Relay keeps reconnecting | `GET /api/relays/<mount>` shows the last error, status and next retry. Typical causes: wrong URL, bad credentials, an upstream format Quikcast does not accept, or a certificate problem. |
| `destination_not_allowed` | A public upstream redirected the relay (or an HLS playlist referenced a segment) to a private or local address, which is refused for safety. Fix the upstream, or point the relay at that address directly if it is yours. |
| Redirect error | The upstream redirects. Set `max_redirects`. HLS relays usually need `max_redirects = 3`, because segments are redirected to a CDN. |
| HLS relay is choppy, skips, or reconnects often | HLS relays are experimental. Try `hls_variant = "lowest"`, set `max_redirects = 3`, or use the station's Icecast/SHOUTcast URL instead. |
| `unsupported_or_invalid_media` on an HLS upstream | The playlist is encrypted, uses byte ranges, carries video only, or holds FLAC/ALAC in MP4. Only AAC and MP3 audio is relayed. |
| HLS relay reconnects every few seconds | The playlist has ended (`#EXT-X-ENDLIST`), so it is not a live stream. |
| Stopped relay won't start | Editing `enabled` only takes effect after a reload (`kill -HUP`). Use `POST /api/relays/<mount>` to start it now. |

### HLS

| Symptom | What to check |
|---|---|
| `404` on the playlist | Both **registration and publication** are needed. After a restart everything is gone until your producer publishes again. |
| Browser blocked it | CORS. `cors_origin` must be the page's exact origin: scheme, host and port, with no trailing slash. |
| Upload `401` | The HLS username or password is wrong, or you used a mount password (they must differ). |
| Upload `409` | A stale generation or revision, a duplicate segment, or a window that skips ahead. Re-read the stream state, then continue. |
| Upload `503` | HLS memory or upload slots are full. Raise `allocation_budget`, or publish a shorter window. |

### Console and status page

| Symptom | What to check |
|---|---|
| `404` at `/console` | `[ui] enabled` is `false`, or `mode = "public"`, which has no console. |
| `404` at `/` | The status page needs `mode = "public"` or `"both"`. |
| `/ui` sends me to `/console` | The console moved. Update bookmarks and proxy rules. |
| Signed in, then immediately signed out | The cookie is `Secure` and you are on plain HTTP. Use HTTPS, or set `secure_cookie = false` for testing. |
| Play does nothing | The format may be unsupported by your browser, the mount has no source, or it uses signed links. The play icon's tooltip says why. |

### Reload problems

| Symptom | What to check |
|---|---|
| Nothing changed after `kill -HUP` | Read the logs: a rejected reload says why and keeps the old config. Also check you edited the file Quikcast was started with. |
| "restart required" | You changed something that needs a restart: addresses, limits, a mount's `listener_limit` or enabling TLS. |

### Still stuck?

1. Raise logging: `QUIKCAST_LOG=quikcast=debug quikcast --config quikcast.toml`.
2. Look at `/api/stats` and `/api/mounts` for what Quikcast believes is happening.
3. Report it to the Quikcast maintainers with your Quikcast version (`quikcast --version`), the **redacted** config, and the relevant log lines. Never paste passwords or tokens.

---

# Part 5: Reference

## Configuration reference

Every setting Quikcast accepts, in the order you will meet them in a real file. Each entry tells you what the setting does, its type, its default, the values it accepts, and whether a SIGHUP reload applies it or it needs a restart.

Prefer a form to a text editor? The config generator builds a file for the common setups.

New to Quikcast? Start with the "Quickstart" for a working local setup, then come back here when you need to know exactly what a line does. A copy-ready file with every option commented lives at `config/quikcast.reference.toml` in the repository; `config/quikcast.example.toml` is the short starting point.

### How to read this page

Each setting is introduced like this:

> **Type** `integer` · **Default** `4096` · **Range** `1–65,536` · **Applies** restart

| Field | Meaning |
|---|---|
| **Type** | The TOML type: `string`, `integer`, `boolean`, `array of strings`, `table`, or `array of tables`. |
| **Default** | The value used when the key is omitted. "none" means the feature is off or the key is required. |
| **Range / Values** | What is accepted. Anything else stops startup with a diagnostic that names the key. |
| **Applies** | `reload` means `kill -HUP` applies it to new work without dropping connections. `restart` means the process must be restarted. |

#### Rules that apply to the whole file

- **Unknown keys are rejected.** A typo such as `listner_limit` stops startup instead of being ignored.
- **`[[mount]]` and `[[relay]]` also work.** `[[mounts]]` and `[[relays]]` are lists, one block per entry, so the guides use the plural. If the singular reads better to you, `[[mount]]` and `[[relay]]` are accepted too, along with their sub-tables (`[mount.access]`, `[mount.listener_auth]`). Use one spelling per file: mixing `[[mount]]` with `[[mounts]]` stops startup with `duplicate field mounts` (and likewise for relays).
- **Root keys come first.** `listen`, `admin_listen` and `log_filter` must appear before the first `[table]` header, or TOML assigns them to that table.
- **Paths are relative to the config file.** A `*_file` value such as `secrets/radio-source` resolves beside the configuration file, not the working directory. Absolute paths stay absolute. `~` and `$VARIABLES` are not expanded.
- **Size limit.** The configuration file itself may be at most 128 KiB.
- **A failed reload changes nothing.** If SIGHUP finds any error, the running configuration stays active and the error is logged.

> **Tip**
>
> Validate any change before applying it:
>
> ```sh
> quikcast --config quikcast.toml --check
> ```
>
> `--check` runs the complete startup validation, including reading every secret, list, certificate and database, and then exits without binding a port. Exit code `0` means the file is good.

#### Secret values

Secrets are never defaults, so you must supply them. Where a setting offers both an inline value and a `_file` form, **prefer the file**.

| Kind | Length | Characters | Used by |
|---|---|---|---|
| Mount / HLS password | 16–512 bytes | any bytes; a password may contain `:` | `secret`, `secret_file` on mounts, `[sources]`, `[hls]` |
| Usernames | 1–64 bytes | ASCII graphic, no whitespace, no `:` | every `username` |
| Management token | 32–512 bytes | ASCII graphic, no whitespace | `[management]` |
| Upstream relay password | 1–512 bytes | ASCII graphic, no whitespace | `[[relays]]` |
| Signed-URL key | 32–4,096 bytes | any bytes | `listener_auth` |
| UI password | at least 15 characters, at most 512 bytes | UTF-8 | `[ui]` |

A secret file contains only the secret. One trailing newline is removed; nothing else is trimmed. Do not wrap the value in quotes or write `password=...`. Files are read at startup and on SIGHUP, so editing a file takes effect only after a successful reload or restart.

Generate a good value with:

```sh
openssl rand -hex 32 > secrets/radio-source
```

### Root settings

These keys sit at the top of the file, above every table.

#### `listen`

> **Type** `string` (`host:port`) · **Default** `"127.0.0.1:8000"` · **Applies** restart

The address of the **public listener**. Players, encoders, HLS clients and the operator console all connect here.

The default only accepts connections from the same machine, which is right for local testing or when a reverse proxy runs beside Quikcast. To accept outside connections, bind a public address such as `"0.0.0.0:8000"`. Inside Docker you must use `0.0.0.0`, otherwise the published port has nothing to reach.

```toml
listen = "0.0.0.0:8000"
```

Use port `0` only in automated tests; the operating system then picks a free port.

#### `admin_listen`

> **Type** `string` (`host:port`) · **Default** `"127.0.0.1:9090"` · **Applies** restart

The address of the **private listener**. It serves `/health/live`, `/health/ready`, `/metrics` and the native `/api` management routes.

This address **must be a loopback address** (`127.0.0.1` or `::1`) unless you opt in with `management.allow_remote`. Without that switch Quikcast refuses to start with a non-loopback admin address, because these routes can disconnect listeners and drain the server. Reach it from outside through an SSH tunnel or an internal-only proxy, or read remote management before opting in.

#### `log_filter`

> **Type** `string` · **Default** `"quikcast=info"` · **Applies** restart

A [tracing filter](https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html) that decides how much is logged. Examples: `"quikcast=debug"` for connection-level detail, `"quikcast=warn"` for problems only.

The `QUIKCAST_LOG` environment variable overrides this value when set. Logs go to standard output through a bounded, non-blocking writer, so the output must be a terminal or a pipe that something is reading. Redirecting straight to a regular file is rejected. Logging currently requires a Unix system.

### `[tls]`

Serve HTTPS directly from Quikcast. Omit the table to serve plain HTTP, which is the right choice when a proxy such as Traefik, nginx or Cloudflare already terminates TLS.

```toml
[tls]
cert_file = "secrets/tls/fullchain.pem"
key_file = "secrets/tls/privkey.pem"
```

TLS applies to the public listener only, unless you set `management.tls` for a remotely exposed admin listener. Otherwise the admin listener stays plain. Quikcast offers TLS 1.2 and 1.3 with ALPN `http/1.1`. A plain HTTP request sent to a TLS port is closed without a response, and the TLS handshake counts against `header_timeout_ms` and `max_handshakes`.

> **Note**
>
> Enabling or disabling `[tls]` needs a restart. **Renewing a certificate does not**: replace the files and send SIGHUP. New connections use the new certificate, existing listeners are not interrupted, and a bad file leaves the old certificate in place.

#### `cert_file`

> **Type** `string` (path) · **Default** none (required inside `[tls]`) · **Max size** 256 KiB · **Applies** reload

A PEM file containing the certificate chain, leaf certificate first, with one to eight certificates. A Let's Encrypt `fullchain.pem` is exactly the right file.

#### `key_file`

> **Type** `string` (path) · **Default** none (required inside `[tls]`) · **Max size** 64 KiB · **Applies** reload

A PEM file with the matching private key (PKCS#8, PKCS#1 or SEC1). A key that does not match the certificate stops startup or the reload with an error.

### `[trusted_proxies]`

Tells Quikcast which network peers are your own proxies, so it can report **real listener addresses** instead of the proxy's address. The real address feeds IP rules, country rules, listener statistics and logs. By default no proxy is trusted and Quikcast uses the connecting address as is.

```toml
[trusted_proxies]
ips = ["127.0.0.1", "10.0.0.0/8"]
providers = ["cloudflare"]
proxy_protocol = false
```

> **Warning**
>
> Only list infrastructure you control. Anyone you trust here can claim any client address, which weakens every IP and country rule.

#### `ips`

> **Type** `array of strings` · **Default** `[]` · **Max** 64 entries · **Applies** reload

IP addresses or CIDR networks (IPv4 or IPv6) of your proxies. When a connection comes from one of these, Quikcast reads the `X-Forwarded-For` header and walks it right to left, stopping at the first address that is not itself trusted. Bare addresses mean a single host (`/32` or `/128`). Hostnames and ports are rejected. Errors name the entry, for example `trusted_proxies.ips[1]`.

The same trust decision applies to `X-Forwarded-Prefix`, which lets the operator console work behind a proxy that mounts it under a path prefix.

#### `providers`

> **Type** `array of strings` · **Default** `[]` · **Values** `"cloudflare"` · **Applies** reload

Adds the built-in list of Cloudflare's published address ranges. A connection that comes **directly** from Cloudflare may then supply the client address in `CF-Connecting-IP`. The ranges ship inside Quikcast and are never fetched at runtime; they are refreshed by upgrading Quikcast.

#### `proxy_protocol`

> **Type** `boolean` · **Default** `false` · **Applies** reload (new connections)

Use this behind a **layer-4** load balancer (HAProxy in TCP mode, nginx `stream`, a cloud network load balancer) that cannot add HTTP headers. When `true`, every public connection must begin with a [PROXY protocol](https://www.haproxy.org/download/1.8/doc/proxy-protocol.txt) v1 or v2 header, sent before TLS and HTTP.

- It needs `ips` or `providers`. Only peers that match them may send the header; a connection from anyone else is closed without a reply.
- The client address in the header replaces the connecting address for all access rules and statistics.
- A header marked `LOCAL` or `UNKNOWN`, which is what health checks send, keeps the connecting address.
- A missing or malformed header closes the connection.
- The admin listener never uses PROXY protocol.

```toml
[trusted_proxies]
ips = ["10.0.0.0/8"]
proxy_protocol = true
```

> **Warning**
>
> Turning this on means **every** public connection, including your own health checks and direct `curl` tests, has to arrive through the proxy.

### `[management]`

Enables the native management API on the admin listener (`/api/server`, `/api/stats`, `/api/mounts`, `/api/listeners`, `/api/history`, and others).

The API is **fail-closed**: without this table every `/api` request is rejected. Mount and HLS passwords do not unlock it.

```toml
[management]
token_file = "secrets/management-token"
```

Call it by sending the token as a Bearer credential to the admin address:

```sh
curl -H "Authorization: Bearer $(cat secrets/management-token)" \
  http://127.0.0.1:9090/api/server
```

#### `token_file`

> **Type** `string` (path) · **Default** none · **Applies** reload

Path to a file holding the token, 32–512 ASCII graphic characters. Set exactly one of `token_file` and `token`. Editing the file rotates the token after the next successful reload.

#### `token`

> **Type** `string` · **Default** none · **Applies** reload

The token written directly in the config. It works, but keeps a secret in a file you may commit or share. Prefer `token_file`.

#### `allow_remote`

> **Type** `bool` · **Default** `false` · **Applies** restart

Permits `admin_listen` to bind a non-loopback address such as `0.0.0.0:8001`, so a remote management client (for example a hosting control panel) can read `/api/stats`, `/api/mounts`, `/api/listeners` and call `DELETE /api/listeners/{id}`. With `false` (the default) a non-loopback `admin_listen` stops startup with an error that names this switch.

When it is `true`, validation (`quikcast --check` included) also requires a `[management]` token and applies the protections described under remote management.

#### `allowed_ips`

> **Type** `array of strings` · **Default** `[]` · **Applies** reload

Only with `allow_remote = true`. IP addresses or CIDR ranges (same syntax as `[trusted_proxies]`, at most 64 entries) allowed to connect to the admin listener. Other peers are dropped before any bytes are read. Empty means any peer that holds the token. The check uses the TCP peer address, never `X-Forwarded-For`. Setting it without `allow_remote` is a configuration error.

#### `tls`

> **Type** `bool` · **Default** `false` · **Applies** reload

Only with `allow_remote = true`, and only when a top-level `[tls]` certificate and key are configured. Serves the admin listener over TLS with the same certificate as the public listener (TLS 1.2/1.3, ALPN `http/1.1`); health and metrics on that port then also require HTTPS. Enabling or disabling `[tls]` itself still needs a restart. Setting `tls = true` without `allow_remote` or without `[tls]` is a configuration error.

#### Remote management

```toml
admin_listen = "0.0.0.0:8001"

[management]
token_file = "secrets/management-token"  # openssl rand -hex 32
allow_remote = true
allowed_ips = ["203.0.113.10"]           # the management client
tls = true                               # needs [tls]
```

What Quikcast enforces once `allow_remote = true`:

- A token of at least 32 bytes, compared in constant time (padded fixed-size comparison). There are no accounts and no lockout of the token itself.
- Per-client failed-authentication throttling: after 10 failed attempts within 60 seconds, a client receives `429 too_many_failures` with `Retry-After` (even for a correct token) until the window ends. IPv6 clients share one budget per /64. The table holds 4096 clients; if it is full of active entries, new clients are not tracked. A successful call clears the client's counter. Without `allow_remote`, nothing is throttled, as before.
- Optional peer allow-list (`allowed_ips`) and optional TLS (`tls`).
- A startup warning in the log that the API is reachable beyond loopback.

What it does not do:

- **Without `tls = true` the bearer token and all responses travel in clear text.** Put the port behind a TLS-terminating proxy, a VPN or a private network, and firewall it to the management client.
- `/health/live`, `/health/ready` and `/metrics` share this listener and stay unauthenticated, so they are reachable too, and so are the HLS ingest routes (`/internal/...`, protected by the HLS producer credential). Use `allowed_ips` or a firewall to keep them private.
- Throttling is per client IP behind your firewall's view; a distributed attacker is not stopped, and an attacker who can spoof a trusted client address can lock that address out. A token is only as strong as its entropy.
- The token grants every management action (drain, disconnect, source control). There are no read-only tokens.

### `[icecast_admin]`

Serves Icecast's admin API on the public listener, so Icecast control panels and monitoring tools can use Quikcast as a remote Icecast server. It is off unless this table exists. See "Icecast-compatible admin API".

```toml
[icecast_admin]
username = "admin"
password_file = "secrets/icecast-admin"
```

| Path | Returns |
|---|---|
| `/admin/stats` | Server totals and one `<source>` per live mount: listeners, artist, title, content type, bitrate, listen URL |
| `/admin/listmounts` | Live mounts with their listener counts |
| `/admin/listclients?mount=/radio.mp3` | One `<listener>` per client with `IP`, `UserAgent`, `Connected` (seconds) and `ID` |
| `/admin/killclient?mount=/radio.mp3&id=…` | Disconnects that listener |
| `/status-json.xsl` | Public JSON status with no login, as Icecast serves it. `?mount=` narrows it, and a mount with `hide_listener_count` reports 0 listeners |

A `.xsl` or `.xml` suffix is accepted on each `/admin` name. A title written "Artist - Title" is reported as separate `artist` and `title`. The same credential may also call `/admin/metadata`. Wrong or missing credentials get `401` with a Basic challenge, and repeated failures from one address are throttled with `429`.

#### `username`

> **Type** `string` · **Default** `"admin"` · **Applies** reload

The Basic-auth user name.

#### `password_file`

> **Type** `string` (path) · **Default** none · **Applies** reload

Path to a file holding the password, 16–512 bytes. Set exactly one of `password_file` and `password`.

#### `password`

> **Type** `string` · **Default** none · **Applies** reload

The password written directly in the config. Prefer `password_file`.

### `[ui]`

The embedded operator console, served at `/console` on **both** listeners, and an optional public status page at `/`. The table can also be written as `[console]`; use one spelling per file. It is compiled into the binary, so there is nothing else to install. It is off by default.

```toml
[ui]
enabled = true
mode = "private"
username = "admin"
password_file = "secrets/ui-password"
```

Behind a reverse proxy that serves the console under a path prefix and strips it (for example `/28000/console` forwarded as `/console`), the proxy can send `X-Forwarded-Prefix: /28000`. Quikcast then prefixes the console's asset, script and link URLs, its API calls, its redirects and the session cookie `Path` (`/28000/console`). The header is honoured **only** from peers listed in `[trusted_proxies]`. A value must start with `/`, have no trailing `/`, `//` or `..`, use only letters, digits and `. _ ~ - /`, and be at most 128 characters; anything else, or a repeated header, is ignored. Stream URLs in the console use `[ui] public_url` when set; otherwise same-origin links carry the prefix too.

The console has one operator identity, separate from source, HLS and management credentials. Any change to the effective UI settings, including a password change, signs out existing sessions after the next reload.

#### `enabled`

> **Type** `boolean` · **Default** `false` · **Applies** reload

When `false`, every `/console` and `/ui` URL, the status page at `/` and the assets all return 404.

#### `mode`

> **Type** `string` · **Default** `"private"` · **Values** `"private"`, `"public"`, `"both"` · **Applies** reload

`"private"` shows a login form and, after sign-in, the full console at `/console`. `"public"` shows only a small sanitized status page at `/` and offers no login or controls. `"both"` runs the two at once: the status page at `/` and the console at `/console`, which still needs its sign-in. `/console/status` is readable without signing in in **every** mode where the UI is enabled. The console used to live at `/ui`; requests to `/ui` and below redirect to `/console`.

#### `username`

> **Type** `string` · **Default** `""` · **Range** 1–64 ASCII graphic bytes · **Applies** reload

The operator login name. Required in private mode.

#### `password_file`

> **Type** `string` (path) · **Default** none · **Applies** reload

Path to a file holding the password: at least 15 characters excluding surrounding whitespace, at most 512 bytes. Obvious values (a single repeated character, common passwords) are rejected. Required in private mode. The file is re-read on every reload.

#### `secure_cookie`

> **Type** `boolean` · **Default** `true` · **Applies** reload

Marks the session cookie `Secure`, so browsers only send it over HTTPS. Leave it on in production, including when a proxy terminates TLS. Set it to `false` only for throwaway testing over plain HTTP.

#### `session_duration`

> **Type** `integer` (seconds) · **Default** `3600` · **Range** 60–2,592,000 (30 days) · **Applies** reload

How long a console sign-in stays valid. The clock starts at login and is not extended by activity, so the operator signs in again once it runs out. The same value sets the cookie's `Max-Age`. Sessions are held in memory, so a restart still signs everyone out, and so does any change to the console settings, including this one.

```toml
[ui]
session_duration = 28800 # stay signed in for 8 hours
```

#### `public_url`

> **Type** `string` · **Default** none · **Applies** reload

The address listeners use to reach your streams, for example `"https://radio.example.com"`. The console uses it for the **Copy URL** buttons and the built-in test player. Without it, the console guesses: it reuses the address of the page you are on and the public port from `listen`. That guess is right for a direct setup and wrong behind a proxy, a CDN or a different domain, so set it in those cases.

It must be an `http://` or `https://` origin: no path, query, fragment or user name. A trailing slash is removed. Changing it signs out console sessions on the next reload, like any other console setting.

```toml
[ui]
enabled = true
username = "admin"
password_file = "secrets/ui-password"
public_url = "https://radio.example.com"
```

#### `public_mounts`

> **Type** `array of strings` · **Default** every mount when `mode` is `"public"` or `"both"`, none when `"private"` · **Applies** reload

The mounts the public status page may show, and the ones `/console/status` reports without a sign-in. It takes one of three forms:

- **Omitted:** with `mode = "public"` or `"both"`, every mount is shown, including mounts that encoders create on the fly (see `allow_dynamic_mounts`). With `mode = "private"`, none are.
- **`["*"]`:** every mount, whatever the mode. It must be the only entry.
- **A list of paths** such as `["/radio.mp3"]`: only those. Each entry must be a configured mount, so an encoder-created mount can never be named here. An empty list `[]` discloses nothing.

Showing a mount publishes its availability, codec, content type and listener count (unless the mount sets `hide_listener_count`). It does not give anyone access to play it.

### `[limits]`

Capacity and timing controls that protect the server. Every value has a sensible default, so most stations never need this table. All of `[limits]` needs a restart.

```toml
[limits]
max_listeners = 2000
listeners_per_mount = 2000
```

Startup checks that the memory you reserve fits `retained_audio_budget`. If it does not, you get `retained audio budget cannot cover admission reservations`; lower `max_listeners` or raise the budget.

| Setting | Default | Range |
|---|---|---|
| `ring_bytes` | `4194304` | positive |
| `ring_entries` | `4096` | 1–65,536 |
| `join_bytes` | `65536` | 0 to `ring_bytes` |
| `max_connections` | `12000` | 1–100,000 |
| `max_handshakes` | `128` | 1 to `max_connections` |
| `max_mounts` | `64` | 1–1,024 |
| `max_listeners` | `10000` | 1 to `max_connections` |
| `listeners_per_mount` | `10000` | 0 to `max_listeners` |
| `retained_audio_budget` | `2147483648` | enough for the reservation formula |
| `relay_allocation_budget` | `33554432` | at least 2 MiB per relay |
| `header_timeout_ms` | `5000` | 1–3,600,000 |
| `source_timeout_ms` | `10000` | 1–3,600,000 |
| `write_timeout_ms` | `10000` | 1–3,600,000 |
| `shutdown_timeout_ms` | `10000` | 1–3,600,000 |
| `flac_initialization_bytes` | `65536` | 42–262,144 |
| `flac_frame_bytes` | `1048576` | 16–4,194,304 |

#### `ring_bytes`

The most encoded audio kept in memory for each live stream, in bytes. It is the catch-up buffer new listeners join from, and the line a slow listener must stay inside: a listener who falls further behind than the ring is disconnected, so one slow client never holds back everyone else. Default 4 MiB.

#### `ring_entries`

The most separate chunks of audio the ring can hold at once. Whichever of `ring_bytes` and `ring_entries` fills first decides when the oldest audio is dropped. A chunk is a block of published data, not one second or one codec frame.

#### `join_bytes`

How much recent audio a new listener may start from, in bytes (not milliseconds). Codec rules still decide the exact safe starting point. `0` means "start at the live edge".

#### `max_connections`

The most simultaneous TCP connections on the **public** listener, counting encoders, players, the console and HLS downloads. The admin listener has its own fixed reserve of 32 connections, so a flood of public clients can never lock you out of health checks or management. Connections beyond the limit are refused, not queued.

#### `max_handshakes`

The most connections that may be waiting to send their request headers (or finish a TLS handshake) at one time. This is the main defence against slow-connection attacks. The admin listener has a separate reserve of 16.

#### `max_mounts`

The most static `[[mounts]]` you may configure. The default is 64 and the ceiling is 1,024. Idle mounts are cheap, but every mount reserves audio memory (about 5.4 MB with default ring settings), so startup checks the total against `retained_audio_budget` and refuses to start if it does not fit. Raise the budget when you raise this. Changing it needs a restart. Mounts that encoders create on demand through `[sources]` are not counted here.

#### `max_listeners`

The most simultaneous **audio listeners** across all mounts. HLS downloads are ordinary requests and do not count here. This value also sizes the memory reservation, even when individual mounts are capped lower.

#### `listeners_per_mount`

The default listener cap for each mount. `0` means no per-mount cap beyond `max_listeners`. A mount's own `listener_limit` replaces this value rather than being combined with it.

#### `retained_audio_budget`

The total memory, in bytes, Quikcast promises it can use for audio rings, parser buffers and listener references. Startup calculates what your mounts and `max_listeners` require and refuses to start if that exceeds the budget. Default 2 GiB, enough for the default maximum of 64 mounts with default listener limits. If you raise `max_mounts`, raise this budget with it. It is a ceiling for these checks, not memory Quikcast allocates up front. The exact formula is in "Capacity and limits".

#### `relay_allocation_budget`

Memory set aside for relay workers, at least 2 MiB per configured relay (up to 64). Disabled relays still count. Default 32 MiB.

#### `header_timeout_ms`

How long a client may take to send its request headers before the connection is dropped. Also bounds the TLS handshake.

#### `source_timeout_ms`

How long an encoder may send nothing before it is disconnected. A healthy stream can run forever; this only catches stalls.

#### `write_timeout_ms`

How long a listener's socket may refuse data before the listener is disconnected as a slow consumer. A quiet stream with nothing to send is not a violation.

#### `shutdown_timeout_ms`

How long a graceful shutdown waits for connections to finish after you stop the server. Anything still running afterwards is aborted.

#### `flac_initialization_bytes`

The most data Quikcast accepts for the start of a native FLAC stream: the `fLaC` marker plus every metadata block, including cover art. Raise it if your encoder embeds large artwork.

#### `flac_frame_bytes`

The most bytes allowed for a single unfinished native FLAC frame. This is a size limit in bytes, not a sample or block-size setting.

### `[[mounts]]`

A **mount** is one stream path, such as `/radio.mp3`, that an encoder feeds and listeners play. Every `[[mounts]]` header starts a new mount; the settings under it, and its sub-tables, belong to it. You can also write `[[mount]]` (and `[mount.access]` and so on) if you prefer the singular; use one spelling per file.

Configure 1 to `limits.max_mounts` mounts (64 by default). Zero mounts is allowed only if you enable `[hls]` or `[sources]`.

```toml
[[mounts]]
path = "/radio.mp3"
username = "source"
secret_file = "secrets/radio-source"
```

Only one encoder can own a mount at a time. A second one is refused with `409 Source already connected`; there is no takeover or priority. When the encoder disconnects, its listeners disconnect too, and players reconnect to the next encoder session.

#### `path`

> **Type** `string` · **Default** none (required) · **Applies** reload

The URL path listeners use. It must start with `/`, be at most 2,048 bytes, and use only ASCII letters, digits and `/ . _ - ~`. Names are case-sensitive, and nested names such as `/stations/jazz` are fine.

Not allowed: `/` alone, a trailing `/`, `//`, `.` or `..` parts, spaces, Unicode, or any path under the reserved roots `/api`, `/admin`, `/internal`, `/health`, `/metrics` and `/hls`.

The extension does not choose the codec. `/radio.mp3` can carry any supported format; the encoder's content type decides.

Adding, removing and renaming mounts on reload is described in "Streams and mounts"; a rename is a removal plus an addition. A reload that adds a path is refused, and the running configuration is kept, if an encoder-created mount is already using that path, if the mount count or the `limits.retained_audio_budget` arithmetic no longer fits, or if the encoder-created mounts already live would no longer fit in the remaining budget.

#### `username`

> **Type** `string` · **Default** `"source"` · **Applies** reload

The username the encoder uses for HTTP Basic authentication (and for metadata updates).

#### `secret_file`

> **Type** `string` (path) · **Default** none · **Applies** reload

Path to the encoder password file. Set exactly one of `secret_file` and `secret`. If you set neither, the mount inherits the whole global `[sources]` credential.

#### `secret`

> **Type** `string` · **Default** none · **Applies** reload

The encoder password written directly in the config. Prefer `secret_file`.

#### `fallback`

> **Type** `string` · **Default** none · **Applies** reload

Another configured mount to serve when this one has no source. The listener keeps its original URL; Quikcast attaches it internally, with no redirect. Chains may be up to eight mounts long including the first. Unknown targets, a mount pointing at itself, loops and chains that are too long stop startup. Compatible MP3 and AAC listeners return to the original mount automatically when its source comes back. See "Backup streams (fallback)".

```toml
[[mounts]]
path = "/live.mp3"
fallback = "/automation.mp3"
secret_file = "secrets/live-source"

[[mounts]]
path = "/automation.mp3"
secret_file = "secrets/automation-source"
```

#### `fallback_when_full`

> **Type** `boolean` · **Default** `false` · **Applies** reload · **Requires** `fallback`

When this mount has reached its `listener_limit`, serve new listeners from its `fallback` instead of refusing them. See "Backup streams (fallback)". Each mount in a chain decides for itself. If every mount is full the listener is refused. Server-wide `limits.max_listeners` is not affected.

#### `hide_listener_count`

> **Type** `boolean` · **Default** `false` · **Applies** reload

Keep this mount's listener count off the public status page and `/console/status`. The mount is still listed, with its availability, codec and bitrate, just without a number. Because the page's server-wide total would reveal the hidden count, the total is left out as soon as any mount sets this. It changes only what the public sees: the signed-in console, `/api`, `/metrics` and listener limits are unaffected.

#### `listener_limit`

> **Type** `integer` · **Default** inherit `limits.listeners_per_mount` · **Range** 0 to `max_listeners` · **Applies** restart

The most listeners this mount allows. `0` removes the per-mount cap (the global limits still apply). A listener served through `fallback` counts against the mount that actually serves it.

#### `charset`

> **Type** `string` · **Default** UTF-8 · **Applies** reload

The character set of title text sent to the metadata endpoint (see "Connect an encoder") for this mount, for encoders that cannot send UTF-8. Quikcast converts it to UTF-8 before listeners see it. Use a standard name such as `ISO-8859-1` or `windows-1252` (`ISO-8859-1` is treated as `windows-1252`). A `charset=` field on a metadata request overrides this value. Text that is not valid in the chosen set is rejected rather than garbled. UTF-16 and other non-ASCII-compatible sets are not supported.

#### `max_listener_duration`

> **Type** `integer` · **Default** `0` (unlimited) · **Range** 0–31,536,000 seconds · **Applies** reload

The longest a single listener may stay connected to this mount. When the time is up, Quikcast closes that connection and most players reconnect on their own. It is counted from when the listener connected, and applies to listeners who asked for this mount, including those served through its `fallback`. Disconnects are counted under the `duration_limit` reason (see "Metrics"). Use it to stop forgotten browser tabs and idle players holding connections open for days.

#### `intro`

> **Type** `string` (file path) · **Default** none · **Applies** reload

An audio file played to every new listener before the live stream starts, such as a station ID or a short jingle. Paths are relative to the config file. The file must be **MP3 or AAC (ADTS)** and at most 8 MiB. Quikcast never converts audio, so the clip must match the live stream's **format, sample rate and channel count**; bitrate may differ. Quikcast compares it with the stream's first frame, and if anything differs (an AAC intro on an MP3 mount, 48 kHz against 44.1 kHz, mono against stereo) the listener gets no intro and a warning naming both formats is logged once. ID3 tags are stripped. Ogg and FLAC mounts do not support intros, and the intro starts once the encoder is sending audio.

```toml
[[mounts]]
path = "/radio.mp3"
secret_file = "secrets/radio-source"
intro = "audio/station-id.mp3"
max_listener_duration = 14400   # 4 hours
charset = "ISO-8859-1"
```

#### `[mounts.listener_auth]`

Protect this mount with signed, expiring URLs created by your own application. Omit the table, or use `type = "none"`, to keep the mount public. Quikcast only verifies; it has no accounts or sessions. See "Signed, expiring links" for the exact signing recipe.

```toml
[mounts.listener_auth]
type = "signed_url"
secret_file = "secrets/radio-signing-key"
max_ttl_seconds = 86400
clock_skew_seconds = 0
previous_secret_files = []
bind_ip = false
```

| Key | Default | Range | Meaning |
|---|---|---|---|
| `type` | `"none"` | `"none"`, `"signed_url"` | `"none"` leaves the mount public. |
| `secret_file` | none | 32–4,096 bytes | HMAC key shared with your application. Required for `signed_url`. |
| `max_ttl_seconds` | `86400` | 1–604,800 | The furthest in the future a link may expire. Longer links are refused. |
| `clock_skew_seconds` | `0` | 0–60 | Extra time after expiry a link is still accepted, to tolerate clock drift. |
| `previous_secret_files` | `[]` | up to 4 files | Older keys that still verify links, so you can rotate the key (see "Signed, expiring links") without breaking links already issued. Same size rules as `secret_file`; each key must be different. |
| `bind_ip` | `false` | `true`, `false` | Also sign the listener's IP address, so a link only works from the address it was made for. See "Signed, expiring links". |

#### `[mounts.access]`

Restrictions on who may **listen**. They are added to the global `[access]` rules: a listener must pass both. The fields are identical to `[access]` except that `geoip_database` and `asn_database` are only allowed in the global table.

```toml
[mounts.access]
countries_allow = ["GH", "NG"]
ip_deny_file = "lists/blocked.txt"
```

#### `[mounts.source_access]`

Restrictions on which IP addresses may connect an **encoder** to this mount. Credentials are still required. There is no global version, and no User-Agent or country rules here.

```toml
[mounts.source_access]
ip_allow = ["203.0.113.10", "2001:db8::/48"]
```

| Key | Type | Meaning |
|---|---|---|
| `ip_allow` | array of strings | Only these IPs or CIDRs may connect. Empty means no restriction. |
| `ip_allow_file` | path | A list file merged with `ip_allow`. It must contain at least one rule. |
| `ip_deny` | array of strings | These IPs or CIDRs are always refused. |
| `ip_deny_file` | path | A list file merged with `ip_deny`. An empty file is fine. |

Up to 10,000 distinct rules per list, counting inline and file entries together. Changes apply on reload.

### `[access]`

Global restrictions on who may **listen**, applied to every mount, in addition to each mount's own `[mounts.access]`. Omit it for open playback.

A listener is allowed only if it passes every category you configure: IP, User-Agent, country and network (ASN). A deny rule always wins over an allow rule in the same category. Everything here applies on reload.

```toml
[access]
ip_deny_file = "lists/blocked.txt"
user_agent_deny = ["exact:bad-monitor"]
countries_allow = ["GH", "NG"]
```

#### `ip_allow` and `ip_deny`

> **Type** `array of strings` · **Default** `[]` · **Limit** 10,000 distinct rules together with the file

IPv4 or IPv6 addresses or CIDR networks, for example `"203.0.113.9"` or `"198.51.100.0/24"`. With a non-empty `ip_allow`, only matching listeners are admitted. `ip_deny` always refuses matches. Equivalent entries are merged; overlapping networks are kept as written. IPv4-mapped IPv6 addresses (`::ffff:192.0.2.1`) match their IPv4 form.

#### `ip_allow_file` and `ip_deny_file`

> **Type** `string` (path) · **Default** none · **Max size** 1 MiB

A text file of rules, one IP or CIDR per line. Blank lines and lines starting with `#` are ignored, and a leading UTF-8 byte-order mark is tolerated. The file is merged with the inline list and re-read on every reload, so you can update a blocklist without restarting.

```text
# blocked.txt
203.0.113.0/24
198.51.100.7
2001:db8:bad::/48
```

Errors name the file and line, such as `ip_deny_file: lists/blocked.txt:2: invalid IP/CIDR "not-an-ip"`.

> **Warning**
>
> An `ip_allow_file` with **no rules is rejected**, because an empty allow list would mean "allow everyone". An empty `ip_deny_file` is fine.

#### `user_agent_allow` and `user_agent_deny`

> **Type** `array of strings` · **Default** `[]` · **Limit** 256 rules · **Rule length** 1–256 bytes

Match the player's `User-Agent` header. Each rule is `mode:text`, where the mode is one of:

| Mode | Matches when the User-Agent... |
|---|---|
| `exact:` | equals the text exactly. |
| `prefix:` | starts with the text. |
| `substring:` | contains the text. |

Matching is case-sensitive. A rule without a mode, or with an unknown mode such as `regex:`, stops startup.

```toml
user_agent_allow = ["prefix:RadioPlayer/"]
user_agent_deny = ["substring:unsupported-build"]
```

> **Note**
>
> User-Agent is chosen by the client and trivially faked. Use it for compatibility and convenience, not security.

#### `countries_allow` and `countries_deny`

> **Type** `array of strings` · **Default** `[]` · **Limit** 249 codes

Two-letter ISO 3166-1 country codes (and `XK` for Kosovo). Lowercase is accepted and normalised. `countries_deny` refuses listeners in those countries; `countries_allow`, when non-empty, admits only those countries. Addresses whose country cannot be determined, such as local ones, pass a deny-only policy but fail an allow list.

#### `geoip_database`

> **Type** `string` (path) · **Default** the built-in database · **Max size** 128 MiB

Country lookups use a database embedded in Quikcast, so country rules work with no setup. Set this to use your own MaxMind-format country database instead, for example `"/etc/quikcast/GeoLite2-Country.mmdb"`. If you set it, it is opened and validated at startup even when no country rules are active, and re-opened on every reload. Quikcast never downloads or updates databases.

#### `asns_allow` and `asns_deny`

> **Type** `array of integers` · **Default** `[]` · **Limit** 256 each · **Uses** the bundled ASN database or `asn_database`

Autonomous system numbers, which identify the network an address belongs to. Use `asns_deny` to refuse hosting providers, proxies and scrapers by network instead of listing every range. `asns_deny` refuses listeners in those networks; `asns_allow`, when non-empty, admits only those. An address the database does not know, or a private one, passes a deny-only policy but fails an allow list. A damaged database refuses every listener rather than silently lifting the rule. With no `asn_database`, a `geoip_database` that also holds ASN records serves both; otherwise the bundled database is used. `0` is reserved and rejected.

```toml
[access]
asn_database = "/etc/quikcast/GeoLite2-ASN.mmdb"  # optional; the bundled database is used if omitted
asns_deny = [16509, 14061]
```

#### `asn_database`

> **Type** `string` (path) · **Default** bundled database · **Max size** 128 MiB · **Global table only**

A MaxMind-format ASN database, such as GeoLite2-ASN, with `autonomous_system_number` records. When omitted, Quikcast uses the [ip-location-db](https://github.com/sapics/ip-location-db) `origin-asn` snapshot (PDDL 1.0) embedded in the binary, which covers IPv4 and IPv6 and is refreshed with each release. A file you set is opened and validated at startup and re-opened on every reload.

#### `listeners_per_ip`

> **Type** `integer` · **Default** `0` (no limit) · **Range** 0–1,000,000

The most simultaneous listeners one address may hold. Set in `[access]`, it counts across all mounts; set in `[mounts.access]`, it counts on that mount only, and both apply. A listener over the limit gets `429 Too Many Requests` and the `listener_per_ip_rejected_total` counter rises. IPv6 listeners share one budget per /64. The count follows the real listener address, so set `trusted_proxies` behind a proxy or every listener will look like one address. The limit applies to continuous streams; HLS listeners are estimated, not connected, so it does not apply to them.

```toml
[access]
listeners_per_ip = 4

[[mounts]]
path = "/members.mp3"
secret_file = "secrets/members-source"

[mounts.access]
listeners_per_ip = 1
```

### `[sources]`

Lets encoders connect to paths you did **not** list under `[[mounts]]`. The mount is created when the encoder connects and disappears when its last listener leaves. Nothing is saved to the config. Listed mounts always win over dynamic ones.

```toml
[sources]
allow_dynamic_mounts = true
username = "source"
secret_file = "secrets/dynamic-source"

[sources.defaults]
name = "Quikcast Stream"
genre = "Various"
public = false
```

Even with `allow_dynamic_mounts = false`, setting credentials here makes every `[[mounts]]` that omits its own secret inherit them. A server with global credentials may have no `[[mounts]]` at all.

#### `allow_dynamic_mounts`

> **Type** `boolean` · **Default** `false` · **Applies** reload

When `true`, a correctly authenticated encoder may create a new mount just by connecting to a free path. It requires the credentials below, and the retained-audio budget must have room for at least one more stream.

#### `username` and `secret_file` / `secret`

> **Type** `string` · **Default** username `"source"` · **Applies** reload

The shared encoder credential for dynamic mounts and for configured mounts that have none of their own. Set exactly one of `secret_file` or `secret`.

#### `[sources.defaults]`

Descriptive station metadata used when an encoder sends none. An encoder's own `ice-name`, `ice-description`, `ice-genre`, `ice-url` and `ice-public` headers always win. These fields describe the station only; they cannot change limits, security or routing.

| Key | Type | Meaning |
|---|---|---|
| `name` | string | The station name shown to players. |
| `description` | string | A short description. |
| `genre` | string | The genre. |
| `url` | string | The station's website. |
| `public` | boolean | Whether the stream may be listed publicly. |

### `[[relays]]`

A **relay** pulls an existing internet stream and republishes it on one of your mounts. Use it to rebroadcast another station, build an edge server, or run a backup feed.

You can also write `[[relay]]`; use one spelling per file. The target mount must exist under `[[mounts]]`. Once a mount has a relay, the relay owns it: an encoder cannot connect there, even while the relay is stopped. You can have up to 64 relays, one per mount. Relay settings apply on reload; changing any of them restarts that relay.

```toml
[[mounts]]
path = "/remote.mp3"
secret_file = "secrets/remote-local"

[[relays]]
mount = "/remote.mp3"
upstreams = [
  { url = "https://primary.example/live" },
  { url = "https://backup.example/live" },
]
```

#### `mount`

> **Type** `string` · **Default** none (required)

The local mount the relay feeds. It is the path your listeners use, not part of the upstream URL.

#### `url`, `urls` and `upstreams`

> **Type** `string`, `array of strings`, or `array of tables` · **Default** none · **Choose exactly one**

Where to pull audio from. Use **one** of the three forms:

- `url = "https://origin.example/live"` is a single upstream.
- `urls = ["https://a.example/live", "https://b.example/live"]` lists 1–8 upstreams that share the relay's credentials.
- `upstreams = [{ url = "..." }, ...]` lists 1–8 upstreams where each may have its own credentials.

All forms need absolute `http://` or `https://` URLs of at most 2,048 bytes. Queries are fine. Fragments, `user:pass@` in the URL, whitespace and other schemes are rejected. Pointing a relay at this same server is rejected. Duplicates are rejected.

The upstream may be a plain stream (MP3, AAC, Ogg, FLAC), an old SHOUTcast server, or an audio-only **HLS playlist** (experimental and not reliable; see "Relay another station").

The first entry is the **primary**. If it fails, Quikcast tries the next entry immediately. After the last entry fails, it waits for the backoff delay and starts again at the primary. A working backup stays selected until it fails: there is no automatic return to the primary.

> **Tip**
>
> New configurations should prefer `upstreams`, since it can express everything `url` and `urls` can. The older forms still work.

```toml
upstreams = [
  { url = "https://primary.example/live", username = "primary-user", secret_file = "secrets/primary-password" },
  { url = "https://backup.example/live" },
]
```

#### `username` and `secret_file`

> **Type** `string` · **Default** none (anonymous) · **Password** 1–512 ASCII graphic bytes

Basic-auth credentials sent to the upstream. Set both or neither. There is no inline `secret` field for relays. With `upstreams`, these act as the **default** for entries that set neither of their own fields; an entry with its own `username` and `secret_file` overrides them.

#### `enabled`

> **Type** `boolean` · **Default** `true`

Whether the relay starts with the server. `false` starts it stopped (the mount still stays reserved); you can start it later through the management API.

#### `charset`

> **Type** `string` · **Default** UTF-8 · **Applies** reload (restarts the relay)

The character set of the titles in the upstream's in-stream metadata. Many older stations send Latin-1 (`ISO-8859-1`) or `windows-1252` titles. With the default, a title that is not valid UTF-8 is rejected and counted under `metadata_rejections_total`; with `charset` set, it is converted to UTF-8 so listeners see the right accented characters. See `charset` on mounts for supported names. It does not affect audio.

#### `on_demand`

> **Type** `boolean` · **Default** `false`

Connect to the upstream only while someone is listening. The relay starts idle, the first listener wakes it (waiting up to `wake_wait_ms`), and it disconnects after `idle_timeout_ms` with no listeners. While idle it reports `state` `stopped` with `stopped_reason` `idle`. How it behaves, including fallback and the management API, is in on-demand relays (see "Relay another station").

#### `idle_timeout_ms`

> **Type** `integer` · **Default** `30000` · **Range** 1–3,600,000 · **Applies** `on_demand` only

How long an on-demand relay stays connected with no listeners before it disconnects. It must not be shorter than `wake_wait_ms`.

#### `wake_wait_ms`

> **Type** `integer` · **Default** `8000` · **Range** 0–60,000 · **Applies** `on_demand` only

How long the first listener waits for the relay to connect and deliver audio. If the origin is not ready in time, the listener gets the usual "not found" response and can retry.

#### `max_redirects`

> **Type** `integer` · **Default** `0` · **Range** 0–8

How many upstream redirects (301, 302, 303, 307, 308) to follow per attempt. `0` treats any redirect as a failure. Credentials are never sent to a different host than the one you configured: they are dropped at the first change of scheme, host or port.

#### `hls_variant`

> **Type** `string` · **Default** `"highest"` · **Values** `"highest"`, `"lowest"` · **Applies** reload (restarts the relay)

When a relay's upstream is an HLS **master playlist** offering several bitrates, this chooses which audio-only variant to follow. `"highest"` gives the best quality; `"lowest"` uses the least bandwidth. Variants that contain video are never chosen. It has no effect on non-HLS upstreams. HLS relaying is experimental; see the warning (see "Relay another station").

```toml
[[relays]]
mount = "/hls-station.aac"
url = "https://stream.example/live/master.m3u8"
hls_variant = "lowest"
max_redirects = 3
```

#### Timeouts and retry

All values are milliseconds from 1 to 3,600,000 unless stated.

| Key | Default | Meaning |
|---|---|---|
| `connect_timeout_ms` | `10000` | One overall deadline for DNS, TCP connect and TLS. |
| `header_timeout_ms` | `5000` | How long the upstream may take to send response headers. |
| `audio_timeout_ms` | `10000` | How long without new audio before the attempt is abandoned. For HLS upstreams the limit is the longer of this and three segment lengths, and it also bounds each playlist or segment download. |
| `initial_backoff_ms` | `1000` | First wait after every upstream failed. Must not exceed `max_backoff_ms`. |
| `max_backoff_ms` | `60000` | Longest wait between retry cycles. |
| `stable_connection_ms` | `30000` | A connection that lasts this long resets the backoff. |
| `jitter_percent` | `20` | Random variation applied to waits, `0` to `50`. |

#### Network safety

These rules have no settings. The guide explains them under Safety rules (see "Relay another station").

- Redirects and HLS references from a **public** upstream may only lead to other public addresses. Targets on loopback, private, link-local or reserved ranges, and `0.0.0.0`/`::`, are refused (`destination_not_allowed`). Upstreams you configure on a private address are trusted, and so is anything they redirect to.
- Outbound HTTPS is always verified against the bundled public certificate roots. There is no option to disable verification, add a private CA or use client certificates.

### `[primary]`

Share the list of this server's streams with replica servers (see "Primary and replica servers"). Omit the table to keep the endpoint off.

```toml
[primary]
username = "replica"
secret_file = "secrets/replica-password"
share = ["/radio.mp3"]
redirect_after = 200
```

#### `username` and `secret` / `secret_file`

> **Type** `string` · **Default** username `"replica"` · **Password** 16–512 bytes · **Applies** reload

The login a replica must present to read the stream list at `GET /api/streams` on the public listener. Configure exactly one of `secret` or `secret_file` (prefer the file). Use a password that is different from every encoder, management and console password.

#### `share`

> **Type** `array of strings` · **Default** every public mount · **Applies** reload

Only list these mounts. Mounts protected by signed links, and mounts that are copies made by a replica, are never listed.

#### `redirect_after`

> **Type** `integer` · **Default** none (never redirect) · **Applies** reload

Send new listeners to replicas (see "Primary and replica servers") once a mount already has this many. `0` redirects every listener. A listener the primary has no room for is redirected whatever the number. Nothing is redirected until a replica has announced itself with `public_url`.

### `[replica]`

Copy the streams of another Quikcast server. See "Primary and replica servers". A server with a `[replica]` section may have no `[[mounts]]` of its own, and it must be started from a config file, because it applies stream changes by reloading it.

```toml
[replica]
primary = "https://radio.example.com"
username = "replica"
secret_file = "secrets/primary-password"
refresh_secs = 30
on_demand = true
max_streams = 16
only = ["/radio.mp3"]
public_url = "https://eu.example.com"
```

#### `primary`

> **Type** `string` · **Required** · **Applies** reload

The primary server's address, such as `https://radio.example.com` or `http://10.0.0.5:8000`. It must have no path. Streams are relayed from the same address at their original paths.

#### `username` and `secret` / `secret_file`

> **Type** `string` · **Default** username `"replica"` · **Applies** reload

The login for the primary's `[primary]` section. Configure exactly one of `secret` or `secret_file`. 1–512 printable bytes, no spaces.

#### `refresh_secs`

> **Type** `integer` · **Default** `30` · **Range** 5–3600 · **Applies** reload

How often the primary's stream list is checked. A failed check keeps the current streams.

#### `on_demand`

> **Type** `boolean` · **Default** `true` · **Applies** reload

Whether replicated relays connect to the primary only while someone is listening. See `on_demand` on relays.

#### `max_streams`

> **Type** `integer` · **Default** `16` · **Range** 1–48 · **Applies** reload

The most streams to copy, before the global limits of `limits.max_mounts` mounts and 64 relays and `limits.relay_allocation_budget`. Streams beyond the limit are skipped with a warning, in alphabetical order.

#### `only`

> **Type** `array of strings` · **Default** all listed streams · **Applies** reload

Copy only these paths.

#### `public_url`

> **Type** `string` · **Default** none · **Applies** reload

This replica's own public address, such as `https://eu.example.com`, with no path. When set, the replica tells the primary its address and the streams it carries, so the primary can redirect listeners (see "Primary and replica servers") to it. Listeners must be able to reach this address.

### `[hls]`

A separate subsystem that serves **HLS** (`.m3u8` playlists with segment files) to browsers and mobile players. Quikcast does not encode: your own tool, such as FFmpeg, pushes finished, correctly packaged segments to the private ingest API, and Quikcast stores and serves them from memory. HLS is not derived from your normal mounts.

Ingested content is held in memory and lost on restart. Alternatively, `directory` serves HLS files that another program writes to disk. See What can be reloaded for what applies on reload.

```toml
[hls]
username = "hls"
secret_file = "secrets/hls-ingest"
cors_origin = "https://player.example.com"
```

See "HLS ingest API" for the ingest API and supported formats.

#### `username`

> **Type** `string` · **Default** `"hls"`

The ingest username (Basic authentication).

#### `secret_file` / `secret`

> **Type** `string` · **Default** none · **Password** 16–512 bytes

The ingest password. Set exactly one. It must differ from every mount password. When `directory` is set, both may be left out; the ingest API is then disabled.

#### `directory`

> **Type** `string` · **Default** none · **Applies** restart

A directory whose subdirectories are served as HLS streams at `/hls/<subdirectory>/...`. A relative path is relative to the configuration file. The directory must exist and be readable at startup (`--check` verifies it). Names must be 1–64 letters, digits, `_` or `-`.

Only regular files ending in `.m3u8`, `.ts`, `.m4s`, `.mp4`, `.aac` or `.mp3` are served, up to 16 MiB each, at most four levels below the stream. Everything else returns `404`. Which files are served, caching, naming and precedence over ingested streams are explained in Serve HLS from a directory (see "HLS for browsers and apps").

```toml
[hls]
directory = "/var/lib/radio/hls"
```

#### `directory_listener_window_secs`

> **Type** `integer` · **Default** `60` · **Range** 5–3600 · **Applies** restart

Only used with `directory`. A client IP counts as an active listener of a directory stream if it fetched a playlist or segment within this many seconds. See "HLS for browsers and apps".

#### `directory_session_timeout_secs`

> **Type** `integer` · **Default** `30` · **Range** 5–3600 · **Applies** restart

Only used with `directory`. A listener session of a directory stream is active if its client requested a playlist or segment within this many seconds. Session fields and limits are in `GET /api/hls/{stream}/listeners` (see "Management API").

#### `cors_origin`

> **Type** `string` · **Default** none (CORS off) · **Max length** 256 bytes

The website allowed to play your HLS from a browser. Use `"*"` or exactly one origin such as `"https://player.example.com"` (no path, no trailing slash, no list). Without it, browsers on other sites cannot fetch your playlists, although non-browser players are unaffected. Preflight requests allow `Range`, `If-None-Match` and `If-Range`.

#### Capacity settings

| Key | Default | Range | Meaning |
|---|---|---|---|
| `max_streams` | `16` | 1–64 | Most HLS streams. |
| `renditions_per_stream` | `8` | 1–16 | Most quality levels per stream. |
| `max_renditions` | `64` | 1–128 | Most quality levels overall. |
| `max_segment_bytes` | `2097152` | 188–16,777,216 | Largest single uploaded segment. A safety ceiling, not a target size. |
| `max_segments` | `1024` | 16–4,096 | Segment slots per rendition. |
| `max_uploads` | `4` | 1–16 | Uploads accepted at the same time. |
| `rendition_budget` | `134217728` | up to `allocation_budget` | Memory reserved per rendition. |
| `allocation_budget` | `536870912` | up to 4 GiB | Total memory for HLS. |

#### `[hls.listener_auth."/hls/NAME"]`

Protect one HLS stream with signed URLs. The key is the stream's public path, `/hls/` followed by 1–64 letters, digits, `_` or `-`. A stream with no entry is public; up to 64 entries are allowed. One signature covers the playlists and every segment of that stream. The fields are the same as `[mounts.listener_auth]`.

```toml
[hls.listener_auth."/hls/private"]
type = "signed_url"
secret_file = "secrets/hls-private-key"
```

### Putting it together

A small station with HTTPS, a private console, a country allow list and a backup feed:

```toml
listen = "0.0.0.0:8443"
admin_listen = "127.0.0.1:9090"

[tls]
cert_file = "secrets/tls/fullchain.pem"
key_file = "secrets/tls/privkey.pem"

[management]
token_file = "secrets/management-token"

[ui]
enabled = true
username = "admin"
password_file = "secrets/ui-password"

[access]
countries_allow = ["GH", "NG"]
ip_deny_file = "lists/blocked.txt"

[[mounts]]
path = "/radio.mp3"
fallback = "/backup.mp3"
secret_file = "secrets/radio-source"

[[mounts]]
path = "/backup.mp3"
secret_file = "secrets/backup-local"

[[relays]]
mount = "/backup.mp3"
upstreams = [{ url = "https://backup.example/live" }]
```

### What can be reloaded

Send SIGHUP to apply changes without dropping connected listeners or encoders:

```sh
kill -HUP "$(pidof quikcast)"
```

| Applies on reload | Needs a restart |
|---|---|
| `[tls]` certificate and key files | `listen`, `admin_listen`, `log_filter` |
| `[trusted_proxies]` (all keys) | Enabling or disabling `[tls]` |
| `[management]` (except `allow_remote`), `[ui]` | `management.allow_remote`, every `[limits]` setting |
| `[access]` and every list file | `listener_limit` of an existing mount |
| Mount credentials, `fallback`, `listener_auth`, `access`, `source_access` | HLS capacity settings and `directory` (while `[hls]` is on) |
| `[sources]` (credentials, dynamic mounts, defaults) | |
| `[[relays]]` (a changed relay restarts) | |
| `[hls]` credentials, `cors_origin`, `listener_auth` | |
| Adding or removing the `[hls]` table (removing it drops ingested HLS streams from memory) | |
| Adding or removing a `[[mounts]]` entry (removal disconnects its encoder and listeners) | |

A reload is all or nothing. Existing listeners and encoders stay connected, and rotated credentials affect new connections and updates. For the full behaviour, see "Production checklist".

## Command line and signals

### Usage

```sh
quikcast [--config PATH] [--check]
```

| Option | Meaning |
|---|---|
| `--config PATH` | The configuration file to load. If omitted, the `QUIKCAST_CONFIG` environment variable is used. There is no default location. |
| `--check` | Load and fully validate the configuration, then exit without starting. Also accepted as the word `check-config`. |
| `-h`, `--help` | Show help and exit. |
| `-V`, `--version` | Show the version and exit. |

`--check` does everything startup does except open ports: it parses the file, reads every secret, list, certificate and database it mentions, and prepares all rules. It prints `<file>: configuration ok` and exits `0`, or prints the problem to standard error and exits `1`.

```sh
quikcast --config /etc/quikcast/quikcast.toml --check
```

### Environment variables

| Variable | Meaning |
|---|---|
| `QUIKCAST_CONFIG` | Path to the configuration file, used when `--config` is not given. `--config` wins if both are set. |
| `QUIKCAST_LOG` | A [tracing filter](https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html) such as `quikcast=debug`. Overrides `log_filter` from the config. |

### Signals (Linux and macOS)

| Signal | What happens |
|---|---|
| `SIGHUP` | Reload the configuration. All or nothing: if anything is invalid the old configuration stays in force and the reason is logged. See "Configuration reference". |
| `SIGTERM`, `SIGINT` (Ctrl+C) | Graceful shutdown. Listeners stop accepting, connections are given `shutdown_timeout_ms` to finish, and then anything left is closed. |

On Windows only Ctrl+C is available, and the configuration cannot be reloaded without restarting.

### Exit codes

| Code | Meaning |
|---|---|
| `0` | Success: a clean shutdown, or `--check` passed. |
| `1` | A configuration, startup or runtime error. The message is printed to standard error. |

### Standard output

Logs go to standard output. It must be a terminal, a pipe or a socket (such as the systemd journal), not a regular file. See "Monitoring".

## Management API

The unversioned `/api` surface runs on `admin_listen`, which binds loopback by default. For a remote management client either forward it through a private proxy, or opt in with `[management] allow_remote = true` (see Remote access). Continuous audio, source authentication, metadata updates, public HLS, HLS ingest, health, and metrics retain their existing independent routes and credentials.

`GET /api/metadata?mount=...&mode=updinfo&song=...` is a separate source operation on the streaming listener (`listen`). It uses the requested mount's source credentials via HTTP Basic authentication and returns the ICY XML response. It does not use the management bearer token. For Icecast-compatible encoders such as Liquidsoap, BUTT and Mixxx, the same operation is also served at `/admin/metadata` and the legacy `/admin/metadata.xsl` on the streaming listener, with identical authentication and behavior; every other `/admin/...` path stays unrouted.

### Configuration and authentication

```toml
[trusted_proxies] # optional
ips = ["127.0.0.1", "10.20.0.0/16"]
providers = [] # Or ["cloudflare"] for direct Cloudflare peers.

[management]
token_file = "secrets/management-token"
# Alternatively: token = "a-generated-machine-secret"

[[mounts]]
path = "/radio.mp3"
username = "source"
secret_file = "secrets/radio-source"
listener_limit = 500
```

Configure exactly one `token` or `token_file`. Relative secret-file paths resolve against the configuration directory. Generate a dedicated token, for example:

```sh
mkdir -p config/secrets
umask 077
openssl rand -hex 32 > config/secrets/management-token
```

The token must contain 32–512 printable ASCII bytes without spaces. Use a generated high-entropy secret; length validation cannot establish entropy. A secret file may end in LF or CRLF. Loading is synchronous, bounded, and fail-fast before binding. Secrets have no debug representation and never appear in responses or logs. Do not reuse a source or HLS producer secret as a management token.

Every endpoint below requires `Authorization: Bearer <token>`; the scheme is case-insensitive. Missing, incorrect, malformed, or oversized bearer credentials receive 401 `unauthorized`, with a Bearer challenge. Comparison uses fixed-size padded arrays and constant-time length/content comparison. At most 519 authorization bytes are accepted. The request parser additionally caps all headers at 16 KiB and 64 fields; duplicate Authorization fields or invalid HTTP framing are rejected by the transport parser. Transport failures before routing remain the existing finite HTTP errors (400, 408, 417, or 431), rather than API JSON.

If `[management]` is omitted, `/api` fails closed with 401 for every request. Health and metrics remain lightweight, loopback-only operational endpoints without the management token. Listener and source routes never require this token.

Examples assume a securely supplied environment variable:

```sh
curl -H "Authorization: Bearer $QUIKCAST_TOKEN" http://127.0.0.1:9090/api/server
```

All management requests have no body. Omit Content-Length or send `Content-Length: 0`. Nonempty/chunked bodies and Expect requests receive 400 `invalid_request`. Queries reject unknown and duplicate parameters. JSON responses use `application/json` and `Cache-Control: no-store`. Connections close after each response. Successful DELETE returns 204 with no body. Unsupported methods receive 405 `method_not_allowed` and an Allow header.

### Remote access

A remote client such as a hosting panel needs only `GET /api/stats`, `GET /api/mounts`, `GET /api/listeners?mount=...&limit=...&after=...` and `DELETE /api/listeners/{id}`. To allow it, set `[management] allow_remote = true`. The settings, the protections Quikcast enforces (token length, failed-authentication throttling, `allowed_ips`, `tls`) and the security caveats are all in Remote management (see "Configuration reference").

### Using the examples

Set the administration URL and load the token from your management token file. Replace the path with the actual `token_file` path from your configuration:

```sh
export QUIKCAST_ADMIN_URL='http://127.0.0.1:9090'
export QUIKCAST_TOKEN="$(cat config/secrets/management-token)"
```

Requests below use `curl -i` to show the HTTP status and headers. Management requests send no body. Response bodies are formatted for readability; example timestamps, counters, limits, IDs, and generations are illustrative, not a capture of your running server. Examples are independent snapshots, not a sequence to run against production. Use IDs, generations, and revisions returned by your own inspection requests.

Successful JSON responses include `Content-Type: application/json` and `Cache-Control: no-store`. A successful 204 response has no JSON body. HLS inspection examples require HLS to be enabled and a producer to have created the illustrated stream and rendition.

### Endpoint inventory

All GETs are observational and have no lifecycle side effects. All paths are case-sensitive. For continuous mounts, append the complete canonical mount path to `/api/mounts` or `/api/sources`: `/nested/radio.mp3` becomes `/api/mounts/nested/radio.mp3`. Separate source resources and a filtered listener collection avoid ambiguity between nested mount paths and reserved suffixes.

#### GET /api/server

No parameters. 200 returns `ServerInfo`: `name` (Quikcast), package `version`, `started_at`, `uptime_ms`, runtime `state` (`accepting`, `draining`, or `shutting_down`), `drain_started_at`, `drain_age_ms`, `config_generation`, `config_committed_at`, `capabilities`, and `limits` (`max_connections`, `max_listeners`, `max_handshakes`). Startup is runtime construction; binding normally immediately follows it. No build paths, implementation details, configuration secrets, or task identifiers are exposed.

**Example request**

```sh
curl -i -H "Authorization: Bearer $QUIKCAST_TOKEN" \
  "$QUIKCAST_ADMIN_URL/api/server"
```

**Example response: 200 OK**

```json
{
  "name": "Quikcast",
  "version": "0.1.0",
  "started_at": 1791460800000,
  "uptime_ms": 60000,
  "config_generation": 1,
  "config_committed_at": 1791460800000,
  "state": "accepting",
  "drain_started_at": null,
  "drain_age_ms": null,
  "capabilities": [
    "mp3",
    "aac-adts",
    "ogg-vorbis",
    "ogg-opus",
    "ogg-flac",
    "flac",
    "icy",
    "management",
    "continuous-relays",
    "hls-mpeg-ts",
    "hls-mpeg-ts-aac",
    "hls-packed-aac",
    "hls-packed-mp3",
    "hls-fmp4-aac",
    "hls-fmp4-flac"
  ],
  "limits": {
    "max_connections": 256,
    "max_listeners": 128,
    "max_handshakes": 32
  }
}
```

Configuration generation starts at 1 and increments only after successful atomic reload. `config_committed_at` is Unix epoch milliseconds. These fields and policy inspection use the same admission snapshot as authentication for that API request. See "Production checklist" for field classification, failure behavior, secret rotation and relay handoff. There is no management reload endpoint. The `atomic-config-reload` capability describes snapshot support; the executable provides its Unix signal trigger.

#### POST /api/server/drain

Requires the same management Bearer token. No query parameters or body. 200 returns the same `ServerInfo` model as GET `/api/server`, with `state: "draining"`, a Unix-millisecond `drain_started_at`, and monotonic `drain_age_ms`. These fields are null before an explicit drain. Repeated/concurrent POSTs are idempotent and preserve the original start time. Invalid/missing authentication returns 401 `unauthorized`; body/query validation failures return 400 `invalid_request`; other methods return 405 with `Allow: POST`.

Draining is one-way until process restart or shutdown. New continuous source/listener admissions receive HTTP 503 with `Server draining\n` (typed domain error `ServerDraining`, native error code `server_draining` where a native operation rejects admission). Existing source/listener leases continue; administrative disconnect, metadata update, management inspection, health, metrics, and public HLS reads remain available. Continuous HEAD requests inspect headers and do not admit a listener, so remain available.

Continuous admission has an early check before generation/listener reservations and a final atomic accepting observation immediately before publishing ownership. That successful final observation is the admission boundary. If drain is authoritative before it, reservations unwind normally and no record/generation/counter is committed. If the final observation wins, that operation may finish committing and starting after the drain response. TCP connection acceptance, partial headers, authentication, and reservation acquisition alone do not establish admission. Network/handshake limits remain necessary to serve management, health, and HLS, and are not disabled by drain.

**HLS option A:** after producer authentication, every non-GET producer request checks admission before upload permits, body budgets, or mutations. New stream/rendition creation, segment uploads, publication, master changes, end, and delete are all rejected with HTTP 503. Requests already admitted before drain may finish, including uploading and accepting a segment afterward. Subsequent requests from that same producer are rejected. Producer GET inspection and all public HLS playback remain available. Published playlists stay immutable, and existing retention/expiry rules continue. No active-producer-session exception is introduced.

Drain does not cancel connections, close rings, retire HLS, schedule a shutdown timer, or wait for zero activity. SIGTERM/Ctrl+C/the shutdown token still owns the existing graceful close/join/deadline behavior. During shutdown, server state is `shutting_down`, which takes precedence over drain state.

**Example request**

```sh
curl -i -X POST -H "Authorization: Bearer $QUIKCAST_TOKEN" \
  "$QUIKCAST_ADMIN_URL/api/server/drain"
```

**Example response: 200 OK**

The body is the full `ServerInfo` from `GET /api/server`. Only these fields differ:

```json
{
  "state": "draining",
  "drain_started_at": 1791460860000,
  "drain_age_ms": 0
}
```

Use this only when you intend to drain the server. To verify the resulting state, repeat GET `/api/server`; repeated drain requests retain the original `drain_started_at`.

Drain observability uses the existing `ready` gauge (0 during drain), `/api/server` state/start/age, a fixed `drain_rejections_total` Prometheus counter, and `/api/stats.drain_rejections`. Rejected source/listener/HLS producer requests also increment existing admission rejection accounting. Health and inspection polls do not. A structured log records the first transition only; repeated POSTs do not restart its clock or restore acceptance.

#### GET /api/stats

No parameters. 200 returns `Stats`: `uptime_ms`, `configured_mounts`, `active_mounts`, `active_sources`, `active_listeners` (mount listeners plus estimated directory HLS listeners), `active_hls_listeners` (the estimated part alone), `active_connections`, `active_handshakes`, `source_connections_total`, `listener_connections_total`, `bytes_ingested_total`, `bytes_served_total`, `slow_consumer_disconnects`, `authentication_failures`, `rejected_connections`, `drain_rejections`, `hls_requests`, `hls_segments_served`, `hls_publication_conflicts`, `hls_active_uploads`, a typed `relays` summary, and a typed `hls` summary.

The HLS summary includes `stream_count`, `rendition_count`, `retained_bytes`, `allocation_reserved_bytes`, `allocation_budget`, and `max_uploads`. Disabled HLS reports zero values. Registry counts include active, ended, and deleted objects still retained for grace/ownership cleanup. Retained bytes count stored segment payloads; reservation bytes additionally include backing capacity, playlists, bookkeeping, uploads, and response-held allocations. The two quantities deliberately differ.

Counters are process-local. Active mounts count streaming source leases, rather than configured mounts or HLS streams. Active connections include the administration request itself. Active handshakes count connections reading their bounded request preface. Rejected connections count admission/source-conflict/authentication/drain rejections, not every malformed request. Global ingested bytes count accepted audio ring publication. Served bytes include actual audio/ICY/HLS transport body writes, excluding response headers. HLS segments served counts successful full (200) and partial (206) GET responses scheduled for segment delivery, excluding HEAD, 304, and rejected range requests; it does not certify that a remote client consumed the complete segment.

Statistics are an observational sample, not an atomic transaction across every connection. Continuous counters use atomics. HLS summaries traverse the bounded stream/rendition registries and use maintained retained-byte counters; they do not clone segments or scan each segment payload/index. Metrics remain separate at `/metrics`.

**Example request**

```sh
curl -i -H "Authorization: Bearer $QUIKCAST_TOKEN" \
  "$QUIKCAST_ADMIN_URL/api/stats"
```

**Example response: 200 OK**

```json
{
  "uptime_ms": 60000,
  "configured_mounts": 2,
  "active_mounts": 1,
  "active_sources": 1,
  "active_listeners": 1,
  "active_hls_listeners": 0,
  "active_connections": 3,
  "active_handshakes": 0,
  "source_connections_total": 7,
  "listener_connections_total": 12,
  "bytes_ingested_total": 944000,
  "bytes_served_total": 480000,
  "slow_consumer_disconnects": 0,
  "authentication_failures": 0,
  "rejected_connections": 0,
  "drain_rejections": 0,
  "relays": {
    "configured": 1,
    "connecting": 0,
    "connected": 0,
    "backoff": 0,
    "stopped": 1,
    "attempts_total": 0,
    "connections_total": 0,
    "reconnects_total": 0,
    "failures_total": 0,
    "response_body_bytes_total": 0,
    "audio_bytes_total": 0,
    "metadata_rejections_total": 0,
    "allocation_reservation_bytes": 2097152
  },
  "hls": {
    "stream_count": 0,
    "rendition_count": 0,
    "retained_bytes": 0,
    "allocation_reserved_bytes": 0,
    "allocation_budget": 536870912,
    "max_uploads": 4
  },
  "hls_requests": 0,
  "hls_segments_served": 0,
  "hls_publication_conflicts": 0,
  "hls_active_uploads": 0
}
```

#### GET /api/mounts

No parameters. 200 returns an array of `MountInfo`, sorted lexicographically by canonical path. Startup restricts configuration to at most 64 mounts, so this list is bounded.

Continuous mount inspection includes a boolean `dynamic`: configured mounts report `false`; ephemeral source-created mounts report `true`. Dynamic mounts participate in the existing mount, source and listener inspection/disconnect endpoints and disappear after their source and listeners close. Credentials are never included.

**Example request**

```sh
curl -i -H "Authorization: Bearer $QUIKCAST_TOKEN" \
  "$QUIKCAST_ADMIN_URL/api/mounts"
```

**Example response: 200 OK**

```json
[
  {
    "path": "/radio.mp3",
    "source": {
      "generation": 7,
      "connected_at": 1791460801000,
      "age_ms": 59000,
      "connection": {
        "remote_address": "127.0.0.1:53124",
        "client_ip": "127.0.0.1",
        "user_agent": "Example encoder"
      },
      "content_type": "audio/mpeg",
      "format": "mp3",
      "codec": "mp3",
      "source_metadata": {
        "name": "Example Radio",
        "description": "Live music",
        "genre": "Various",
        "url": "https://radio.example.com",
        "public": false,
        "declared_bitrate_kbps": 128,
        "declared_sample_rate_hz": 44100,
        "declared_channels": 2
      },
      "track": {
        "revision": 3,
        "title": "Example Artist - Example Track"
      },
      "bytes_received": 944000,
      "state": "streaming"
    },
    "active_listeners": 1,
    "listener_limit": 64,
    "bytes_ingested": 944000,
    "bytes_served": 480000,
    "state": "accepting"
  }
]
```

#### GET /api/mounts/{mount path}

No parameters. 200 returns `MountInfo`; 404 `mount_not_found` for an unknown mount. A configured mount remains inspectable without a source.

`MountInfo` fields:

- `path`, lifecycle `state` (`accepting`, `draining`, or `closed`).
- `source`: a `SourceInfo` object, or null when no generation owns the mount.
- `active_listeners`, `listener_limit` (null means unlimited locally).
- Process-lifetime per-mount `bytes_ingested` and `bytes_served`.

Per-mount ingested bytes count encoded input submitted to the source lifecycle, including input subsequently rejected as malformed media; source `bytes_received` uses the same receive definition. This can differ from globally accepted ring bytes. Served bytes count actual listener body writes including ICY bytes.

**Example request**

```sh
curl -i -H "Authorization: Bearer $QUIKCAST_TOKEN" \
  "$QUIKCAST_ADMIN_URL/api/mounts/radio.mp3"
```

**Example response: 200 OK**

```json
{
  "path": "/radio.mp3",
  "source": {
    "generation": 7,
    "connected_at": 1791460801000,
    "age_ms": 59000,
    "connection": {
      "remote_address": "127.0.0.1:53124",
      "client_ip": "127.0.0.1",
      "user_agent": "Example encoder"
    },
    "content_type": "audio/mpeg",
    "format": "mp3",
    "codec": "mp3",
    "source_metadata": {
      "name": "Example Radio",
      "description": "Live music",
      "genre": "Various",
      "url": "https://radio.example.com",
      "public": false,
      "declared_bitrate_kbps": 128,
      "declared_sample_rate_hz": 44100,
      "declared_channels": 2
    },
    "track": {
      "revision": 3,
      "title": "Example Artist - Example Track"
    },
    "bytes_received": 944000,
    "state": "streaming"
  },
  "active_listeners": 1,
  "listener_limit": 64,
  "bytes_ingested": 944000,
  "bytes_served": 480000,
  "state": "accepting"
}
```

When the configured mount has no source, `source` is null and `active_listeners` is zero. The mount itself remains in the response.

#### GET /api/sources/{mount path}

No parameters. 200 returns a `SourceInfo` object or JSON null when disconnected. Unknown mount returns 404 `mount_not_found`.

`SourceInfo`: `generation`, `connected_at`, `age_ms`, `connection`, `content_type`, `format`, `codec`, typed `source_metadata`, typed `track`, `bytes_received`, and `state` (`connecting`, `streaming`, or `disconnecting`). Configured-mount generations are mount-local and monotonically increasing during this process. Dynamic generations use a daemon-wide monotonic sequence, so recreating a dynamic path cannot reuse an earlier generation guard.

`connection` contains `remote_address` (socket IP and port), resolved `client_ip`, and optional `user_agent` (bounded to 256 characters). `format` is `mp3`, `aac-adts`, `ogg-audio`, or `flac`. Ogg `codec` is null until the existing Ogg parser identifies Vorbis, Opus, or FLAC; chained Ogg updates the known codec. MP3/AAC codec follows the admitted content type.

`source_metadata` contains optional `name`, `description`, `genre`, `url`, `public`, `declared_bitrate_kbps`, `declared_sample_rate_hz`, and `declared_channels`. Audio properties are explicit producer declarations from existing source headers, not measurements. Unknown or malformed declarations are null. `track` contains `revision` and `title`, independently of station metadata and connection state. The initial/cleared title is an empty string. These records belong to the source generation and disappear when its lease ends.

**Example request**

```sh
curl -i -H "Authorization: Bearer $QUIKCAST_TOKEN" \
  "$QUIKCAST_ADMIN_URL/api/sources/radio.mp3"
```

**Example response: 200 OK**

```json
{
  "generation": 7,
  "connected_at": 1791460801000,
  "age_ms": 59000,
  "connection": {
    "remote_address": "127.0.0.1:53124",
    "client_ip": "127.0.0.1",
    "user_agent": "Example encoder"
  },
  "content_type": "audio/mpeg",
  "format": "mp3",
  "codec": "mp3",
  "source_metadata": {
    "name": "Example Radio",
    "description": "Live music",
    "genre": "Various",
    "url": "https://radio.example.com",
    "public": false,
    "declared_bitrate_kbps": 128,
    "declared_sample_rate_hz": 44100,
    "declared_channels": 2
  },
  "track": {
    "revision": 3,
    "title": "Example Artist - Example Track"
  },
  "bytes_received": 944000,
  "state": "streaming"
}
```

A configured mount with no connected source returns **200 OK** with the JSON body `null`, rather than 404. Native FLAC additionally exposes parsed `sample_rate_hz`, `channels`, and `bits_per_sample`; these fields are omitted when parsed native FLAC properties are unavailable.

#### DELETE /api/sources/{mount path}

Optional `generation=<unsigned 64-bit integer>` query. No body. 204 requests cancellation of the resolved generation through its normal source lifecycle. 404 `mount_not_found`; 409 `source_not_connected` if no source; 409 `conflict` if the requested or resolved generation is stale; 400 `invalid_request` for invalid parameters.

The operation first obtains an owned target, then validates exact generation identity under mount admission before cancelling it. A delayed action for generation N cannot affect N+1. Supplying `generation` additionally prevents an operator acting on stale previously inspected state. Without it, the action targets the generation active when this request resolves it.

Cancellation interrupts raw/framed source reads, closes its ring and triggers compatible continuous listeners to resolve their configured fallback (other listeners disconnect), and lets the owning source lease perform normal accounting and metadata cleanup. It does not release admission early or replace a source. 204 means cancellation accepted, not joined cleanup completed. Duplicate requests may receive 204 while the same generation is disconnecting, then 409 after cleanup. Without an explicit generation, a later separate request can intentionally target a newly resolved source. Administrative disconnects record a typed reason and structured mutation log.

**Example request**

```sh
curl -i -X DELETE -H "Authorization: Bearer $QUIKCAST_TOKEN" \
  "$QUIKCAST_ADMIN_URL/api/sources/radio.mp3?generation=7"
```

**Example response: 204 No Content**

```http
HTTP/1.1 204 No Content
Cache-Control: no-store
```

There is no response body.

#### GET /api/listeners?mount={canonical path}&limit={n}&after={id}

`mount` is required and must exactly name a configured mount. `limit` defaults to 100 and must be 1–200. `after` is an optional opaque listener ID. Use curl's query encoding:

200 returns `ListenerPage`: `items` (at most limit `ListenerInfo` records) and `next_after` (null at the end, otherwise pass it unchanged). 400 `invalid_pagination` for missing/invalid/duplicate/unknown parameters; 404 `mount_not_found` for an unknown mount.

Ordering is ascending lexical listener ID, with the cursor strictly exclusive. IDs are random, so this is not chronological order. Pagination is a live view: listeners that leave disappear; additions sorting before an already passed cursor can be missed until a fresh listing. A cursor need not remain active. Each page locks only that mount's registry, visits at most limit+1 entries, and constructs only the requested page. There is no global listener list clone or persistent history.

**Example request**

```sh
curl -i -G -H "Authorization: Bearer $QUIKCAST_TOKEN" \
  --data-urlencode "mount=/radio.mp3" \
  --data-urlencode "limit=1" \
  "$QUIKCAST_ADMIN_URL/api/listeners"
```

**Example response: 200 OK**

```json
{
  "items": [
    {
      "id": "0123456789abcdef0123456789abcdef",
      "mount": "/radio.mp3",
      "generation": 7,
      "connected_at": 1791460830000,
      "duration_ms": 30000,
      "connection": {
        "remote_address": "127.0.0.1:54210",
        "client_ip": "127.0.0.1",
        "user_agent": "Example player"
      },
      "bytes_sent": 480000,
      "icy_metadata": false,
      "state": "connected"
    }
  ],
  "next_after": "0123456789abcdef0123456789abcdef"
}
```

This example assumes another listener follows this page. Fetch the next page by adding `--data-urlencode "after=0123456789abcdef0123456789abcdef"` to the same request. The final page has `next_after: null`; an empty collection is `{"items":[],"next_after":null}`.

#### GET /api/listeners/{listener_id}

No parameters. 200 returns `ListenerInfo`; 404 `listener_not_found` for an invalid/unknown/no-longer-active ID.

`ListenerInfo`: opaque `id` (32 lowercase hexadecimal characters from 128 random bits), canonical serving `mount`, `requested_mount`, `serving_mount`, owning source `generation`, `connected_at`, `duration_ms`, `connection`, `bytes_sent` (actual body transport writes, including ICY bytes), `icy_metadata`, and `state` (`connected` or `disconnecting`). Incoming forwarding headers are not exposed. Random IDs do not disclose memory addresses or reusable slot indexes. Entropy failure rejects admission; an active-ID collision fails closed.

**Example request**

```sh
curl -i -H "Authorization: Bearer $QUIKCAST_TOKEN" \
  "$QUIKCAST_ADMIN_URL/api/listeners/0123456789abcdef0123456789abcdef"
```

**Example response: 200 OK**

```json
{
  "id": "0123456789abcdef0123456789abcdef",
  "mount": "/radio.mp3",
  "generation": 7,
  "connected_at": 1791460830000,
  "duration_ms": 30000,
  "connection": {
    "remote_address": "127.0.0.1:54210",
    "client_ip": "127.0.0.1",
    "user_agent": "Example player"
  },
  "bytes_sent": 480000,
  "icy_metadata": false,
  "state": "connected"
}
```

#### DELETE /api/listeners/{listener_id}

No parameters or body. 204 requests cancellation; 404 `listener_not_found` for invalid/unknown/completed listeners; 400 `invalid_request` for query parameters.

The domain marks the administrative reason and cancels that record's token. The existing supervised connection monitor/body terminates the transport; lease Drop removes the ephemeral record and releases the same local/global permits as any normal close. The handler never owns or edits sockets. Concurrent duplicate operations are safe and may return 204 until cleanup, then 404. Cancellation is observed by the existing monitor at its 50 ms tick even if no source audio arrives. 204 does not promise completed task joining. A stale ID cannot select a new connection through a reused index. Mutation logs include the opaque listener ID, mount, result, and reason.

**Example request**

```sh
curl -i -X DELETE -H "Authorization: Bearer $QUIKCAST_TOKEN" \
  "$QUIKCAST_ADMIN_URL/api/listeners/0123456789abcdef0123456789abcdef"
```

**Example response: 204 No Content**

```http
HTTP/1.1 204 No Content
Cache-Control: no-store
```

There is no response body.

#### GET /api/hls

No parameters. 200 returns bounded `StreamInfo[]`, sorted by stream name. Disabled HLS returns 404 `hls_not_found`. Startup limits registry capacity to at most 64 streams.

**Example request**

```sh
curl -i -H "Authorization: Bearer $QUIKCAST_TOKEN" \
  "$QUIKCAST_ADMIN_URL/api/hls"
```

**Example response: 200 OK**

```json
[
  {
    "name": "radio",
    "generation": 101,
    "state": "active",
    "playlist_revision": 2,
    "rendition_count": 1,
    "retained_bytes": 192000
  }
]
```

Enabled HLS with no registered streams returns `[]`. Disabled HLS returns 404 `hls_not_found`.

When `[hls] directory` (see "Configuration reference") is set, each stream directory that no ingested stream shadows is listed as well, with `"source": "directory"` instead of the ingest fields:

```json
{
  "name": "radio",
  "source": "directory",
  "state": "active",
  "playlist_count": 2,
  "retained_bytes": 481920,
  "active_listeners": 12,
  "listener_window_seconds": 60,
  "active_sessions": 14,
  "session_timeout_seconds": 30,
  "playlist_requests": 5231,
  "segment_requests": 5198
}
```

`state` is `active` when the directory holds a playlist and `empty` otherwise. `active_listeners` is the number of distinct client IPs that fetched a playlist or segment within `listener_window_seconds`; the request counters count successful reads since startup. `GET /api/hls/{stream}` returns the same object; the `/renditions` endpoints do not apply to directory streams. `active_sessions` is the number of sessions returned by `GET /api/hls/{stream}/listeners`.

#### GET /api/hls/{stream}

No parameters. 200 returns `StreamInfo`; 404 `hls_not_found` if unknown or HLS disabled. `StreamInfo`: `name`, `generation`, `state` (`active`, `ended`, `deleted`), master `playlist_revision`, `rendition_count`, and retained segment `retained_bytes`.

**Example request**

```sh
curl -i -H "Authorization: Bearer $QUIKCAST_TOKEN" \
  "$QUIKCAST_ADMIN_URL/api/hls/radio"
```

**Example response: 200 OK**

```json
{
  "name": "radio",
  "generation": 101,
  "state": "active",
  "playlist_revision": 2,
  "rendition_count": 1,
  "retained_bytes": 192000
}
```

#### GET /api/hls/{stream}/listeners

No parameters. Lists the active listener sessions of a directory stream (see "Configuration reference"), most recently active first. Returns `[]` when nobody is listening; 404 `hls_not_found` for an unknown stream, an ingested stream (not tracked) or disabled HLS.

HLS has no connection, so a session is one client address plus user agent. It is active if it fetched a playlist or segment within `directory_session_timeout_secs` (see "Configuration reference") (default 30). The client address honours `[trusted_proxies]` and `X-Forwarded-For`. At most 10,000 sessions are kept per stream; the least recently active are evicted first. Sessions reset on restart.

`SessionInfo`: `id` (16 hex characters, a stable hash of client IP and user agent), `ip`, `user_agent` (up to 256 characters, or `null`), `country` (ISO 3166-1 alpha-2 from the `[access]` GeoIP database, or `null` for private or unknown addresses), `first_seen` and `last_seen` (Unix seconds), `duration_seconds` (`last_seen - first_seen`), `playlist_requests`, `segment_requests` (successful `GET`s, including initialization files) and `bytes_served` (response body bytes, `0` for `304`).

**Example request**

```sh
curl -i -H "Authorization: Bearer $QUIKCAST_TOKEN" \
  "$QUIKCAST_ADMIN_URL/api/hls/radio/listeners"
```

**Example response: 200 OK**

```json
[
  {
    "id": "9f3a1c5e7b2d4086",
    "ip": "203.0.113.8",
    "user_agent": "AppleCoreMedia/1.0.0 (iPhone)",
    "country": "US",
    "first_seen": 1767225600,
    "last_seen": 1767225690,
    "duration_seconds": 90,
    "playlist_requests": 45,
    "segment_requests": 44,
    "bytes_served": 1843200
  }
]
```

#### GET /api/hls/{stream}/renditions

No parameters. 200 returns bounded `RenditionInfo[]`, sorted by rendition name; 404 `hls_not_found` for unknown stream or disabled HLS. Configured bounds allow at most 16 renditions per stream and 128 across the server.

**Example request**

```sh
curl -i -H "Authorization: Bearer $QUIKCAST_TOKEN" \
  "$QUIKCAST_ADMIN_URL/api/hls/radio/renditions"
```

**Example response: 200 OK**

```json
[
  {
    "name": "audio",
    "generation": 102,
    "state": "active",
    "bandwidth": 128000,
    "codecs": "mp4a.40.2",
    "target_duration": 4,
    "playlist_revision": 5,
    "media_sequence": 10,
    "advertised_segment_count": 3,
    "retained_segment_count": 3,
  "format": "mpeg-ts",
  "container": "mpeg-ts",
  "codec": "aac",
  "content_type": "video/mp2t",
  "initialization_object": null,
  "initialization_object_count": 0,
  "media_object_count": 3,
  "audio_properties": null,
    "format": "mpeg-ts",
    "container": "mpeg-ts",
    "codec": "aac",
    "content_type": "video/mp2t",
    "initialization_object": null,
    "initialization_object_count": 0,
    "media_object_count": 3,
    "audio_properties": null,
    "retained_bytes": 192000,
    "allocation_reserved_bytes": 262144,
    "allocation_budget": 134217728,
    "last_segment_ingest_at": 1791460858000,
    "last_playlist_publication_at": 1791460859000
  }
]
```

#### GET /api/hls/{stream}/renditions/{rendition}

No parameters. 200 returns `RenditionInfo`; 404 `hls_not_found` for unknown stream/rendition or disabled HLS.

`RenditionInfo`: `name`, `generation`, `state` (`active`, `ended`, `deleted`), producer-declared `bandwidth` and `codecs`, `target_duration` (seconds), `playlist_revision`, `media_sequence` (first currently advertised sequence or null), `advertised_segment_count`, `retained_segment_count`, `retained_bytes`, `allocation_reserved_bytes`, `allocation_budget`, `last_segment_ingest_at`, and `last_playlist_publication_at`.

Generalized audio inspection also includes `format` (`mpeg-ts`, `packed-aac`, `packed-mp3`, `fmp4`), `container` (`mpeg-ts`, `packed`, `fmp4`), `codec`, canonical `content_type`, nullable current `initialization_object` name, `initialization_object_count`, `media_object_count` and nullable `audio_properties` (`sample_rate_hz`, `channels`, nullable `bits_per_sample`). Retained bytes include initialization objects. Current initialization is null until a playlist publishes it; held/grace objects remain charged independently. See "HLS ingest API" for typed ingest, lifecycle and supported codecs. No object bytes or producer credentials are exposed.

Retained segment bytes include staging and grace-period objects. Deleted tombstones remain inspectable until existing maintenance and final references permit reclamation; after that lookup returns 404. Read snapshots lock registry/state synchronously and never await or clone media payloads. Different resources need not represent one atomic cross-stream instant. The producer API remains responsible for HLS end/delete; `/api` does not duplicate it. Continuous streaming and HLS remain independent.

**Example request**

```sh
curl -i -H "Authorization: Bearer $QUIKCAST_TOKEN" \
  "$QUIKCAST_ADMIN_URL/api/hls/radio/renditions/audio"
```

**Example response: 200 OK**

```json
{
  "name": "audio",
  "generation": 102,
  "state": "active",
  "bandwidth": 128000,
  "codecs": "mp4a.40.2",
  "target_duration": 4,
  "playlist_revision": 5,
  "media_sequence": 10,
  "advertised_segment_count": 3,
  "retained_segment_count": 3,
  "format": "mpeg-ts",
  "container": "mpeg-ts",
  "codec": "aac",
  "content_type": "video/mp2t",
  "initialization_object": null,
  "initialization_object_count": 0,
  "media_object_count": 3,
  "audio_properties": null,
  "retained_bytes": 192000,
  "allocation_reserved_bytes": 262144,
  "allocation_budget": 134217728,
  "last_segment_ingest_at": 1791460858000,
  "last_playlist_publication_at": 1791460859000
}
```

### Errors, times, and health

API errors have a stable native envelope:

```json
{
  "error": {
    "code": "mount_not_found",
    "message": "Mount not found"
  }
}
```

Shared endpoint errors: 401 `unauthorized`, 400 `invalid_request`, 405 `method_not_allowed`, 404 `endpoint_not_found`, and 500 `internal_error` for domain/serialization faults. HLS malformed identifiers receive 400 `invalid_request`; state conflicts receive 409 `conflict`. Error responses never contain secret values, credentials, filesystem paths, debug types, or stack traces. Internal faults retain diagnostic log context. Admission rejected because of drain uses 503 `server_draining` when surfaced through a native API operation. Endpoint-specific errors are listed above.

Timestamp fields ending in `_at`, plus `connected_at`/`started_at`, are Unix epoch milliseconds. Duration/age/uptime use monotonic elapsed milliseconds. Counters and identifiers are ephemeral across restarts; do not use source generation alone as a cross-restart identity.

Public responses identify as `Server: Quikcast`. Continuous audio remains HTTP/1.0 close-delimited with no conflicting Content-Length/Transfer-Encoding, existing content/ICY headers, and `Cache-Control: no-cache, no-store`.

`/health/live` confirms the running request service and stays 200 while draining. `/health/ready` returns 200 only while accepting, and becomes 503 with `Server draining\n` after drain; during shutdown it follows the existing 503 unavailable response. Readiness probes do not increment drain admission rejection counters. Configuration and subsystem initialization finish before binding. Neither requires connected sources, listeners, or HLS streams. Both remain constant-cost. `/metrics` continues to expose a fixed bounded-cardinality Prometheus inventory; no listener IDs, addresses, user agents, or dynamic mount labels have been added.

#### Example error responses

Missing authentication:

```sh
curl -i "$QUIKCAST_ADMIN_URL/api/server"
```

**401 Unauthorized**, with `WWW-Authenticate: Bearer realm="Quikcast management"`:

```json
{
  "error": {
    "code": "unauthorized",
    "message": "Authentication required"
  }
}
```

Unknown mount:

```sh
curl -i -H "Authorization: Bearer $QUIKCAST_TOKEN" \
  "$QUIKCAST_ADMIN_URL/api/mounts/missing.mp3"
```

**404 Not Found**:

```json
{
  "error": {
    "code": "mount_not_found",
    "message": "Mount not found"
  }
}
```

Invalid listener pagination:

```sh
curl -i -G -H "Authorization: Bearer $QUIKCAST_TOKEN" \
  --data-urlencode 'mount=/radio.mp3' --data-urlencode 'limit=201' \
  "$QUIKCAST_ADMIN_URL/api/listeners"
```

**400 Bad Request**:

```json
{
  "error": {
    "code": "invalid_pagination",
    "message": "Invalid listener pagination"
  }
}
```

A source DELETE with a stale `generation` on a mount that currently has a different source returns **409 Conflict**:

```json
{
  "error": {
    "code": "conflict",
    "message": "Source generation changed"
  }
}
```

If the mount exists but has no source, source DELETE returns **409 Conflict**:

```json
{
  "error": {
    "code": "source_not_connected",
    "message": "Source not connected"
  }
}
```

Relay POST/DELETE with a stale `revision` returns **409 Conflict**:

```json
{
  "error": {
    "code": "conflict",
    "message": "Resource changed"
  }
}
```

A relay POST during drain returns **503 Service Unavailable**:

```json
{
  "error": {
    "code": "server_draining",
    "message": "Server draining"
  }
}
```

An unsupported method returns **405 Method Not Allowed**, with the allowed methods in the `Allow` header:

```json
{
  "error": {
    "code": "method_not_allowed",
    "message": "Method not allowed"
  }
}
```

### Trusted proxy contract

A direct peer matched to the enabled `cloudflare` provider may supply one plain IP in `CF-Connecting-IP`. Otherwise the existing bounded `X-Forwarded-For` chain is used for peers matched by `trusted_proxies.ips` or provider networks. Untrusted peers cannot override their client IP, and manually trusted proxies do not gain Cloudflare header authority. IPv4-mapped IPv6 addresses normalize to IPv4 consistently. All inspection uses this shared resolved identity.

For a trusted peer, accept exactly one header, at most 1024 bytes, containing at most 16 comma-separated plain IP addresses. Starting from the socket peer, walk right to left while the current hop is trusted; the first untrusted hop becomes the client address. Never skip past that untrusted hop to an attacker-supplied leftmost address. If all hops are trusted, the leftmost address is selected. Empty, malformed, oversized, overlong-chain, duplicate, port-bearing, or non-IP entries invalidate the whole header and fall back to the socket peer. No RFC Forwarded, X-Real-IP, or PROXY protocol is interpreted.

How to configure your proxy safely is covered in "HTTPS and proxies". This identity is for operational inspection; it does not change authentication or admission policy.

### Continuous relay operations

Use these endpoints for configured continuous relays. The complete canonical mount path follows `/api/relays`; the upstream URL and credentials cannot be changed through this API. Relay commands have no body, accept an optional `revision` guard, and return 202 with a snapshot. Control revision and source generation are different identifiers.

Relay snapshots include ordered failover inspection: `upstream_count` (1–8), `current_upstream_index` (zero-based or null), `current_upstream` (origin only, no path/query), `upstream_usable` (normal codec/media readiness), `attempt_cycle`, `consecutive_failures`, and `last_failure` (fixed last remote category, retained across connection). Connected state means source ownership; Ogg can still await initialization with usability false. Backoff/stopped state has null selection and false usability. Cycle increments at index-0 attempts. Consecutive remote failures reset on explicit control revision changes or when a stable attempt ends. Worker replacement resets these observations. Upstream credentials, secret paths, URL paths/queries and raw errors are never exposed.

Failover is sticky: remote failure selects the next candidate after cleanup, exhaustion backs off then retries primary, and recovery of the primary does not displace a healthy backup. POST always resets selection to primary; DELETE and source DELETE suppress failover/retry. Drain blocks successors, while admitted connections continue. The fixed unlabeled `/metrics` counters `relay_failovers_total` and `relay_upstream_failures_total` distinguish forward candidate transitions from genuine remote failures; administrative actions and local mount conflicts do not count. URL/list editing remains file-based through atomic reload. An unchanged list preserves a healthy backup; any effective list/credential edit restarts that worker from primary.

#### GET /api/relays

Returns an array of all configured relays; no relays returns `[]`. No query parameters.

**Example request**

```sh
curl -i -H "Authorization: Bearer $QUIKCAST_TOKEN" \
  "$QUIKCAST_ADMIN_URL/api/relays"
```

**Example response: 200 OK**

```json
[
  {
    "mount": "/remote.mp3",
    "upstream_count": 1,
    "current_upstream_index": 0,
    "current_upstream": "https://origin.example",
    "upstream_usable": true,
    "attempt_cycle": 2,
    "consecutive_failures": 0,
    "last_failure": null,
    "state": "connected",
    "desired_running": true,
    "revision": 4,
    "attempt": 2,
    "generation": 9,
    "connected_at": 1791460830000,
    "connection_age_ms": 30000,
    "next_retry_at": null,
    "retry_in_ms": null,
    "retry_delay_ms": null,
    "stopped_reason": null,
    "last_error": null,
    "last_upstream_status": 200,
    "attempts_total": 2,
    "connections_total": 2,
    "reconnects_total": 1,
    "response_body_bytes_total": 481024,
    "audio_bytes_total": 480000,
    "metadata_rejections_total": 0,
    "allocation_reservation_bytes": 2097152
  }
]
```

#### GET /api/relays/{mount path}

Inspect a configured relay. No query parameters. Unknown relay returns 404 `relay_not_found`.

**Example request**

```sh
curl -i -H "Authorization: Bearer $QUIKCAST_TOKEN" \
  "$QUIKCAST_ADMIN_URL/api/relays/remote.mp3"
```

**Example response: 200 OK**

```json
{
  "mount": "/remote.mp3",
  "upstream_count": 1,
  "current_upstream_index": 0,
  "current_upstream": "https://origin.example",
  "upstream_usable": true,
  "attempt_cycle": 2,
  "consecutive_failures": 0,
  "last_failure": null,
  "state": "connected",
  "desired_running": true,
  "revision": 4,
  "attempt": 2,
  "generation": 9,
  "connected_at": 1791460830000,
  "connection_age_ms": 30000,
  "next_retry_at": null,
  "retry_in_ms": null,
  "retry_delay_ms": null,
  "stopped_reason": null,
  "last_error": null,
  "last_upstream_status": 200,
  "attempts_total": 2,
  "connections_total": 2,
  "reconnects_total": 1,
  "response_body_bytes_total": 481024,
  "audio_bytes_total": 480000,
  "metadata_rejections_total": 0,
  "allocation_reservation_bytes": 2097152
}
```

#### POST /api/relays/{mount path}

Start a stopped relay or reconnect a running relay. Read its current revision first; this example uses revision 4.

**Example request**

```sh
curl -i -X POST -H "Authorization: Bearer $QUIKCAST_TOKEN" \
  "$QUIKCAST_ADMIN_URL/api/relays/remote.mp3?revision=4"
```

**Example response: 202 Accepted**

```json
{
  "mount": "/remote.mp3",
  "upstream_count": 1,
  "current_upstream_index": 0,
  "current_upstream": "https://origin.example",
  "upstream_usable": true,
  "attempt_cycle": 2,
  "consecutive_failures": 0,
  "last_failure": null,
  "state": "connected",
  "desired_running": true,
  "revision": 5,
  "attempt": 2,
  "generation": 9,
  "connected_at": 1791460830000,
  "connection_age_ms": 30000,
  "next_retry_at": null,
  "retry_in_ms": null,
  "retry_delay_ms": null,
  "stopped_reason": null,
  "last_error": null,
  "last_upstream_status": 200,
  "attempts_total": 2,
  "connections_total": 2,
  "reconnects_total": 1,
  "response_body_bytes_total": 481024,
  "audio_bytes_total": 480000,
  "metadata_rejections_total": 0,
  "allocation_reservation_bytes": 2097152
}
```

202 means the command was accepted. The response can still show the prior connected generation while the worker cancels it. Poll GET `/api/relays/remote.mp3` to observe subsequent connecting/connected/backoff state. A stale revision returns 409 `conflict`; a start/reconnect during drain returns 503 `server_draining`.

#### DELETE /api/relays/{mount path}

Stop automatic pulling and retry. This independent example assumes the latest inspected revision is 4.

**Example request**

```sh
curl -i -X DELETE -H "Authorization: Bearer $QUIKCAST_TOKEN" \
  "$QUIKCAST_ADMIN_URL/api/relays/remote.mp3?revision=4"
```

**Example response: 202 Accepted**

```json
{
  "mount": "/remote.mp3",
  "upstream_count": 1,
  "current_upstream_index": 0,
  "current_upstream": "https://origin.example",
  "upstream_usable": true,
  "attempt_cycle": 2,
  "consecutive_failures": 0,
  "last_failure": null,
  "state": "connected",
  "desired_running": false,
  "revision": 5,
  "attempt": 2,
  "generation": 9,
  "connected_at": 1791460830000,
  "connection_age_ms": 30000,
  "next_retry_at": null,
  "retry_in_ms": null,
  "retry_delay_ms": null,
  "stopped_reason": "administrative_stop",
  "last_error": null,
  "last_upstream_status": 200,
  "attempts_total": 2,
  "connections_total": 2,
  "reconnects_total": 1,
  "response_body_bytes_total": 481024,
  "audio_bytes_total": 480000,
  "metadata_rejections_total": 0,
  "allocation_reservation_bytes": 2097152
}
```

The worker stops asynchronously. Poll until `state` is `stopped`; a 202 response can still show `state: "connected"` during cleanup. Stop remains available during drain. A stale revision returns 409 `conflict`.

See "Relay another station" for every snapshot field, retry behavior, counters, and lifecycle semantics. `/api/stats.relays` provides aggregate visibility.

### Fallback visibility

Configured continuous mount snapshots include `fallback` (canonical target or null). Listener records add `requested_mount` and `serving_mount`. The existing `mount` field continues to mean the serving mount; listener pagination filters that mount's registry. Active counts and body bytes belong to the serving mount only. `/api/stats` and Prometheus expose the fixed unlabeled `fallback_listener_admissions_total`; `/api/server` includes capability `fallback-mounts`. See "Backup streams (fallback)" for routing, metadata and restoration semantics.

### Listener history

`GET /api/history` reports volatile listener history for the whole server (including estimated directory HLS listeners); add `mount=/radio.mp3` for one mount (percent-encode nested paths) and `minutes=N` (1–1440, default 60) to limit the per-minute window. History is held in bounded memory, covers the last 24 hours, and resets on restart. A dynamic mount's history ends when the mount is cleaned up; the server-wide view is unaffected.

```json
{
  "mount": null,
  "window_minutes": 60,
  "retention_minutes": 1440,
  "peak_listeners_24h": 41,
  "listener_starts_24h": 318,
  "unique_listeners_estimate_24h": 207,
  "minutes": [{"start_ms": 1790000000000, "peak_listeners": 12, "listener_starts": 3}],
  "hours": [{"start_ms": 1789999200000, "unique_listeners_estimate": 88}]
}
```

`peak_listeners` is the highest concurrent listener count seen in that minute; quiet minutes carry the current audience forward. `listener_starts` counts admissions. Unique counts are HyperLogLog estimates (about 3% error) per hour and merged over 24 hours; client addresses are hashed into the sketch with a per-process random key and are never stored. The `listener-history` capability appears in `/api/server`. Invalid parameters return `400 invalid_request`; an unknown mount returns `404 mount_not_found`.

### Listener access inspection

`/api/server` advertises `listener-access-control` and includes sanitized global `access` rule counts/country lists, `geoip_loaded`, and `mount_access_enabled`. Continuous mount inspection includes the same sanitized `access` model for that mount's own restrictions. IP and UA rule contents and MMDB paths are omitted. Global policy remains a prerequisite for every mount and public HLS playback. See "Limit who can listen" for configuration, limits, deny counters and fallback behavior. These are read-only inspection fields; management authentication is unchanged.

### Source IP access inspection

Mount snapshots include `source_access` with deduplicated `ip_allow_rules` and `ip_deny_rules` counts; omitted policy has zero counts. IP rules, credentials and secret-file paths are not exposed. Server capabilities include `source-ip-access-control`. Private `/metrics` exposes the fixed unlabeled `source_access_denied_ip_total` counter separately from authentication and source admission accounting. There are no source ACL mutation endpoints. See "Limit who can listen" for policy, proxy resolution and protocol ordering.

### Listener bans and link revocation

Two groups of endpoints act on listeners at runtime. Both are kept **in memory**: they are lost on restart, every entry expires, and the lists are bounded. They are not shared between replicas (see "Primary and replica servers"), so send the call to each node. Requests take query parameters and no body. `/api/server` advertises `listener-bans` and `listener-link-revocation`.

#### GET /api/bans

Returns `{"items": [{"ip", "expires_in_seconds", "reason"}]}`: the active bans.

#### POST /api/bans?ip={address or CIDR}&ttl_seconds={n}&reason={text}&kick={true|false}

Refuses an address or range, on mounts and HLS, before any other access rule. `ip` is required. `ttl_seconds` is 1 to 2,592,000 and defaults to 3,600. `reason` is optional, up to 128 bytes, and is kept for the list and the log. With `kick=true` every connected listener in that range is disconnected too. Responds `201` with `{"ip", "expires_in_seconds", "kicked_listeners"}`. Banning the same `ip` text again replaces its entry. At most 1,024 bans are held (`507 ban_list_full`). A banned listener gets a plain `403`.

#### DELETE /api/bans?ip={address or CIDR}

Lifts a ban, using the same text it was created with. `204`, or `404 ban_not_found`.

```sh
curl -X POST -H "Authorization: Bearer $QUIKCAST_TOKEN" \
  "$QUIKCAST_ADMIN_URL/api/bans?ip=203.0.113.0%2F24&ttl_seconds=86400&kick=true&reason=scraper"
```

#### GET /api/revocations

Returns `{"items": [{"signature", "expires_in_seconds"}]}`: the revoked signed links (see "Signed, expiring links").

#### POST /api/revocations?sig={signature}&expires={unix seconds}

Stops one signed link from working before it expires, without rotating the key. Pass the link's own `sig` and `expires`. `expires` must be in the future and within a week. The entry is dropped when the link would have expired anyway. Responds `201` with the list; `507 revocation_list_full` at 10,000 entries. Existing playback sessions are not interrupted; end them with a ban and `kick`, or `DELETE /api/listeners/{id}`.

#### DELETE /api/revocations?sig={signature}

Re-enables a link. `204`, or `404 revocation_not_found`.

### Signed listener URL authentication

See "Signed, expiring links" for mount-local and HLS stream configuration, exact signing rules, external PHP signing, atomic key rotation, sanitized management fields, and protected cache/Range semantics.

See "Metrics" for additive fields, exact byte semantics, reason enums and the complete metric inventory.

## HLS ingest API

The private API your **producer** uses to publish HLS audio. For a gentle introduction read "HLS for browsers and apps" first.

All routes are on the **admin address** (`admin_listen`) under `/internal/v1/hls/`, use HTTP Basic authentication with the `[hls]` username and password, and are separate from the "Management API" and its bearer token.

### Conventions

- **Names.** A stream or rendition name is 1–64 letters, digits, `_` or `-`. Names are never used as file paths.
- **Generations.** Creating a stream or rendition returns a *generation*, as a JSON **string**. Send it back, unchanged, in `X-HLS-Generation` (stream) and `X-HLS-Rendition-Generation` (rendition) on later calls. A stale generation is rejected, which stops an old producer from damaging its replacement.
- **Revisions.** Every publication has a revision starting at `0`. You send the revision you expect; a mismatch is rejected.
- **Numbers.** Sequence numbers and IDs are plain unsigned decimals: no sign, no leading zeros (except `0`).
- **JSON.** Send `Content-Type: application/json`. Unknown fields are rejected. Bodies are at most 256 KiB.
- **No playlists.** You never upload `.m3u8` files. Quikcast writes playlists from the structured data you publish.

In the table below, `S` is `/internal/v1/hls/streams/{stream}` and `R` is `S/renditions/{rendition}`.

### Endpoints

| Request | What it does |
|---|---|
| `PUT S` | Create a stream. Empty body. Returns `201` with its generation. |
| `GET S` | Read the stream's generation, master revision and state. |
| `PUT R` | Create a rendition from a JSON description. Needs `X-HLS-Generation`. |
| `GET R` | Read the rendition's generation, revision, state and segment count. |
| `PUT R/segments/{n}` | Upload media segment `n`. |
| `PUT R/initializations/{id}` | Upload an fMP4 initialization object (fMP4 only). |
| `PUT R/publication` | Atomically publish the media playlist. |
| `PUT S/master` | Atomically publish the master playlist. An empty rendition list withdraws it. |
| `POST R/end` | Publish the current window with `ENDLIST`. |
| `POST S/end` | End the stream once all its renditions are ended. |
| `DELETE R` | Hide a rendition's playlist and retire its data. Withdraw it from the master first. |
| `DELETE S` | Hide the stream and retire every rendition. |

### Create a rendition

```json
{
  "format": "fmp4",
  "target_duration": 3,
  "window_segments": 6,
  "bandwidth": 128000,
  "codecs": "fLaC"
}
```

| Field | Meaning |
|---|---|
| `format` | `mpeg-ts` (default), `packed-aac`, `packed-mp3` or `fmp4`. |
| `target_duration` | Segment length in seconds, 1–60. Fixed for this rendition. |
| `window_segments` | Segments kept in the live playlist, 3–256. Subject to your `max_segments` budget. |
| `bandwidth` | Peak bits per second you declare. A positive number. |
| `codecs` | The RFC 6381 codecs string, up to 128 characters. |

You are responsible for **truthful declarations**: Quikcast checks the structure of what you upload but never decodes audio or invents bitrates.

#### Supported combinations

| Format | Codecs | Segment | Content type |
|---|---|---|---|
| `mpeg-ts` | `mp4a.40.2`, `mp4a.40.5` or `mp4a.40.29` (AAC) | `.ts` | `video/mp2t` |
| `packed-aac` | `mp4a.40.2`, `mp4a.40.5` or `mp4a.40.29` | `.aac` | `audio/aac` |
| `packed-mp3` | `mp4a.40.34` (alias `mp3`) | `.mp3` | `audio/mpeg` |
| `fmp4` | `mp4a.40.2`, `mp4a.40.5` or `mp4a.40.29` | `.m4s` + init `.mp4` | `audio/mp4` |
| `fmp4` | `fLaC` (alias `flac`) | `.m4s` + init `.mp4` | `audio/mp4` |

`mp4a.40.2` is AAC-LC, `mp4a.40.5` is HE-AAC and `mp4a.40.29` is HE-AACv2. Packed AAC must be ADTS with one raw data block per frame. HE-AAC signalled implicitly inside ADTS is passed through untouched.

### Upload a segment

```text
PUT R/segments/0
Authorization: Basic ...
X-HLS-Generation: <stream generation>
X-HLS-Rendition-Generation: <rendition generation>
X-HLS-Duration-Ms: 2000
X-HLS-Discontinuity: 0
Content-Type: audio/mp4
```

- `X-HLS-Duration-Ms` is the real duration in milliseconds. It must match `target_duration` after rounding to the nearest second.
- `X-HLS-Discontinuity` is optional (`0` or `1`).
- For fMP4 also send `X-HLS-Initialization: <init id>`, which must be an already uploaded, compatible initialization object.
- Success is `201`. A duplicate sequence is a `409`; nothing is overwritten.

#### What is validated

| Format | Checks |
|---|---|
| MPEG-TS | Whole 188-byte packets, valid sync bytes and adaptation fields, no scrambling, and an initial valid PAT and PMT. |
| Packed AAC/MP3 | Starts with an ID3v2 tag holding the `com.apple.streaming.transportStreamTimestamp` timestamp, then complete, contiguous frames. You supply the timestamp. |
| fMP4 | One audio track, supported codec, self-contained, then one `moof`/`mdat` pair per segment matching the initialization. Encryption and multiple tracks are rejected. |

### fMP4 initialization

Upload this **before** the segments that use it:

```text
PUT R/initializations/1
Content-Type: audio/mp4
```

Initialization IDs are immutable: uploading an existing ID is a `409`. To change to a compatible initialization, upload a new ID, mark its first fragment as a discontinuity, and publish a window that uses only the new one. A change in decoder configuration needs a new rendition.

### Publish a playlist

Upload first, then publish. Publication lists consecutive sequences you have uploaded:

```json
{
  "expected_revision": 0,
  "initialization": 1,
  "segments": [
    { "sequence": 0, "duration_ms": 2000 },
    { "sequence": 1, "duration_ms": 2000 }
  ],
  "end": false
}
```

- `initialization` is required for fMP4 and forbidden otherwise.
- A segment may add `"discontinuity": true`, matching its upload.
- Every referenced segment must already exist. If any check fails, nothing changes.
- A sliding window must stay at least three target durations long.

The master playlist lists renditions that are ready:

```json
{ "expected_revision": 0, "renditions": ["aac"] }
```

Ending a rendition: `POST R/end` with `{"expected_revision": 1}`.

Playlists are version 3 for TS and packed audio, and version 7 for fMP4.

### Status codes

| Code | Meaning |
|---|---|
| `201` | Created or accepted. |
| `400` | Bad syntax or an invalid description or structure. |
| `401` | Wrong credentials. |
| `404` | Unknown stream, rendition or object. |
| `409` | Stale generation or revision, duplicate or retired sequence, missing or mismatched object, or an illegal window change. |
| `413` | Upload larger than `max_segment_bytes` (initializations: the smaller of that and 256 KiB). |
| `415` | Unsupported content type or codec. |
| `503` | Out of upload slots, memory or registry capacity. Draining also refuses new work. |

### Timing and retention

- Upload bodies must keep flowing (10 seconds of silence aborts them), and finish within 30 seconds.
- Uploaded but unpublished objects expire after **30 seconds**.
- Advertised segments never expire. Once removed from the playlist, a segment stays available for its own duration plus the longest playlist that listed it, as HLS requires.
- A window `W` needs `2W + 1 + max_uploads` object slots (plus one for fMP4 initialization), within `max_segments`.
- Everything is in memory and is lost on restart.

### Public side

Players fetch:

| URL | Content |
|---|---|
| `/hls/{stream}/master.m3u8` | The master playlist |
| `/hls/{stream}/{rendition}/index.m3u8` | A media playlist |
| `/hls/{stream}/{rendition}/<generation>-<n>.ts\|aac\|mp3\|m4s` | A segment |
| `/hls/{stream}/{rendition}/<generation>-init-<id>.mp4` | An initialization object |

`GET` and `HEAD` are supported, with `ETag` revalidation (`304`) and single byte ranges (`206`; invalid ones return `416`). Playlists use `Cache-Control: no-cache`; segments are `public, max-age=31536000, immutable`. With `cors_origin` set, `OPTIONS` preflight is answered, allowing the `Range`, `If-None-Match` and `If-Range` headers.

### Inspection

Operators can see the state of HLS streams through the "Management API" (`/api/hls`), including formats, object counts and memory use.

## Metrics

`GET /metrics` on the admin address (default `http://127.0.0.1:9090/metrics`) returns every metric in Prometheus text format. It needs no token because the admin address only listens on localhost. For how to scrape and alert, see "Monitoring".

Counters (names ending in `_total`) only ever go up and reset when Quikcast restarts. Use `rate()` or `increase()` on them. Gauges go up and down. There are no per-mount or per-listener labels, so the number of series stays small and fixed no matter how busy the server gets. The only labelled metrics use a fixed set of `reason` values (see disconnect reasons).

### Server

| Metric | Type | Meaning |
|---|---|---|
| `uptime_seconds` | gauge | Seconds since the process started. |
| `ready` | gauge | `1` while the server accepts new work, `0` while draining or shutting down. |
| `config_generation` | gauge | Starts at `1` and increases with every successful reload. |
| `config_reload_attempts_total` | counter | Reloads attempted. |
| `config_reload_successes_total` | counter | Reloads that were applied. |
| `config_reload_failures_total` | counter | Reloads that were rejected. The old config stayed active. |
| `errors_total` | counter | Error responses sent to clients. |
| `admission_rejections_total` | counter | Connections refused because a connection or handshake limit was full. |
| `accept_errors_total` | counter | Failed `accept()` calls. Descriptor exhaustion pauses accepting briefly instead of stopping the server. |
| `open_files` | gauge | Open file descriptors, sampled every few seconds. |
| `open_files_limit` | gauge | Soft open-file limit used to size admission (0 when unknown). |
| `drain_rejections_total` | counter | New work refused because the server is draining. |
| `logging_dropped_total` | counter | Log lines dropped because the log reader could not keep up. |

### Sources (encoders)

| Metric | Type | Meaning |
|---|---|---|
| `active_sources` | gauge | Sources connected right now. |
| `active_mounts` | gauge | Mounts that currently have a source. Same value as `active_sources`. |
| `source_connections_total` | counter | Sources admitted since start. |
| `source_auth_denials_total` | counter | Source connections refused for a wrong password. |
| `source_conflicts_total` | counter | Source connections refused because the mount already has a source (or a relay). |
| `source_access_denied_ip_total` | counter | Source connections refused by `source_access` IP rules. |
| `source_auth_duration_seconds` | histogram | Time spent checking source credentials. |
| `source_disconnects_total` | counter | Sources that ended, by `reason`. |
| `bytes_ingested_total` | counter | Audio bytes accepted from sources and relays. |
| `retained_audio_allocation_bytes` | gauge | Memory currently reserved for retained audio. |
| `metadata_updates_total` | counter | Song title updates accepted. |

### Listeners

| Metric | Type | Meaning |
|---|---|---|
| `active_listeners` | gauge | Listeners connected right now. Directory HLS listeners are estimates and are not included. |
| `listeners_connected_total` | counter | Listeners admitted since start. |
| `listeners_disconnected_total` | counter | Listeners that ended, by `reason`. |
| `slow_consumers_total` | counter | Listeners dropped for falling too far behind. |
| `bytes_served_total` | counter | Audio bytes sent to continuous-stream listeners, including embedded titles. |
| `audio_bytes_served_total` | counter | Of those, the audio itself. |
| `icy_metadata_bytes_served_total` | counter | Of those, embedded song-title blocks. |
| `fallback_listener_admissions_total` | counter | Listeners served by a fallback (see "Backup streams (fallback)") mount instead of the one they asked for. |
| `listeners_redirected_total` | counter | Listeners sent to a replica (see "Primary and replica servers") with an HTTP redirect. |

### Access control

| Metric | Type | Meaning |
|---|---|---|
| `listener_access_denied_ip_total` | counter | Listeners refused by an IP rule. |
| `listener_access_denied_geo_total` | counter | Listeners refused by a country rule. |
| `listener_access_denied_user_agent_total` | counter | Listeners refused by a User-Agent rule. |
| `listener_access_denied_asn_total` | counter | Listeners refused by an ASN rule. |
| `listener_banned_total` | counter | Listeners refused by a runtime ban (see "Management API"). |
| `listener_per_ip_rejected_total` | counter | Listeners refused with `429` for holding too many connections from one address. |
| `listener_link_revoked_total` | counter | Requests refused because their signed link was revoked. |
| `listener_signed_auth_denied_total` | counter | Listeners refused for a bad or expired signed link (see "Signed, expiring links"). |
| `hls_signed_auth_denied_total` | counter | The same, for HLS requests. |

### Relays

| Metric | Type | Meaning |
|---|---|---|
| `relay_attempts_total` | counter | Connection attempts to upstreams. |
| `relay_connections_total` | counter | Successful connections to an upstream. |
| `relay_failures_total` | counter | Failed attempts. |
| `relay_upstream_failures_total` | counter | Failures caused by the upstream (as opposed to local problems). |
| `relay_failovers_total` | counter | Switches to the next upstream. |
| `relay_cycles_exhausted_total` | counter | Times every upstream failed and the relay had to back off. |
| `relay_reconnects_total` | counter | Reconnects after an earlier connection. |
| `relay_response_body_bytes_total` | counter | Bytes read from upstreams. |
| `relay_audio_bytes_total` | counter | Audio bytes demultiplexed from upstreams. |
| `relay_metadata_rejections_total` | counter | Invalid song titles from upstreams that were ignored. |

### HLS

| Metric | Type | Meaning |
|---|---|---|
| `hls_requests_total` | counter | Public HLS requests. |
| `hls_get_responses_total` | counter | `GET` responses served. |
| `hls_head_responses_total` | counter | `HEAD` responses served. |
| `hls_partial_responses_total` | counter | `206 Partial Content` responses (byte ranges). |
| `hls_not_modified_responses_total` | counter | `304 Not Modified` responses. |
| `hls_range_rejections_total` | counter | Byte-range requests refused as unsatisfiable. |
| `hls_rejections_total` | counter | HLS requests and uploads that were rejected. |
| `hls_bytes_served_total` | counter | Body bytes of HLS responses. |
| `hls_ingest_bytes_total` | counter | Bytes of accepted segment and initialization uploads. |
| `hls_segments_accepted_total` | counter | Media segments accepted. |
| `hls_initializations_accepted_total` | counter | fMP4 initialization objects accepted. |
| `hls_publications_total` | counter | Playlist publications. |
| `hls_active_uploads` | gauge | Uploads in progress. |
| `hls_stored_objects` | gauge | Segments and initialization objects held in memory. |
| `hls_stored_bytes` | gauge | Bytes held in memory. |
| `hls_allocation_reserved_bytes` | gauge | Memory reserved against `allocation_budget`. |

### Disconnect reasons

`listeners_disconnected_total` and `source_disconnects_total` carry one `reason` label with a fixed set of values. All values always appear, even at zero.

| Reason | Meaning |
|---|---|
| `client_disconnected` | The listener closed the connection. |
| `source_disconnected` | The encoder disconnected. Listeners ended with it. |
| `slow_consumer` | The listener fell behind the retained audio. |
| `write_stall` | The listener's connection stopped accepting data. |
| `shutdown` | The server was shutting down. |
| `source_timeout` | The encoder sent nothing for `source_timeout_ms`. |
| `malformed_input` | The source sent audio Quikcast could not parse. |
| `internal_fault` | An internal error. Please report it. |
| `administrative_disconnect` | An operator disconnected it through the API or console. |
| `duration_limit` | The listener reached the mount's `max_listener_duration`. |

### What is not measured

Listener numbers over time are not metrics. Use the `/api/history` (see "Management API") endpoint for the last 24 hours, or graph `active_listeners` in your own Prometheus for longer.

## Capacity and limits

Quikcast refuses to start with limits that its memory budget cannot honour, so a server that boots is a server that has reserved what it promised. This page explains how the limits relate and how to size them. The individual settings are listed in the `[limits]` reference (see "Configuration reference").

### The short version

For most stations, change **only** `max_listeners` and `listeners_per_mount` to match your bandwidth, and leave the rest alone.

```toml
[limits]
max_listeners = 2000
listeners_per_mount = 2000
```

That is enough for roughly **200 MB of reserved memory** and keeps startup checks happy.

### What the limits protect

| Limit | Protects against |
|---|---|
| `max_connections`, `max_handshakes` | Too many sockets, and slow clients that connect but never finish asking. |
| `max_mounts` | Configuring more streams than you have memory for. |
| `max_listeners`, `listeners_per_mount` | Too much outbound bandwidth and memory for audio listeners. |
| `retained_audio_budget` | The total memory promised to audio buffers and listeners. |
| `ring_bytes`, `ring_entries`, `join_bytes` | How much recent audio each stream remembers. |
| `*_timeout_ms` | Stalled clients, encoders and shutdowns. |

None of them cap how long a healthy stream may run.

### How the memory budget is checked

At startup Quikcast adds up what it must be able to hold, in the worst case, and compares it with `retained_audio_budget` (2 GiB by default).

```text
required = 2 × mounts × generation + max_listeners × listener
```

- **`2 × mounts × generation`**: each mount can hold two source *generations* at once (the current one and one that listeners are still draining). A generation reserves its ring (`ring_bytes` plus bookkeeping for `ring_entries`) and fixed parser buffers. With default settings it is about **5.4 MB**.
- **`max_listeners × listener`**: every possible listener reserves pending-write space, a metadata block and a share of header storage. That is about **105 KB** each.

#### Rules of thumb

| You have | Reserved memory is about |
|---|---|
| 1 mount, 1,000 listeners | 115 MB |
| 4 mounts, 2,000 listeners | 255 MB |
| 10 mounts, 10,000 listeners | 1.16 GB |
| 64 mounts (the default maximum), 10,000 listeners | 1.74 GB |

The defaults (`max_listeners = 10000` and a 2 GiB budget) already hold the maximum of 64 mounts, so you only meet this check after raising limits, lowering the budget, or turning on dynamic mounts. If the sum is too big you will see something like:

```text
limits.retained_audio_budget: retained audio budget cannot cover admission reservations:
2 mount(s) and max_listeners = 10000 need about 1032 MiB but retained_audio_budget is 1024 MiB;
lower limits.max_listeners or raise limits.retained_audio_budget
```

Fix it by lowering `max_listeners`, or by raising `retained_audio_budget`. Both are restart settings.

> **Note: The budget is a ceiling, not a preallocation**
>
> Quikcast does not reserve this memory up front. Real memory use follows your audio: ring buffers fill as streams run and listeners connect. If you enable dynamic mounts (see "Streams and mounts"), the part of the budget your configured mounts and listeners do not use is what limits how many dynamic streams can exist at once.

The reservation counts what Quikcast promises, not process memory: the operating system, your proxy and the HLS store (below) are on top.

### Other budgets

These are separate and do not borrow from `retained_audio_budget`:

| Budget | Setting | Notes |
|---|---|---|
| Relay workers | `relay_allocation_budget` | At least 2 MiB per relay (up to 64 relays), counted even when a relay is disabled. |
| HLS | `[hls] allocation_budget`, `rendition_budget` | In-memory segments for all HLS streams. The per-rendition minimum is `8 × (max_segment_bytes + 128) + 4 × 262,144`. |

### Choosing a listener limit

Listeners cost outbound bandwidth:

```text
bandwidth ≈ listeners × bitrate
```

For example 1,000 listeners at 128 kbit/s is about **128 Mbit/s**. Check your host's real network capacity (and your provider's fair-use limits) before setting `max_listeners`. It is far better to refuse listeners cleanly than to let everyone's audio stutter.

Also remember file descriptors: allow more than `max_connections` open files (`LimitNOFILE` in systemd, `ulimit -n`, or `ulimits.nofile` in Docker). Plan for `max_connections` + 32 (administration) + about 128 spare, so about 12,200 for the defaults and 65,536 is a comfortable value.

Quikcast raises its own soft limit up to the hard limit at startup. If the hard limit is still too low, it logs a warning and lowers public admission to fit, rather than failing later. If the system runs out of descriptors anyway, `accept()` errors are logged and counted in `accept_errors_total`, accepting pauses briefly, and existing sources and listeners keep running. `quikcast --check` warns when the hard limit is below what `max_connections` needs.

### Fixed limits

Some limits are built in and have no setting:

| What | Limit |
|---|---|
| Request headers | 16 KiB and 64 fields |
| Configuration file | 128 KiB |
| Mounts | `limits.max_mounts` configured (64 by default, at most 1,024), plus dynamic mounts within the memory budget |
| Relays | 64, each with up to 8 upstreams |
| IP rule lists | 10,000 distinct entries each |
| User-Agent rule lists | 256 rules of 1–256 bytes |
| Country lists | 249 codes |
| Signed-link HLS entries | 64 |
| Console sessions | 128, one hour each by default (`ui.session_duration`) |
| Management request bodies | none allowed |
| Country database file | 128 MiB, 2 million records |

## Glossary

#### Admin address

The private listener (`admin_listen`, default `127.0.0.1:9090`). It serves health checks, metrics, the management API and the HLS ingest API. It must be a loopback address.

#### Backup stream

See fallback.

#### Drain

Refusing new work while letting current listeners and encoders finish. Used before a restart, and one-way until the process restarts. The console button is called **Stop accepting connections**.

#### Encoder

Also called a **source**. Software that captures and compresses audio and sends it to Quikcast: BUTT, Liquidsoap, FFmpeg.

#### Fallback

A backup mount that new listeners are attached to when their requested mount has no source. See "Backup streams (fallback)".

#### Generation

One run of a source on a mount. A reconnecting encoder starts a new generation. Listeners belong to a single generation.

#### HLS

HTTP Live Streaming. Audio delivered as many small files plus a playlist, favoured by browsers and phones. See "HLS for browsers and apps".

#### ICY metadata

The "now playing" text embedded in MP3 and AAC streams for players that ask for it.

#### Listener

Anyone playing a mount or an HLS stream.

#### Management API

The JSON API on the admin address, protected by a bearer token. See the reference (see "Management API").

#### Mount

One stream, identified by a URL path such as `/radio.mp3`. An encoder feeds it and listeners play it.

#### PROXY protocol

A small header that a TCP load balancer sends first to tell the server the real client address. See "HTTPS and proxies".

#### Public address

The `listen` address that listeners, encoders and HLS players connect to.

#### Reload

Applying configuration changes without a restart, by sending `SIGHUP`.

#### Master playlist

An HLS playlist that lists several versions (variants) of a stream at different bitrates. A relay follows one audio-only variant; see "Configuration reference".

#### Relay

Quikcast pulling a stream from elsewhere and publishing it on one of your mounts. See "Relay another station".

#### Rendition

One quality level (variant) of an HLS stream.

#### Ring

The in-memory buffer holding the most recent audio of a mount. New listeners start from it; listeners that fall out of it are dropped.

#### Secret file

A file containing a password, token or key, referenced from the config by path so the secret is not written in the config itself.

#### Signed URL

A link with an expiry and an HMAC signature made by your own application. See "Signed, expiring links".

#### Source

See encoder.

#### Trusted proxy

A proxy or load balancer you control, whose claims about the real listener address Quikcast believes. See "HTTPS and proxies".

---

# Part 6: Client libraries

## Client libraries

A client library wraps the "Management API" so your own code can read stats, list listeners, disconnect a source, ban an address or update a track title without writing HTTP calls by hand. Each library returns typed objects and raises a typed error for every API error code.

| Language | Package | Status |
|---|---|---|
| PHP (see "PHP client") | `quikcast/quikcast` | Covers the whole management API, source metadata updates, health and metrics |

More languages may follow. Until then, any language can call the "Management API" directly: it is plain HTTP with a Bearer token and JSON responses.

### What every client needs

- **The admin address.** The management API listens on `admin_listen`, which is loopback by default. Run your code on the same host, or reach it through a private proxy, a VPN or an SSH tunnel. Allowing remote access is covered in Remote management (see "Configuration reference").
- **A management token.** Enable `[management]` and read the token from the secret file. Keep it out of source code:

  ```sh
  export QUIKCAST_ADMIN_URL='http://127.0.0.1:9090'
  export QUIKCAST_TOKEN="$(cat secrets/management-token)"
  ```

- **Source credentials, only for metadata updates.** Changing the "now playing" title is a source operation on the streaming port. It uses the mount's encoder username and password, not the management token.

### What a client covers

| Area | Operations |
|---|---|
| Server | Info, capabilities and limits, drain |
| Stats and history | Counters, per-minute listener history |
| Mounts and sources | List and inspect mounts, inspect or disconnect a source |
| Listeners | Page through a mount's listeners, disconnect one |
| Relays | List, inspect, restart, stop |
| HLS | Streams, renditions, directory-stream listener sessions |
| Bans and revocations | Ban an address or range, revoke one signed link |
| Source metadata | Update artist and title |
| Monitoring | Health probes and Prometheus text |

### Versions

A client is released separately from the server and reads only the fields it knows, so an older client keeps working against a newer server. A new server feature may need a newer client. Each library's changelog says which server version it was checked against.

## PHP client

`quikcast/quikcast` is a PHP library for the "Management API". It returns typed read-only objects, maps every API error code to its own exception and builds on [ElliePHP HttpClient](https://github.com/ElliePHP/HttpClient) (Symfony HttpClient).

Source and issues: [github.com/RadioPlatform/quikcastphp](https://github.com/RadioPlatform/quikcastphp).

### Install

It needs PHP 8.4 or newer.

```sh
composer require quikcast/quikcast
```

### Connect

Give the client the admin address and the management token. Read the token from the environment or a secret store, never from source code.

```php
use Quikcast\QuikcastClient;

$client = QuikcastClient::create('http://127.0.0.1:9090', getenv('QUIKCAST_TOKEN'));

$server = $client->server()->get();
echo $server->state->value; // accepting | draining | shutting_down

$stats = $client->stats()->get();
printf("listeners=%d sources=%d\n", $stats->activeListeners, $stats->activeSources);

foreach ($client->mounts()->list() as $mount) {
    echo $mount->path.' '.($mount->source?->track->title ?? '(no source)').PHP_EOL;
}
```

The management API is on `admin_listen`, which is loopback by default. See client libraries for how to reach it from another host.

### Resources

One method group per part of the API:

| Call | What it does |
|---|---|
| `server()` | Server info, capabilities, limits, `drain()` |
| `stats()` | Counters |
| `mounts()` | List and inspect mounts |
| `sources()` | Inspect or disconnect a mount's source |
| `listeners()` | Page, iterate, get or disconnect listeners |
| `relays()` | List, inspect, restart, stop |
| `hls()` | Streams, renditions and directory-stream sessions |
| `bans()` | List, create and lift bans |
| `revocations()` | List, revoke and restore signed links |
| `history()` | Listener history |
| `metadata()` | Update the track title (source credentials) |
| `metrics()` | Prometheus text |
| `health()` | Liveness and readiness probes |

### Listeners

Listener lists are paged. Use one page, walk every page lazily, or collect them all.

```php
// One page.
$page = $client->listeners()->page('/radio.mp3', limit: 100);

// Every page, one at a time.
foreach ($client->listeners()->paginate('/radio.mp3') as $page) {
    foreach ($page->items as $listener) {
        echo $listener->id.PHP_EOL;
    }
}

// Everything at once. Mount registries are bounded, so this is fine for admin tools.
$all = $client->listeners()->all('/radio.mp3');

// Disconnect one listener.
$client->listeners()->disconnect('0123456789abcdef0123456789abcdef');
```

### Sources

```php
// Null when the mount exists but nothing is connected.
$source = $client->sources()->get('/radio.mp3');

// Pass the generation so you never disconnect a newer source by mistake.
if ($source !== null) {
    $client->sources()->disconnect('/radio.mp3', $source->generation);
}
```

### Relays

Restart and stop return a snapshot straight away (HTTP 202). Pass the revision you read, and poll `get()` until the state settles.

```php
foreach ($client->relays()->list() as $relay) {
    $updated = $client->relays()->restart($relay->mount, $relay->revision);
    echo $updated->state->value.PHP_EOL;
    // $client->relays()->stop($relay->mount, $relay->revision);
}
```

### HLS

```php
foreach ($client->hls()->listStreams() as $stream) {
    foreach ($client->hls()->listRenditions($stream->name) as $rendition) {
        echo $rendition->name.' '.$rendition->format.PHP_EOL;
    }
}
```

A stream served from a directory (see "HLS for browsers and apps") has `$stream->isDirectory()` set, plus listener and request counters. List its sessions with `$client->hls()->listeners('radio')`.

### Bans and link revocation

Both are held in memory on the server: they are lost on restart and not shared between replicas (see "Primary and replica servers"), so call each node.

```php
$result = $client->bans()->create('203.0.113.0/24', ttlSeconds: 86400, reason: 'scraper', kick: true);
echo $result->kickedListeners;

foreach ($client->bans()->list() as $ban) {
    echo $ban->ip.' '.$ban->expiresInSeconds.PHP_EOL;
}
$client->bans()->lift('203.0.113.0/24'); // the same text it was created with

// Stop one signed link before it expires. The sig and expires come from the link itself.
$client->revocations()->revoke($sig, $expires);
$client->revocations()->restore($sig);
```

See "Signed, expiring links".

### Listener history

```php
$history = $client->history()->get();                           // whole server, last 60 minutes
$history = $client->history()->get('/radio.mp3', minutes: 180); // one mount, 1 to 1440 minutes

echo $history->peakListeners24h;
echo $history->uniqueListenersEstimate24h; // an estimate, about 3% error
foreach ($history->minutes as $m) {
    echo $m->startMs.' '.$m->peakListeners.PHP_EOL;
}
```

History is kept in memory and resets on restart.

### Policies and counters

`MountInfo` and `ServerInfo` expose the access rules in effect (`access`, `sourceAccess`, `listenerAuth`, `hlsListenerAuth`), the fallback target, listener capacity, disconnect counters and an embedded relay snapshot. Rule contents and secret paths are never included. `ServerInfo::hasCapability()` checks the list of features the server advertises.

### Drain

```php
$client->server()->drain(); // one way until restart; safe to repeat
```

### Update the track title

This is not a management call. It runs on the streaming port with the mount's **encoder** username and password. Pass the listen address, not the admin address.

```php
$client->metadata()->updateSong(
    'http://127.0.0.1:8000', // listen address
    '/radio.mp3',
    'source',                // the mount's encoder username
    $sourceSecret,           // the mount's encoder password
    'Artist - Title',
);

// Or artist and title separately:
$client->metadata()->updateTrack('http://127.0.0.1:8000', '/radio.mp3', 'source', $sourceSecret, 'Title', 'Artist');
```

### Metrics and health

Both are on the admin address and need no token.

```php
$text = $client->metrics()->text();   // Prometheus text

$client->health()->live();   // true while serving
$client->health()->ready();  // false while draining
```

### Errors

Every API error maps to its own exception. They all extend `Quikcast\Exception\QuikcastException`, which carries `->statusCode`, `->errorCode` and, for a 405, `->allow`.

| HTTP | Code | Exception |
|---|---|---|
| 401 | `unauthorized` | `UnauthorizedException` |
| 400 | `invalid_request` | `InvalidRequestException` |
| 400 | `invalid_pagination` | `InvalidPaginationException` |
| 404 | `mount_not_found` | `MountNotFoundException` |
| 404 | `listener_not_found` | `ListenerNotFoundException` |
| 404 | `hls_not_found` | `HlsNotFoundException` |
| 404 | `relay_not_found` | `RelayNotFoundException` |
| 404 | `ban_not_found` | `BanNotFoundException` |
| 404 | `revocation_not_found` | `RevocationNotFoundException` |
| 404 | `endpoint_not_found` | `EndpointNotFoundException` |
| 405 | `method_not_allowed` | `MethodNotAllowedException` |
| 409 | `source_not_connected` | `SourceNotConnectedException` |
| 409 | `conflict` | `ConflictException` (stale generation or revision) |
| 507 | `ban_list_full` | `BanListFullException` |
| 507 | `revocation_list_full` | `RevocationListFullException` |
| 503 | `server_draining` | `ServerDrainingException` |
| 500 | `internal_error` | `InternalErrorException` |

```php
use Quikcast\Exception\ConflictException;
use Quikcast\Exception\MountNotFoundException;

try {
    $client->sources()->disconnect('/radio.mp3', $generation);
} catch (ConflictException $e) {
    // The source changed. Read it again and retry.
} catch (MountNotFoundException $e) {
    // Unknown mount.
}
```

Network failures, timeouts and malformed JSON throw `TransportException`. Bad arguments (a `limit` outside 1 to 200, a malformed listener ID, an empty mount) throw `InvalidArgumentException` before anything is sent.

### Mount paths

Pass `/radio.mp3` or `radio.mp3` or `nested/radio.mp3`. The client adds the leading slash and encodes each segment, so nested mounts never collide with reserved paths.

---

# Appendix A: config/quikcast.reference.toml (every option, commented)

```toml
# Quikcast configuration reference: EVERY option, with its default.
#
# This file is documentation, not a working config: several options exclude each
# other (for example a relay owns its mount, so it has no encoder), and some
# need files you must create. Copy only what you use. For a starting point use
# config/quikcast.example.toml.
#
# Rules that apply everywhere
#   * Unknown keys are rejected at startup (typos cannot be silently ignored).
#   * Every *_file path resolves relative to THIS file's directory.
#   * Secrets: 16-512 bytes; one final newline is stripped. Usernames: 1-64
#     ASCII graphic bytes, no whitespace or ":". Use distinct secrets per scope.
#   * Validate without starting:   quikcast --config quikcast.toml --check
#   * Reload with SIGHUP what the table below marks "reload"; everything else
#     needs a restart. A failed reload keeps the active configuration.
#   * QUIKCAST_CONFIG=PATH is an alternative to --config.

# ---------------------------------------------------------------------------
# Listeners and logging                                       (restart)
# ---------------------------------------------------------------------------
listen = "127.0.0.1:8000"       # Public: listeners, encoders, HLS. Use 0.0.0.0:8000 in Docker.
admin_listen = "127.0.0.1:9090" # Health, metrics, management API. Loopback unless [management] allow_remote = true.
log_filter = "quikcast=info"    # tracing filter. QUIKCAST_LOG overrides it. Unix only.

# ---------------------------------------------------------------------------
# Native HTTPS on the public listener                         (reload certs; restart to enable/disable)
# ---------------------------------------------------------------------------
# Omit to serve plain HTTP (terminate TLS in a proxy instead).
# [tls]
# cert_file = "secrets/tls/fullchain.pem" # PEM chain, leaf first, up to 8 certs, <= 256 KiB
# key_file = "secrets/tls/privkey.pem"    # PEM private key, <= 64 KiB

# ---------------------------------------------------------------------------
# Real client addresses behind proxies                        (reload)
# ---------------------------------------------------------------------------
# [trusted_proxies]
# ips = ["127.0.0.1", "10.0.0.0/8", "2001:db8::/32"] # up to 64 IPs/CIDRs; XFF is honoured only from these
# providers = ["cloudflare"]  # bundled Cloudflare ranges; trusts CF-Connecting-IP from direct CF peers
# proxy_protocol = false      # true: public peers (must match ips/providers) send PROXY v1/v2 first
# Also from these peers only: "X-Forwarded-Prefix: /28000" makes the /console console emit URLs, redirects and the
# cookie Path under that prefix (for a proxy that strips it). Must start with "/", no trailing "/", "//" or "..".

# ---------------------------------------------------------------------------
# Management API (private, on admin_listen)                   (reload)
# ---------------------------------------------------------------------------
# Fail-closed: without this section every /api request is rejected.
# [management]
# token_file = "secrets/management-token" # exactly ONE of token_file / token
# token = "inline-machine-secret"         # prefer token_file
# Remote management (e.g. a hosting panel on another host). Default: off.
# allow_remote = false  # true: admin_listen may bind a non-loopback address, e.g. "0.0.0.0:8001".
#                       # RESTART to change. Requires a >= 32-byte token; failed auths are throttled
#                       # per client (10 per 60 s -> 429). /health and /metrics on that port stay open.
# allowed_ips = []      # (reload) peer IP/CIDR allow-list, e.g. ["203.0.113.10"]; empty = any peer with the token
# tls = false           # (reload) serve the admin listener over TLS with the top-level [tls] certificate.
#                       # Without TLS the token travels in clear text: use a TLS proxy, VPN or firewall.

# ---------------------------------------------------------------------------
# Icecast-compatible admin API                                          (reload)
# ---------------------------------------------------------------------------
# Lets Icecast control panels and monitoring tools poll Quikcast as a remote Icecast server:
# /admin/stats, /admin/listmounts, /admin/listclients (listener IPs) and /admin/killclient
# on the public listener. Off unless this section exists. Do not expose it to the internet.
# [icecast_admin]
# username = "admin"                          # default "admin"
# password_file = "secrets/icecast-admin"     # exactly ONE of password_file / password, 16..512 bytes
# password = "inline-machine-secret"          # prefer password_file

# ---------------------------------------------------------------------------
# Operator console                                            (reload)
# ---------------------------------------------------------------------------
# [ui]                         # [console] is accepted as an alias
# enabled = false
# mode = "private"              # "private": login + controls at /console. "public": status page at /. "both": the two together
# username = "admin"
# password_file = "secrets/ui-password"
# secure_cookie = true          # keep true behind HTTPS
# session_duration = 3600       # seconds a console sign-in lasts (60-2592000)
# public_mounts = ["*"]         # status page mounts: omit = all (public/both) or none (private); ["*"] = all incl. dynamic; or a list of configured paths
# public_url = "https://radio.example.com" # address for the console's copy-URL and test-play links

# ---------------------------------------------------------------------------
# Capacity limits                                             (restart)
# ---------------------------------------------------------------------------
# Values shown are the defaults. Change only what you must; startup rejects
# combinations whose memory budgets do not fit.
# [limits]
# ring_bytes = 4194304               # per-mount live audio ring
# ring_entries = 4096
# join_bytes = 65536                 # what a new listener is caught up with
# flac_initialization_bytes = 65536  # native FLAC marker + metadata incl. artwork
# flac_frame_bytes = 1048576         # one unresolved native FLAC frame
# max_connections = 12000            # public sockets (admin has its own reserve of 32)
# max_handshakes = 128               # connections still sending request headers / TLS
# max_mounts = 64                    # 1-1024 static mounts; raise retained_audio_budget with it
# max_listeners = 10000              # all mounts together
# listeners_per_mount = 10000        # default per mount (0 = up to max_listeners)
# retained_audio_budget = 2147483648 # bytes of retained audio, all mounts
# relay_allocation_budget = 33554432 # 2 MiB per relay, at most 64 relays
# header_timeout_ms = 5000
# source_timeout_ms = 10000          # idle encoder
# write_timeout_ms = 10000           # stalled listener
# shutdown_timeout_ms = 10000

# ---------------------------------------------------------------------------
# Mounts (encoder-fed streams). 1 to limits.max_mounts (64).         (add/remove and credentials reload)
# ---------------------------------------------------------------------------
[[mounts]]
path = "/radio.mp3"                  # canonical: leading "/", no trailing "/", no duplicates
username = "source"                  # default "source"
secret_file = "secrets/radio-source" # exactly ONE of secret_file / secret
# secret = "0123456789abcdef"        # inline alternative (prefer secret_file)
# fallback = "/backup.mp3"           # another configured mount; chains up to 8 long
# fallback_when_full = true          # at listener_limit, serve new listeners from the fallback (needs fallback)
# listener_limit = 500               # omit: inherit limits.listeners_per_mount; 0: unlimited locally (restart)
# charset = "ISO-8859-1"             # charset of metadata updates for this mount (default UTF-8)
# hide_listener_count = true         # keep this mount's listener count off the public status page
# max_listener_duration = 14400      # seconds a listener may stay connected; 0/omit: unlimited
# intro = "audio/station-id.mp3"     # MP3/AAC clip played to each new listener (same format as the stream)

# Listener authentication for this mount: signed, expiring URLs.
# [mounts.listener_auth]
# type = "signed_url"                # or "none" (default, public)
# secret_file = "secrets/radio-signing-key"
# max_ttl_seconds = 86400            # longest accepted expiry
# clock_skew_seconds = 0

# Listener restrictions for this mount (ANDed with the global [access]).
# [mounts.access]
# ip_allow = ["203.0.113.0/24"]
# ip_allow_file = "lists/allow.txt"  # file must contain at least one rule
# ip_deny = ["198.51.100.7"]
# ip_deny_file = "lists/blocked.txt" # empty deny file is fine
# user_agent_allow = ["prefix:VLC/"] # rules: "exact:X", "prefix:X", "substring:X" (case-sensitive, <=256 bytes)
# user_agent_deny = ["exact:bad-monitor"]
# countries_allow = ["GH", "NG"]     # ISO 3166 alpha-2
# countries_deny = ["XX"]

# Which IPs may connect an ENCODER to this mount (credentials still apply).
# [mounts.source_access]
# ip_allow = ["127.0.0.1", "::1"]
# ip_allow_file = "lists/encoders.txt"
# ip_deny = []
# ip_deny_file = "lists/blocked.txt"

# A second mount; each [[mounts]] header starts a new one and its sub-tables follow it.
# [[mounts]]
# path = "/backup.mp3"
# secret_file = "secrets/backup-source"

# ---------------------------------------------------------------------------
# Global listener restrictions                                (reload)
# ---------------------------------------------------------------------------
# IP/CIDR lists hold up to 10,000 distinct rules (inline + file together).
# File format: one IP or CIDR per line, "#" comments and blank lines ignored.
# [access]
# ip_allow = []
# ip_allow_file = "lists/allow.txt"
# ip_deny = ["203.0.113.0/24"]
# ip_deny_file = "lists/blocked.txt"
# user_agent_allow = []              # up to 256 rules
# user_agent_deny = ["exact:blocked-client"]
# countries_allow = []               # up to 249 codes
# countries_deny = []
# geoip_database = "/etc/quikcast/GeoLite2-Country.mmdb" # omit: use the embedded database

# ---------------------------------------------------------------------------
# Dynamic continuous sources (encoders may create mounts)     (reload credentials; restart for capacity)
# ---------------------------------------------------------------------------
# [sources]
# allow_dynamic_mounts = false       # true requires the credentials below
# username = "source"
# secret_file = "secrets/dynamic-source" # or secret = "..."
# [sources.defaults]                 # station metadata for sources that send none
# name = "Quikcast Stream"
# description = ""
# genre = ""
# url = ""
# public = false

# ---------------------------------------------------------------------------
# Continuous relays (pull an upstream into a configured mount)  (reload; max 16)
# ---------------------------------------------------------------------------
# The mount must exist under [[mounts]]; the relay then owns it (no encoder).
# [[relays]]
# mount = "/radio.mp3"
# enabled = true
#
# Choose exactly ONE of url / urls / upstreams:
# url = "https://upstream.example/live"
# urls = ["https://primary.example/live", "https://backup.example/live"] # 1-8, ordered, sticky backups
# upstreams = [                                                         # 1-8, per-entry credentials
#   { url = "https://primary.example/live" },
#   { url = "https://backup.example/live", username = "other", secret_file = "secrets/backup-password" },
# ]
#
# username = "remote-user"           # Basic auth upstream. With url/urls: used for all.
# secret_file = "secrets/upstream-password" # With upstreams: default for entries with none of their own.
#
# charset = "ISO-8859-1"             # charset of the upstream's ICY titles (default UTF-8)
# on_demand = false                  # true: connect upstream only while someone listens
# idle_timeout_ms = 30000            # on_demand: disconnect after this long with no listeners
# wake_wait_ms = 8000                # on_demand: how long the first listener waits for audio
# max_redirects = 0                  # 0: a 3xx fails the attempt; 1-8: follow; credentials never cross origins
# hls_variant = "highest"           # audio-only HLS master playlist: "highest" or "lowest" bitrate
# connect_timeout_ms = 10000
# header_timeout_ms = 5000
# audio_timeout_ms = 10000
# initial_backoff_ms = 1000
# max_backoff_ms = 60000
# stable_connection_ms = 30000       # a connection this long resets backoff
# jitter_percent = 20                # 0-50

# ---------------------------------------------------------------------------
# Primary and replica servers                                 (reload)
# ---------------------------------------------------------------------------
# On the server your encoders use: let replicas read its stream list (GET /api/streams).
# [primary]
# username = "replica"
# secret_file = "secrets/replica-password" # or secret = "...". 16-512 bytes
# share = ["/radio.mp3"]             # omit: every public mount (signed-link mounts are never listed)
# redirect_after = 200               # send listeners to replicas once a mount has this many; 0: all; omit: never
#
# On another server: copy every stream of the primary. No [[mounts]] needed there.
# [replica]
# primary = "https://radio.example.com"   # address only, no path
# username = "replica"
# secret_file = "secrets/primary-password" # or secret = "..."
# refresh_secs = 30                  # 5-3600, how often the stream list is checked
# on_demand = true                   # connect to the primary only while someone listens
# max_streams = 16                   # 1-48, also bounded by limits.max_mounts, 64 relays and limits.relay_allocation_budget
# only = ["/radio.mp3"]              # omit: everything the primary lists
# public_url = "https://eu.example.com"   # this replica's own address; lets the primary redirect listeners here

# ---------------------------------------------------------------------------
# Independent MPEG-TS / packed-audio / fMP4 HLS               (reload credentials, CORS, auth; restart for capacities)
# ---------------------------------------------------------------------------
# [hls]
# username = "hls"
# secret_file = "secrets/hls-ingest" # or secret = "...". MUST differ from every mount secret
# cors_origin = "https://player.example" # omit: no CORS
# max_streams = 16
# renditions_per_stream = 8
# max_renditions = 64
# max_segment_bytes = 2097152        # safety ceiling, not an expected size
# max_segments = 1024
# max_uploads = 4
# rendition_budget = 134217728
# allocation_budget = 536870912
# directory = "/var/lib/radio/hls"            # serve HLS written by an external muxer
# directory_listener_window_secs = 60        # window for unique-IP active_listeners
# directory_session_timeout_secs = 30        # window for GET /api/hls/STREAM/listeners sessions
# Signed-URL protection per HLS stream (up to 64; key is "/hls/STREAM"):
# [hls.listener_auth."/hls/private"]
# type = "signed_url"
# secret_file = "secrets/hls-private-signing-key"
# max_ttl_seconds = 86400
# clock_skew_seconds = 0
```

---

# Appendix B: config/quikcast.example.toml (short starting point)

```toml
# Quikcast starter configuration.
# Secret file paths are relative to this file. Check it without starting:
#   quikcast --config quikcast.toml --check

# Where listeners and encoders connect. Use "0.0.0.0:8000" to accept outside connections
# (or run: qc listen 0.0.0.0:8000). For HTTPS see: qc tls --domain radio.example.com
listen = "127.0.0.1:8000"

# Health, metrics and the management API. Keep this private.
admin_listen = "127.0.0.1:9090"

# One stream. Encoders connect to /radio.mp3 with this username and password.
[[mounts]]
path = "/radio.mp3"
username = "source"
secret_file = "secrets/radio-source"

# Everything else is optional and off until you add it: HTTPS, fallback streams,
# relays, access limits, the operator console, the management API and HLS.
# Every option, commented and ready to copy: config/quikcast.reference.toml in the
# repository, or https://quikcastdocs.streamafrica.net/reference/configuration
```

---

# Appendix C: config/quikcast.docker.toml (container starting point)

```toml
# Quikcast — Docker / Dokploy example.
# Mount at /etc/quikcast/quikcast.toml with secrets in /etc/quikcast/secrets/.
# Secret paths below resolve relative to this file, so
#   secret_file = "secrets/radio-source" -> /etc/quikcast/secrets/radio-source
#
# DOKPLOY NOTES
# - listen MUST be 0.0.0.0:8000 in the container, otherwise the port mapping
#   has nothing to forward to. The repo example defaults to 127.0.0.1, which
#   only works for bare-metal local runs.
# - admin_listen MUST stay 127.0.0.1:9090. Startup validation in src/config.rs
#   rejects a non-loopback admin binding, and /health/live, /health/ready and
#   /metrics only exist on that listener. Do NOT publish 9090 in Dokploy;
#   the Dockerfile HEALTHCHECK probes it from inside the container.
# - Behind Dokploy/Traefik, set trusted_proxies if you need real client IPs:
#     [trusted_proxies]
#     ips = ["10.0.0.0/8"]   # adjust to your Dokploy network
#   Or providers = ["cloudflare"] when Cloudflare sits in front. A TCP (layer-4)
#   proxy can instead send PROXY protocol: add proxy_protocol = true there.
# - Let Traefik terminate TLS, or add [tls] with cert_file/key_file under secrets/.
# - Validate before deploying: docker run --rm -v ...:/etc/quikcast quikcast --check
# - Set the container's nofile ulimit (docker-compose.yml does: 65536). Each listener uses one
#   file descriptor; the default max_connections of 12000 needs about 12,200. Check the startup
#   log line "open-file limit" and the open_files / open_files_limit metrics.
# - [limits] defaults are fine for most stations; see config/quikcast.reference.toml.

listen = "0.0.0.0:8000"
admin_listen = "127.0.0.1:9090"
log_filter = "quikcast=info"

# [trusted_proxies]
# ips = ["10.0.0.0/8"]

# [management]
# token_file = "secrets/management-token"

# [ui]
# enabled = true
# mode = "private"
# username = "admin"
# password_file = "secrets/ui-password"
# public_mounts = ["*"]  # omit: every mount on a public page; or list configured paths

[[mounts]]
path = "/radio.mp3"
username = "source"
secret_file = "secrets/radio-source"
# listener_limit = 10000 # Omit to inherit limits.listeners_per_mount.
```
