Library-first
SQLite remembers file state across restarts, so large libraries do not start from zero after every deployment.
Install it, configure safe encoding rules, operate a multi-node cluster, automate it through the JSON API, and recover confidently when something goes wrong.
Snacks scans video and music libraries, evaluates each file against your target codec and bitrate rules, builds an FFmpeg command, validates the result, and keeps the output only when it satisfies the configured policy. It can run as a web container on a NAS, as an Electron desktop application, or as a distributed cluster.
SQLite remembers file state across restarts, so large libraries do not start from zero after every deployment.
NVIDIA, Intel, AMD, Apple VideoToolbox, and CPU paths are selected according to platform and configured device slots.
Retries, fallbacks, persistent logs, output verification, and cluster reassignment protect long-running sweeps.
services:
snacks:
image: derekshreds/snacks-docker:latest
container_name: snacks
network_mode: host
volumes:
- /path/to/media:/app/work/uploads
- /path/to/snacks/logs:/app/work/logs
- /path/to/snacks/config:/app/work/config
environment:
- ASPNETCORE_ENVIRONMENT=Production
- SNACKS_WORK_DIR=/app/work
- FFMPEG_PATH=/usr/lib/jellyfin-ffmpeg/ffmpeg
- FFPROBE_PATH=/usr/lib/jellyfin-ffmpeg/ffprobe
restart: unless-stopped
http://NAS-IP:6767.
Snacks configures its listener explicitly, so the generic ASP.NET variables
(HTTP_PORTS, DOTNET_URLS) are ignored. How to move off
6767 depends on the network mode:
ports: mappings under network_mode: host. Set the port through
the one variable Snacks honors:
environment:
- ASPNETCORE_URLS=http://0.0.0.0:7070
Keep the 0.0.0.0 host so the UI and cluster peers can reach it over the LAN.
network_mode: host and map the
host port onto the container's default instead — no environment variable needed:
ports:
- "7070:6767"
Note that UDP broadcast discovery for clusters does not work across a bridge network;
use manual node URLs, or stay on host networking.
Cluster nodes announce whatever port they actually bound, so a custom port is safe with
discovery. The UDP discovery port 6768 itself is fixed.
Install the Windows or Apple Silicon macOS build, launch Snacks, and use
Browse Library. The desktop wrapper starts the ASP.NET backend
locally and bundles or points it at FFmpeg. Cluster mode intentionally changes the
backend from localhost-only to a LAN listener. There is no port to configure: the
wrapper prefers 6767 and automatically starts on another free port when
it is taken.
A manual process action is explicit: it can force a mux pass even when the source is already at the video target, allowing audio/subtitle rules and output-container normalization to be applied. Automatic scanning uses the normal eligibility rules.
| State | Meaning | What happens next |
|---|---|---|
Pending | Waiting for a local or remote slot. | Processed according to priority and queue policy. |
Uploading | Source is moving to a worker. | Becomes Processing after transfer and verification. |
Processing | FFmpeg is running. | Progress and log lines arrive through SignalR. |
Downloading | Cluster output is returning to the master. | The master validates and places it. |
Completed | Validated output was kept. | Terminal. |
NoSavings | Output was valid but not worth keeping under the size policy. | Terminal unless explicitly retried. |
Failed | Retry paths were exhausted. | Inspect logs, adjust settings, then retry. |
Stopped | Removed for now. | May reappear on a later automatic scan. |
Cancelled | Explicitly marked “do not reprocess.” | Only a manual selection queues it again. |
| Area | Key choices | Guidance |
|---|---|---|
| Mode | Transcode, mux-only, or hybrid | Hybrid is useful when track/container cleanup matters even for already-efficient video. |
| Video | H.264, HEVC, AV1; bitrate; hardware encoder | Choose compatibility first. AV1 may be slow or unsupported on older playback devices. |
| Resolution | Never, cap at target, always; fixed frame; FPS cap | A fixed frame overrides normal downscale behavior and adds padding when required. |
| HDR | Preserve or tone-map to SDR | Validate color and brightness with real HDR sources before a batch. |
| Audio | Languages, original tracks, output profiles | Use ISO language preferences and verify files with missing/incorrect language tags. A source track that already matches an output (same codec and layout) is copied, not re-encoded, at any bitrate. Optional: Re-encode above the output bitrate (a known bitrate more than 5% above the output's; unknown bitrates still copy) and AAC profiles to copy (e.g. LC only, so HE-AAC is re-encoded). |
| Subtitles | Languages, sidecars, OCR, image pass-through, SDH exclusion | PGS/VobSub OCR needs Tesseract data and is more expensive than text subtitle handling. Sidecars can be limited to the best track per language (full over forced, non-SDH over SDH, the default track, text over image, then the larger track), named with 2- or 3-letter language tags, and skipped for languages that already have a sidecar. |
| Output | Container, output directory, scratch directory, original replacement, hvc1 tagging | Scratch should have enough free space for source-scale temporary files. With an MP4 output, Tag HEVC as hvc1 for Apple devices gives an HEVC file tagged hev1 a retag-only remux (video copied, never re-encoded). The tag is read when a file is probed (scan, Process Item, Process Directory), not stored in the library database, so run Process Directory on an existing library to retag it. Advanced Video rules can match the tag too (field Codec tag, e.g. a MuxOnly rule for hev1). |
| Reliability | Retry, log retention, deep-verification budget, output checks | Use a nonzero verification budget to continuously sample older library entries. Before any output replaces or joins its original, Check Output Duration (on by default) requires its duration within 0.5% of the source's (2 s for short files) and the optional Check Output Size a size between 5% and 101% of the source's; a failing output is deleted, the original kept, and the job fails with the reason. An output whose duration cannot be read fails; when the source's duration cannot be read, the durations are not compared and the job log says so; a shorter output whose missing tail is black in the source passes, as the encode-time truncation check allows. |
| Queue | Bitrate-first or newest-first | Newest-first is best when recent downloads should jump ahead of a backlog. |
Add und (Undetermined) to either Languages to Keep list
when you want to retain audio or subtitle tracks whose language tag is missing, empty,
und, mul, zxx, or otherwise unrecognized. Its
position in the list controls output order like any other language. A recognizable
language tag or a language-bearing title still wins, so an und-tagged track
titled “English SDH” is treated as English rather than undetermined. Leaving the keep
list empty continues to keep all tracks.
Advanced Video is an optional layer under Settings → Video. It is off by default and upgrades never change it: until you enable it, existing settings, presets, watched folders, skip decisions, and FFmpeg behavior remain unchanged. Enable it only after creating and validating at least one profile. Audio, subtitles, container, paths, and file handling continue to come from the ordinary settings; profiles are deliberately video-only.
The panel is organized as three numbered steps that mirror how a decision actually happens: a decision flow of plain-language rule cards every video falls through top to bottom (the first match wins — visibly), the encoding recipes those rules pick (recipes are the UI name for video profiles), and a live library impact preview that runs the staged, unsaved flow against every video Snacks knows about and shows exactly how many files each rule catches and what would happen to them — before anything is applied.
A recipe (video profile) selects H.264, HEVC, or AV1; automatic or one exact detected encoder; bitrate, quality, or custom rate control; preset/speed, threads, pixel format, GOP, codec profile/level, transformations, extra filters, guarded options, and output retention. The editor shows the FFmpeg video arguments the recipe generates as you type.
Enabled rules run top to bottom and the first match wins. Each card reads as a sentence — “If the codec is not av1 and the resolution class is 2160p+ → encode with AV1 4K” — with a live count of the library files it catches. A rule uses a flat All or Any condition list; there are no scripts, expressions, or nested condition trees.
The impact section is read-only: it never queues, re-evaluates, or saves anything. It applies the same shared resolver used by scanning and dispatch — including per-folder policies — to every tracked video and buckets the outcomes with example files, current disk usage, and how many files in each bucket were already processed, so a mistake is visible as a wrong-looking bar instead of a surprise batch of jobs. Bitrate recipes also show an approximate output size (target × duration); quality and custom recipes deliberately show no forecast, because their size genuinely depends on content. A search box answers "what happens to this file" by name, and once encodes complete, a Measured so far strip shows each recipe's real jobs, savings, and average output bitrate next to the forecast. Very large libraries are analyzed as a uniform random sample beyond 20,000 videos and labeled as such.
Applying a policy only changes future decisions. Files already in the catalog keep their current status until Re-evaluate runs — the impact panel says so and offers the button right after an apply. Rules the flow can never reach are flagged inline ("never reached — an earlier rule always claims these files first") by a conservative static analysis that only reports what it can prove.
A policy exports as a plain snacks-video-policy.json file and imports on
any Snacks instance; imports arrive as a staged draft with fresh internal ids and
nothing applies until Validate & Apply. The current draft can also be saved as a
named template that appears alongside the built-in quick-start cards. Exact-encoder
recipes may name any adapter-known encoder — including ones no connected node
advertises yet, labeled "not detected yet" — so a policy can be written today for
hardware that joins the cluster tomorrow.
Conditions can inspect normalized codec aliases, width, height, short-edge resolution
class (SD, 720p, 1080p, 1440p, or 2160p+), video bitrate, file size, duration, pixel
format, derived bit depth, HDR, and 4K. Unknown values match only
IsUnknown; numeric ranges include both endpoints.
| Action | Behavior |
|---|---|
UseSimpleSettings | Runs the established codec/bitrate/filter/mux skip ladder unchanged. |
TranscodeWithProfile | Forces video re-encoding with the complete selected profile, even when legacy bitrate checks would skip. |
MuxOnly | Copies video and runs only applicable container, audio, and subtitle work; files with no mux work remain skipped. |
Skip | Skips the entire job, including mux-only work. |
The encoder picker is populated from the configured FFmpeg binary and connected workers. An exact encoder is never remapped or replaced by a retry fallback. If no local or protocol-compatible worker advertises that exact name on the assigned device, the job remains Pending and shows why. Older workers can still run Simple jobs, but cannot receive resolved Advanced plans.
Each custom row stores one option and at most one literal value token. Encoder-private
controls such as -aom-params are allowed and appended after generated video
settings so an intentional duplicate wins with a warning. Inputs, outputs, maps,
muxers, audio/subtitle controls, progress/report controls, and replacement filtergraphs
are rejected. Additional filters belong in the dedicated ordered single-chain field.
FFmpeg is started with an argument vector, never through a shell; the displayed command
is only a readable preview.
The fastest way in is the Quick start gallery at the top of the Advanced Video panel. Each template stages a complete working policy — profiles, rules, and default action — and immediately shows its validation result and the FFmpeg arguments it would generate. Nothing is saved until you press Validate & Apply, so a template is also a safe way to explore how profiles and rules fit together before building your own.
-aom-params rows. Requires an FFmpeg build with libaom.The expert template stages all of the following in one click; the same policy can be built by hand:
libaom-av1, then choose Quality.yuv420p10le, GOP 300, and Always Keep.-aom-params as separate guarded rows; use Validate Preview to inspect exact tokens.codec is not AV1 plus resolutionClass is 2160p+ and select a 4K profile.
A complete importable block for that scenario lives at
examples/advanced-video-policy.json. Full-app user presets include this
block. Applying a built-in Simple preset disables Advanced Video without deleting its
profiles or rules, so it can be turned back on later.
Snacks stages output separately from the source, validates the result, and only then performs final placement. Encoding never writes into the source file in place. Keep Replace original files disabled until the chosen settings have been tested with the playback clients and media types that matter to you.
[snacks] is treated as previously produced output and is not automatically fed back into the pipeline.| Configuration | Result |
|---|---|
| No output directory; replacement off | Movie [snacks].mkv is placed beside the original, which remains untouched. |
| Output directory; replacement off | The tagged output is kept in that directory and the original stays in place. |
| Scratch/encode directory configured | Temporary output is created there, then moved to the requested final destination after validation. |
| Replacement on | The validated output is moved into the source directory with the [snacks] tag removed; replacement happens only during final placement. |
| Music: Delete original file after success on | Works like video replacement: the output drops the [snacks] tag and replaces the source in its own folder, under the source's name; a music output directory only holds the encode until then. Music always follows its own output-directory and delete settings, including for cluster encodes; the video Replace original files toggle does not apply to it. |
Sidecar files produced during processing move with the output. A stale tagged output
left by an interrupted attempt is removed before FFmpeg starts again. If an ordinary
encode is not smaller than its source, Snacks discards it as NoSavings;
intentional remuxes, explicitly configured audio-output growth, and Advanced profiles
set to AlwaysKeep are retained.
Retries are selected from the failure itself, so not every job uses every stage. The normal escalation order is:
Failed partial output is cleaned between attempts. When all retries are exhausted, the source remains unchanged and the final reason is stored in the job log and catalog. The music path is deliberately simpler: it validates duration and discards empty, invalid, or no-savings output instead of using the video retry ladder. Exact Advanced encoders may retry decoding/subtitle handling, but never enter the encoder-substitution step.
Auto-scan keeps a persistent catalog, watches one or more folders, and periodically finds new or materially changed media. A file modified in the last 30 minutes is skipped to avoid reading it during a transfer.
A known path is treated as replaced media when its size changes by more than 10% or its
duration changes by more than 30 seconds. It is then probed and evaluated as new work.
Previously processed rows are retained in SQLite across restarts, failed files carry a
failure count, and interrupted [snacks] output is cleaned before retrying.
ScanProgress / AutoScanCompleted or the UI status.filenamePatterns: glob-style patterns such as *REMUX* or sample?.mkv; applies to video and music.minSizeGBToSkip: skips video or music files at or above the threshold.excludeResolutions: video-only labels such as 2160p, 1080p, or 720p. Snacks classifies by the larger of the real height and the 16:9 height derived from the width, so widescreen 1920×1080 media is 1080p and an ultra-wide 1920×800 master still buckets as 1080p.Analyze uses the same exclusions as a real scan and reports excluded files without queueing them. An explicit manual Process Item is a force-add and bypasses exclusions, which lets you process a deliberately excluded file when needed.
A master owns the authoritative queue and catalog. Worker nodes advertise capabilities, accept assigned files, encode them, and return verified output. Major version compatibility is checked during discovery.
6767 (see Changing the port); nodes announce the port they actually bound.6768 (fixed).Snacks asks GitHub for its latest release at most every 12 hours and shows Snacks vX.Y.Z is available with the way to update this install. The request carries a generic User-Agent and nothing that identifies you, the machine, or the install. Turn it off under Settings → System → Updates.
/app/work/app and, after
Restart (or by itself on a worker whose master allows it), winds down and restarts into it. The image's entrypoint runs
the newer of its own app and the download, and goes back to the previous version when a new one does not answer
/api/health in time. Mount /app/work/app to keep updates when the container is recreated. Nothing gets
the Docker socket; SNACKS_CONTAINER_UPDATES=false turns it off. A release that needs a new image, or an image from
before this updater, still shows docker compose pull && docker compose up -d (on Unraid, update ready
on the Docker tab).SNACKS_UPDATE_CHECK=false; the switch then shows as locked.In a cluster the master owns both switches. Workers never ask GitHub themselves: they show Managed by the master, and desktop workers update themselves only when the master allows it (on Windows only after a click on that machine, which the master's cluster panel asks for), only when idle, and only to the version the master runs or is installing itself (a newer release of the same major version, when the master is a desktop app that updates itself) — behind a Docker or Unraid master they move when the master does. Update the master first: after it moves to a new major version, desktop workers follow it, and the master's cluster panel lists Docker and Unraid workers that are behind with the command to run.
Shared storage avoids source/output transfer when both sides can access the same share. Workers fail closed: configure explicit input and output allowlists. If mount points differ, add master-prefix → worker-prefix rewrites; the longest matching prefix wins. If either side cannot safely use the shared path, Snacks falls back to normal transfer.
When the master runs the optional media server, worker nodes can transcode parts of
its streams. A node takes part only when Accept playback chunks is on for it: the master sets it in
the node's Hardware Devices dialog (the gear on its card in the Queue page's Cluster panel) and the node
picks it up within a heartbeat; the node's own Cluster settings then show Managed by the master. Until
the master sets it, the node's own acceptPlaybackChunks in its cluster.json applies (off by
default). The node also needs cluster mode and the shared secret. While the switch is off nothing playback-related runs on the node: no test encodes,
no extra files, nothing new in its heartbeat. Once it is on, the node checks its playback encoders and tone mappers
in the background once per ffmpeg build (a few seconds; results in
config/cluster-playback/playback/encoders.json) and reports them to the master with its heartbeat.
playbackDevices value (maxConcurrency = Streams, maxSessions = Max encodes),
and older nodes simply ignore the master's numbers. Playback chunks are never shown as queue jobs and never
cancelled by batch housekeeping.playbackEncoder: "software" makes the node offer only software encoding and tone mapping (its GPU stays
with batch work); the default auto uses the validated hardware encoder. It has no control in the
settings form: read GET /api/cluster-admin/config, change it and post the whole object back, because
POST /api/cluster-admin/config replaces the whole cluster configuration. The GET carries
every setting except the shared secret (posting it back keeps the stored one), and a post without a
nodeId keeps the instance's identity.useHttps in cluster.json; Snacks serves plain HTTP), works for a cluster, batch and
playback, only when the master trusts it: set SNACKS_TRUSTED_PROXIES on the master to the proxy's address
as the master sees it, and make the proxy send X-Forwarded-For. The master records each node at the address
its handshake comes from (every 30 s) — the right-most X-Forwarded-For entry that is not a listed proxy
when the connection comes from a listed proxy, otherwise the TCP address — and reaches the node, matches its completion
reports and checks its media-source reads by that address. It believes the header from no other peer, not even from
its own machine unless listed. Without the setting the dashboard lists the node at the proxy's address and the
master's calls meant for the node go to the proxy; shared storage does not help. The master always calls nodes
directly, never through the proxy. Alternatively encrypt with a VPN between the machines and useHttps
off, or a TLS layer that keeps client addresses (a transparent proxy). HTTP-source chunks over HTTPS have not been
run end to end through such a layer.SSL_CERT_FILE when it names an existing file by its full path, else the platform's
(/etc/ssl/cert.pem, /etc/ssl/certs/ca-certificates.crt, /etc/pki/tls/certs/ca-bundle.crt
or /etc/ssl/ca-bundle.pem). A master certificate that only the system store trusts (a private CA added to
the macOS Keychain, or, from the code, the Windows store) is refused, and the certificate must name the address the
node uses: the host of its master URL, or without one the master's IP (an IP SAN). The master must send its
intermediate certificates (the full chain): neither the node's ffmpeg nor its check fetches a missing one, so give the
server fullchain.pem (Let's Encrypt), not cert.pem; a bundle that also holds the intermediate
works too. Windows has no bundle file: from
the code (not yet run on a Windows node), a Windows node without SSL_CERT_FILE gets no HTTP-source chunks
from an HTTPS master. A node refused this way gets no HTTP-source chunks for 10 minutes (shown as
excluded when that leaves it nothing to do). For a private CA, point SSL_CERT_FILE at a copy
of the public bundle with your root CA appended (on Linux, other HTTPS clients in Snacks read it too).playback-chunks/ under its work folder only until the master fetched
them (at most 2 minutes after the chunk ended or was last read), takes at most 2 GB there, and removes the folder when it
stops accepting chunks.PlaybackLocalMaxConcurrency) or a ready node whose encoder, tone mapper and filters can make that quality.
A first chunk after play or seek normally runs on the master (no network overhead); later ~30 s chunks spread over the
nodes, where the player's buffer hides the few tenths of a second a node adds (measured). Turn Encode playback on this server
off (PlaybackLocalEncodingEnabled) to send every playback transcode to the nodes. That is strict: the master
never falls back to its own encoder, so with no node ready a new transcoded session gets 503 capacity and a
running one waits for a node. Direct Play, Direct Stream copies and audio always stay on the master.503 capacity with reason: "preparing". A chunk stopped before the node answered its submission is deleted on the node in the background. While the media server runs, the master also asks every ready node every 2 s whether it answers (on the playback chunk route below): a refused connection or two unanswered probes in a row give the node up at once. A quality no online encoder can make is answered at once with 503 capacity and reason: "no_encoder" instead of after the 20 s wait, and with local encoding off the 1080p quality is HEVC only while a ready node makes HEVC. New sessions are
admitted against the capacity of the master and every ready node; the playback upload limit
(PlaybackEgressLimitMbps) also counts the source reads of nodes without shared storage.testing, failed, stale, cooling, excluded, incompatible). The
batch device chips and job counters stay batch-only, and nothing about playback is shown while the media server is
off. A node's own dashboard shows its own PLAYBACK line (the chunks it encodes now) while it accepts playback chunks.
GET /api/media-server/sessions tells, per session, which nodes made which share of its segments.| Encoder family | Docker / Linux | Windows | macOS |
|---|---|---|---|
| NVIDIA | NVENC through CUDA runtime (amd64 and arm64) | NVENC | — |
| Intel | VAAPI | QSV | — |
| AMD | VAAPI | AMF | — |
| Apple | — | — | VideoToolbox H.264/HEVC |
| Rockchip RK35xx (experimental) | MPP H.264/HEVC (arm64) | — | — |
| Software | x264, x265, SVT-AV1 | x264, x265, SVT-AV1 | x264, x265, SVT-AV1 |
/dev/dri/renderD*, each with its own VAAPI driver), each NVIDIA GPU, and on Windows each Intel adapter it can confirm; every card that passes is its own device. A job goes to the card with the most free slots, so several cards share the queue.NVIDIA #1, NVIDIA #2 when a node has several cards of a kind — and a switched-off card's chip is struck through. The line under the node's name shows its role and OS only./dev/mpp_service, /dev/rga and /dev/dma_heap passed through (see docker-compose.gpu.yml), and is used only after its decode → scale → encode check passes at startup.privileged: true because its video/render group layout differs from conventional Linux hosts. Unraid normally uses group access instead; follow unraid/README.md.
Passing /dev/dri or enabling privileged mode is not enough for NVENC.
Install the NVIDIA Container Toolkit on the host (amd64 or arm64) and configure the NVIDIA runtime; with
NVIDIA_VISIBLE_DEVICES=all every GPU is used:
runtime: nvidia
environment:
- NVIDIA_VISIBLE_DEVICES=all
- NVIDIA_DRIVER_CAPABILITIES=compute,video,utility
Add this to the Docker service when the host should monitor application liveness:
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:6767/api/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
The maintained QNAP example is deploy-compose.yml. Typical media roots are
/share/CACHEDEV1_DATA/Multimedia or /share/Public on QNAP and
/volume1/video or /volume1/Media on Synology.
Luna can privately inspect selected Sonarr/Radarr metadata, search their catalogs, and add movies or series you explicitly request. Snacks stays inside your network: it polls Luna over an outbound connection, executes a small typed action locally, and returns a path-free result. No port forwarding or public Snacks URL is required.
https://veryluna.com. Luna's source and self-hosting environment are private;
there is no public self-hosted Luna distribution. Custom URLs exist only for the project
owner's explicit local integration testing.
localhost means the Snacks container—not the Docker host or NAS.https://veryluna.com. Do not substitute another Luna endpoint.https://veryluna.com in normal deployments.| Where a service runs | Address to enter in containerized Snacks |
|---|---|
| Official VeryLuna service | https://veryluna.com |
| Project owner's isolated integration test | http://luna:8080 only with both explicit local-testing overrides |
| Radarr/Sonarr published on the Docker host | http://host.docker.internal:7878 / :8989 |
| Radarr/Sonarr on a NAS or another machine | The machine's LAN URL, such as http://192.168.1.50:7878 |
SNACKS_INTEG_Luna__BaseUrl=http://luna:8080 and
SNACKS_LUNA_ALLOW_CUSTOM_URL=true. Its HTTP-only Compose bridge additionally
sets SNACKS_LUNA_ALLOW_INSECURE_HTTP=true. The test URL is supplied outside
the UI; never use these overrides in a normal or internet-routable Snacks deployment.
| Capability | What it permits | When it appears |
|---|---|---|
radarr.catalog.search | Search Radarr's public movie catalog. | Radarr is enabled and configured. |
radarr.library.read | Read path-free movie pages (100 by default, 200 maximum). | Filtered metadata reads are enabled. |
radarr.movie.add | Add by TMDb ID; monitoring and search options are bounded. | Library changes are enabled. |
sonarr.catalog.search | Search Sonarr's public series catalog. | Sonarr is enabled and configured. |
sonarr.library.read | Read path-free series and episode-count metadata. | Filtered metadata reads are enabled. |
sonarr.series.add | Add by TVDb ID with a validated monitoring mode. | Library changes are enabled. |
Snacks rechecks the live configuration before executing every task. Turning off a
permission blocks that action immediately, even before Luna receives the next
capability heartbeat. Add actions are idempotent: a retry checks the stable TMDb/TVDb
ID and returns alreadyExists instead of adding a duplicate.
Arr URLs and API keys, filesystem paths, filenames, file sizes, root-folder paths, and raw error responses.
Titles, years, genres, public TMDb/TVDb/IMDb IDs, ratings, monitoring state, and basic episode/file availability.
Completed task rows are hard-deleted as soon as Luna consumes the result. An abandoned completion has a five-minute safety prune. Full connector results are omitted from durable tool history; Luna's final chat reply remains normal chat history.
Filtered metadata used for a recommendation may be included in Luna's current
AI-provider request. Snacks stores the restricted refresh credential separately from
integration settings; access tokens remain in memory. On Unix, the credential file and
backup are owner-only (0600). Disconnect disables the connector, cancels
unfinished work, revokes the refresh credential, and removes the local backup.
host.docker.internal, or a LAN address—not host localhost.| Integration | Purpose | Credential |
|---|---|---|
| Plex (external media server) | Connection test and optional library rescan after completion, scoped to the file's folder in a library of the same kind (music libraries for music). A server with no library of that kind is skipped; a path that lines up with none of its libraries falls back to refreshing every library. | Server token |
| Jellyfin (external media server) | Connection test and optional rescan after completion: Jellyfin is told about the file in a library of the same kind (music libraries for music), with the same skip and fallback rules as Plex. Jellyfin applies its own change delay (60 seconds by default) before updating. | API key |
| Luna | Outbound typed tasks for private Sonarr/Radarr recommendations and explicit additions. | Restricted Luna connector session |
| Sonarr / Radarr | Media-manager connectivity, Luna tasks, metadata workflow support, and a series/movie rescan after an encode replaces its original. | API key |
| Lidarr | Album-folder rescan after a music encode replaces its original. | API key |
| TheTVDB / TMDb | Original-language and metadata lookups used by language-aware processing. | API key; TVDB PIN optional. TMDb works without one, using Snacks' built-in key. |
| fanart.tv | Artist photos, backgrounds and logos for the media server's music, while Fetch music info and artwork online is on. | Optional personal key (shows newly added artwork sooner); works without one, using Snacks' built-in key. |
| Homarr | Compact Snacks iFrame tile, or Homarr's native Media Transcoding widget through a read-only Tdarr adapter. | Scoped iframe token or Snacks API key |
| Notifications | Webhook, ntfy, or Apprise destinations for encode/scan/node events. The File Replaced event (off by default) fires after an output replaces its original or is written beside it; a webhook's payload carries jobId, sourcePath, outputPath, action (replaced or written), sourceSize, outputSize, sourceDuration, outputDuration and codec, is signed like other webhooks when the destination has a secret, and is retried twice (after 2 s and 5 s) without holding up the job. | Destination-specific |
Plex and Jellyfin appear in Settings under External media servers: servers you already run, which Snacks only asks to rescan. Snacks' own optional media server is separate; see Media Server.
Most integration credentials are stored in plaintext JSON inside the Snacks config
directory. Luna is different: your password is exchanged once and never saved, while
its restricted refresh credential is stored separately in luna-connection.json.
Protect the complete config directory with host permissions, enable control-panel
authentication, and restrict network access to trusted clients.
The Arr apps track individual files, so an episode, movie, or track whose original Snacks
replaced (for example Movie.mp4 → Movie.mkv) shows as missing until
the app rescans its folder. With the connection enabled, Snacks requests that rescan itself.
| App | What is rescanned | Command |
|---|---|---|
| Sonarr | The one series that owns the replaced episode. | RescanSeries with seriesId |
| Radarr | The one movie that owns the replaced file. | RescanMovie with movieId |
| Lidarr | The album folder of the replaced track. | RescanFolders with that folder |
[snacks] copy beside the original./mnt/media/tv/Show (2020)/Season 01 matches Sonarr's /tv/Show (2020), and Snacks' /mnt/media/music/Artist/Album lines up with Lidarr's /music root. Video is offered to Sonarr or Radarr first by its file name pattern, then to the other. When nothing matches, nothing is sent and the Snacks log says so.Both choices are read-only and expose the same Snacks queue and cluster state, but they use different presentation, credentials, and network paths. They may be used together.
| Option | Choose it for | Who connects to Snacks | Credential |
|---|---|---|---|
| Snacks compact tile | Snacks' responsive Stats, Queue, and Workers views inside a Homarr iFrame widget. | Each viewer's browser | Scoped iframe URL when Snacks sign-in is enabled |
| Homarr Media Transcoding | Homarr's native widget, backed by Snacks' Tdarr-compatible read model. | The Homarr server or container | Snacks API key when Snacks sign-in is enabled |
The compact tile is a server-rendered Snacks page at /iframe/homarr. Its
Stats tab shows lifetime space savings, encode counts, current queue counts, a 14-day
savings sparkline, and active work. Queue shows active and pending files; Workers shows
the local instance and discovered cluster nodes. Nothing in the tile can mutate Snacks.
https://homarr.example.com or http://192.168.1.20:7575. Enter
an origin, not a board path, then select Save origins.
snacks usually is not. If necessary, replace only the generated
URL's scheme, host, and port with the browser-reachable Snacks origin.
The generated URL can be customized by appending these query parameters:
| Parameter | Values and default | Effect |
|---|---|---|
embedToken | Generated snk_embed_… value | Required by the iframe route when the Snacks sign-in gate is active. It is retained when changing tile tabs. |
theme | dark (default) or light | Selects the tile color scheme. |
tab | stats (default), queue, or workers | Selects the initial tab; visitors can still switch tabs in the tile. |
limit | 10 by default; clamped to 1–30 | Limits rows shown on the Queue tab. |
refresh | 30 seconds by default; 0 disables, other values clamp to 10–3600 | Reloads the server-rendered snapshot. |
https://snacks.example.com/iframe/homarr?embedToken=YOUR_TOKEN&theme=dark&tab=stats&limit=10&refresh=30
Snacks implements only the read-only Tdarr API subset consumed by Homarr's native Media Transcoding widget. Use this choice when the widget should inherit Homarr's own design, default-view setting, and queue pagination.
http://snacks:6767 or http://192.168.1.20:6767. Do not append
/api or an endpoint path. This address must be reachable from the Homarr
server or container, not merely from the browser.
| Homarr tab | Snacks data | Intentional limitations |
|---|---|---|
| Statistics | Catalog and lifetime encode totals, saved space, outcomes, current queue counts, 365-day video/music codec mix, and 4K split. | Health-check and container-history charts are empty because Snacks does not retain those Tdarr concepts. |
| Queue | Current active and SQLite-backed pending transcodes, with source container, codec, resolution, size, and status. | Read-only; completed history and Tdarr health-check table are not exposed here. |
| Workers | Local and discovered cluster nodes, pause state, active file, device, phase, and progress. | FPS, ETA, and worker size estimates are not currently available and display neutral values. |
http://snacks:6767 can work here because Homarr makes
the requests; localhost refers to Homarr itself. The adapter cannot execute
Tdarr plugins, control jobs, or act as a complete Tdarr server. Although its calls are
read-only, a Snacks API key is a full API credential and must be protected accordingly.
Homarr's current field names and widget options are also described in its official Tdarr integration, Media Transcoding widget, and iFrame widget documentation.
SNACKS_WORK_DIR selects the work root. In the standard container it is
/app/work; desktop defaults under the current user's local application data.
| Path under work directory | Contents | Back up? |
|---|---|---|
config/snacks.db | SQLite catalog, status, transitions, and encode history. | Yes |
config/settings.json | Global encoder options. | Yes |
config/presets.json | Named encoder presets. | Yes |
config/autoscan.json | Watch folders, interval, pause state, exclusions. | Yes |
config/cluster.json | Role, identity, shared secret, discovery, shared paths. | Yes; sensitive |
config/node-settings.json | Per-node devices, schedules, and limits. | Yes |
config/integrations.json | Third-party endpoints, credentials, and non-secret Luna preferences. | Yes; sensitive |
config/luna-connection.json and .bak | Luna connector identity and restricted refresh credential; removed on disconnect. | Yes; sensitive |
config/notifications.json | Notification destinations and event toggles. | Yes; sensitive |
config/auth.json | Password hash and session signing secret. | Yes; sensitive |
config/networking.json | Cluster transfer limits and chunk size. | Yes |
config/updates.json | Release check and automatic-update switches. | Yes |
config/update-check.json | Last answer of the release check (rebuilt on demand). | No |
logs/ | Rolling application log and per-encode FFmpeg logs. | Optional |
remote-jobs/ | Worker transfer and encode scratch space. | No |
config/ directory as one unit./api/health.
JSON configuration writes are atomic and keep .bak fallbacks, but a
host-level backup remains the recovery boundary for accidental deletion or disk loss.
Encoder, auto-scan, integration, and media-server settings can be pinned from the environment — handy for version-controlling configuration in a compose file. Overrides are applied in-memory on every load and never written to the JSON files, so removing a variable reverts to the file's value. Env-pinned settings show a lock icon in the GUI.
SNACKS_SET_<Prop> → settings.json, nested properties via __ (e.g. SNACKS_SET_Music__BitrateKbps).SNACKS_SCAN_<Prop> → autoscan.json.SNACKS_INTEG_<Section>__<Prop> → integrations.json.SNACKS_MEDIA_<Prop> → mediaserver.json (the optional media server, e.g. SNACKS_MEDIA_Enabled=true).
Property names are case-insensitive. Booleans accept true/false/1/0/yes/no/on/off;
numbers and enums accept their plain values; string lists accept comma-separated or JSON
values; nested objects and other complex values accept JSON. An invalid or unknown
variable logs a warning once and is skipped — startup never fails on a bad override.
environment:
- SNACKS_API_KEY=change-me
- SNACKS_SET_Codec=av1
- SNACKS_SET_TargetBitrate=2500
- SNACKS_SET_Music__BitrateKbps=256
- SNACKS_SET_AudioLanguagesToKeep=en,ja
- 'SNACKS_SET_AudioOutputs=[{"Codec":"aac","Layout":"Stereo","BitrateKbps":192}]'
- SNACKS_SET_AdvancedVideo__Enabled=true
- 'SNACKS_SET_AdvancedVideo__Profiles=[{"Id":"11111111-1111-4111-8111-111111111111","Name":"AV1 CQ 35","Codec":"av1","EncoderSelection":"Explicit","Encoder":"libaom-av1","RateControl":{"Mode":"Quality","Quality":35},"Preset":"4","Threads":8,"PixelFormat":"yuv420p10le","GopSize":300,"OutputRetention":"AlwaysKeep"}]'
- 'SNACKS_SET_AdvancedVideo__Rules=[{"Id":"22222222-2222-4222-8222-222222222222","Name":"Codec is not AV1","Match":"All","Conditions":[{"Field":"Codec","Operator":"IsNot","Values":["av1"]}],"Action":"TranscodeWithProfile","ProfileId":"11111111-1111-4111-8111-111111111111"}]'
- 'SNACKS_SCAN_Directories=["/media/tv","/media/movies"]'
- SNACKS_SCAN_Enabled=true
- SNACKS_SCAN_IntervalMinutes=30
- SNACKS_INTEG_Plex__BaseUrl=http://plex:32400
- SNACKS_INTEG_Plex__Token=replace-me
- SNACKS_INTEG_Plex__RescanOnComplete=true
- SNACKS_INTEG_Plex__Enabled=true
Environment values win on every load, but are never copied into the JSON files.
HardwareDevicePath is dispatch-specific and cannot be pinned. Runtime scan
state—QueuePaused, LastScanTime, and
LastScanNewFiles—is also excluded; control pause state through the queue API.
On a worker, settings sent with a master-assigned job are authoritative, so node-local
SNACKS_SET_* values affect only work queued by that node itself.
GET /api/health is an unauthenticated liveness check.GET /metrics exposes Prometheus text and is cached for 15 seconds.GET /api/diagnostics/log?lines=200 returns the latest application-log tail.GET /api/diagnostics/logs.zip downloads available logs.# Liveness
curl -fsS http://snacks-host:6767/api/health
# Prometheus scrape
curl -fsS http://snacks-host:6767/metrics
# Authenticated local log tail
curl -b snacks.cookies \
"http://snacks-host:6767/api/diagnostics/log?lines=300"
docker exec snacks ls -la /app/work/uploads
In container mode, paths outside the configured upload root are rejected by the API.
docker exec snacks ls -la /dev/dri
docker exec snacks vainfo
NVIDIA also requires the NVIDIA container runtime and its video capability; privileged
mode alone does not provide CUDA/NVENC libraries.
A startup failure like
Failed to bind to address http://[::]:6767: address already in use
means another process owns the port. Warnings such as
Overriding HTTP_PORTS… or
Overriding address(es)… Binding to endpoints defined via IConfiguration
and/or UseKestrel() instead mean a port was supplied through a variable
Snacks does not honor — it configures its listener explicitly, and only
ASPNETCORE_URLS is read.
With Docker host networking, ports: mappings are silently ignored;
set ASPNETCORE_URLS=http://0.0.0.0:7070 instead. With bridge
networking, map "7070:6767" and leave the environment alone. The
desktop app resolves port conflicts automatically. See
Changing the port.
Confirm that the integration URL is the Snacks base origin with no API path, that it points to the master/coordinator, and that the Homarr container can resolve and reach it. Use API Key with a current Snacks key when sign-in is enabled, or No Authentication only when the Snacks sign-in gate is disabled. Test the same probe from Homarr's network namespace when possible:
curl -i -X POST \
-H "X-Api-Key: YOUR_SNACKS_API_KEY" \
http://snacks:6767/api/v2/is-server-alive
HTTP 401 indicates a missing or stale key. A DNS or connection error indicates the Homarr-to-Snacks network path. For HTTPS, also verify the certificate trust chain. See Homarr Media Transcoding setup.
First open the generated iframe URL directly on the same viewer device. HTTP 401
means the scoped token was omitted, revoked, or replaced. If the URL works directly
but not inside Homarr, add the exact Homarr origin—including scheme and port—to
Settings → Security → Iframe Access. Also check that a reverse proxy
is not replacing Snacks' Content-Security-Policy: frame-ancestors …
response and that an HTTPS board is not trying to frame an HTTP URL.
A browser DNS or connection error means the generated Snacks origin is not reachable from the viewer; unlike an integration, an iFrame is not fetched by the Homarr container. See Snacks compact tile setup.
config/auth.json. On the next start, authentication returns to its default
disabled state and a new session secret is generated.
The web UI uses the same JSON endpoints documented below. Paths are relative to the
running instance, for example http://snacks-host:6767. JSON properties use
camelCase; incoming property names are case-insensitive. Dates are UTC ISO 8601.
The running app also publishes a generated, machine-readable OpenAPI document at
/openapi/v1.json. It contains the supported
public/UI API and intentionally excludes the internal cluster RPC protocol.
With control-panel authentication disabled, ordinary API routes require no credential.
When enabled, sign in through the form endpoint and retain the
snacks_session cookie. The cookie is HTTP-only and signed; its embedded
token expires after 14 days (the browser cookie itself is session-scoped).
BASE="http://snacks-host:6767"
curl -fsS -c snacks.cookies \
-H "Content-Type: application/x-www-form-urlencoded" \
--data-urlencode "username=admin" \
--data-urlencode "password=your-password" \
--data-urlencode "returnUrl=/" \
"$BASE/Auth/Login"
curl -fsS -b snacks.cookies "$BASE/api/queue/stats"
/api/health, /metrics, static assets, the login page, and
secret-authenticated cluster RPC are intentionally outside cookie authentication.
SignalR is protected whenever UI authentication is enabled.
For callers that can't do cookie login, /api/* also accepts an API key —
sent as an X-Api-Key header or an Authorization: Bearer token.
Generate one in Settings → Security → API Access (or via
POST /api/auth/apikey/generate), or supply one through the
SNACKS_API_KEY environment variable; both work at once, and the env-supplied
key is never revealed by the API.
The Sonarr-style ?apiKey= query form is restricted to the read-only
/api/v1/* and Homarr/Tdarr compatibility routes because URL credentials can
leak into history and proxy logs. Mutation routes require a header, bearer token, or
signed session. Iframe pages use a separate scoped ?embedToken= credential.
curl -fsS -H "X-Api-Key: $SNACKS_API_KEY" "$BASE/api/queue/stats"
Remote access requires sign-in. While no password is configured, Snacks
only serves clients on loopback, private (RFC1918), CGNAT/Tailscale, link-local, and IPv6
unique-local addresses, plus the IPv6 prefixes of the machine's own network interfaces
(so dual-stack LAN clients keep working). Requests from public addresses — including
clients relayed by a reverse proxy that sends X-Forwarded-For,
Forwarded, X-Real-IP, or CF-Connecting-IP — receive
403 unless they present a valid API key (or, on /iframe/*, the
embed token). The routes listed above as outside cookie authentication stay reachable.
Enable sign-in before exposing Snacks beyond the LAN. To treat additional ranges as local,
list them in SNACKS_LOCAL_NETWORKS (for example
203.0.113.0/24, 2001:db8:1::/48). If an upstream proxy (Authelia, Authentik,
and similar) already authenticates every user, set
SNACKS_ALLOW_REMOTE_WITHOUT_AUTH=true to restore open access.
After 10 failed sign-in attempts from one client within 5 minutes, further attempts are
refused until the window passes; successful sign-ins never count. While sign-in is active,
changing the username or password, or turning sign-in off, requires the current password
(currentPassword on POST /api/auth/config).
Media server players are throttled per username and per client address. For players, the address is the
connecting one; X-Forwarded-For counts only when the connection comes from this machine (a reverse
proxy on the same host) or from a proxy listed in SNACKS_TRUSTED_PROXIES (addresses or CIDR ranges,
comma, semicolon or space separated, e.g. 172.17.0.2, 10.0.5.0/24; a malformed entry is logged under
that name and ignored; a cluster master uses the same list for nodes behind a proxy). A reverse proxy elsewhere that
is not listed makes every player behind it share one sign-in address. An IPv6 client counts as its whole /64
network (one device can rotate through every address of it), so players on the same IPv6 network share an
address, as players behind one IPv4 router do. Failures only delay new sign-ins; devices already signed in are
never affected. When the failure table is full, the oldest locked-out addresses are forgotten first; locked-out
usernames and PINs are kept for their full day.
Content-Type: application/json for JSON request bodies.{ "success": true }./api/*.curl -fsS -b snacks.cookies \
"$BASE/api/queue/items?status=Pending&skip=0&limit=50"
curl -fsS -b snacks.cookies \
-H "Content-Type: application/json" \
-d '{"paused":true}' \
"$BASE/api/queue/paused"
curl -fsS -b snacks.cookies "$BASE/api/settings" > settings.json
jq -n \
--arg filePath "/app/work/uploads/Movies/Movie.mkv" \
--slurpfile options settings.json \
'{filePath:$filePath, options:$options[0]}' > request.json
curl -fsS -b snacks.cookies \
-H "Content-Type: application/json" \
--data-binary @request.json \
"$BASE/api/library/process-file"
jq -n \
--arg directoryPath "/app/work/uploads/Movies" \
--slurpfile options settings.json \
'{directoryPath:$directoryPath, recursive:true, options:$options[0]}' > analyze.json
JOB_ID=$(curl -fsS -b snacks.cookies \
-H "Content-Type: application/json" \
--data-binary @analyze.json \
"$BASE/api/library/analyze-directory" | jq -r .jobId)
curl -fsS -b snacks.cookies "$BASE/api/library/analyze-status/$JOB_ID"
curl -fsS -b snacks.cookies "$BASE/api/library/analyze-results/$JOB_ID"
# Read-modify-write so unknown/newer fields are preserved.
curl -fsS -b snacks.cookies "$BASE/api/settings" |
jq '.targetBitrate = 3000 | .queueNewestFirst = true' > settings.updated.json
curl -fsS -b snacks.cookies \
-H "Content-Type: application/json" \
--data-binary @settings.updated.json \
"$BASE/api/settings"
No API endpoints match the current filter.
| Method | Path | Inputs | Purpose / response |
|---|---|---|---|
| GET | /api/library/directories | — | Browsable roots with names and media counts. |
| GET | /api/library/subdirectories | directoryPath | Immediate allowed child directories. |
| GET | /api/library/files | directoryPath, recursive=true, skip=0, limit=1000 (max 5000) | {files,total,videoTotal,musicTotal,truncated}. |
| POST | /api/library/process-file | {filePath, options?} | Queues one file as an explicit/manual job. options is optional; when omitted (or null / {}), the server's saved settings are used, including the output location. Legacy twoChannelAudio/audioCodec/audioBitrateKbps become audioOutputs when audioOutputs is absent; a present audioOutputs, even [], wins. |
| POST | /api/library/process-directory | {directoryPath, recursive, options?} | Queues allowed media under a directory. options is optional; when omitted, the server's saved settings are used (same rules as process-file). |
| POST | /api/library/analyze-directory | {directoryPath, recursive, options?} | Starts dry-run analysis; returns {success,jobId}. options is optional; when omitted, the server's saved settings are used. |
| GET | /api/library/analyze-status/{jobId} | Path ID | {state,processed,total,error}; total is −1 while enumerating. |
| GET | /api/library/analyze-results/{jobId} | Path ID | Results, summary, total, and truncation state; 409 while running. |
| POST | /api/library/analyze-cancel/{jobId} | Path ID | Cancels an active analysis job. |
| GET | /api/library/health | filter, q, skip=0, limit=100 | {items,total,summary}; issue filters include no-audio, no-video, no-duration, failed, verify-failed. |
| GET | /api/library/insights | — | Library totals plus codec, resolution, and status distributions. |
| POST | /api/library/health/verify | {filePath} | Runs bounded FFmpeg decode samples; returns {ok,issues}. |
| POST | /api/library/health/reset-verify-file | {filePath} | Clears one failed-verification flag without deleting the file. |
| POST | /api/library/health/reset-verify | {filter,q} | Bulk-clears verification flags matching the current health view. |
| POST | /api/library/health/delete | {filePath} | Destructive: deletes a flagged file and its catalog row. Files not currently listed on the Library Health page are refused with 400. |
| POST | /api/library/health/delete-all | {filter,q} | Destructive: bulk-deletes matching flagged files; returns deleted/failed/capped counts. |
No API endpoints match the current filter.
| Method | Path | Inputs | Purpose / response |
|---|---|---|---|
| GET | /api/queue/items | limit, skip=0, status | Paginated non-active queue plus all active items and totals. |
| GET | /api/queue/stats | — | Pending, active, completed, failed, and related aggregate counts. |
| GET | /api/queue/item/{id} | Work item ID | One in-memory work item or 404. |
| GET | /api/queue/logs/{id} | Work item ID | Available per-job log lines. |
| POST | /api/queue/prioritize/{id} | Work item ID | Moves a pending item to the front using queue priority. |
| POST | /api/queue/stop/{id} | Work item ID | Stops active work and marks it eligible for later reprocessing. |
| POST | /api/queue/cancel/{id} | Work item ID | Stops/cancels and prevents automatic reprocessing. |
| POST | /api/queue/retry | {filePath} | Retries one failed file under the current encoder settings. |
| GET | /api/queue/failed | — | Returns failed queue entries. |
| DELETE | /api/queue/failed | — | Destructive to history: removes all failed entries. |
| GET | /api/queue/paused | — | Returns the persisted pause state. |
| POST | /api/queue/paused | {paused:true|false} | Pauses/resumes the processing system. |
No API endpoints match the current filter.
| Method | Path | Inputs | Purpose / response |
|---|---|---|---|
| GET | /api/settings | — | Full effective EncoderOptions JSON. |
| POST | /api/settings | Settings object | Saves settings atomically and applies presence-aware migration. |
| POST | /api/settings/reevaluate | forceRetryNoSavings=false | Re-evaluates catalog eligibility using current settings. |
| GET | /api/settings/video-encoders | refresh=false | Runtime H.264/HEVC/AV1 encoder catalog, native rate controls, local devices, and connected-worker availability. |
| POST | /api/settings/advanced-video/validate | {advancedVideo, profileId?, sourceFacts?} | Validates staged profiles/rules and returns stable diagnostics plus a literal FFmpeg video-argument preview without executing it. |
| POST | /api/settings/advanced-video/impact | {advancedVideo} | Read-only library impact preview for a staged policy, including decision buckets and rule matches. |
| GET | /api/settings/advanced-video/measured | — | Measured encode-history outcomes grouped by Advanced Video profile. |
| GET | /api/settings/advanced-video/templates | — | Lists user-saved Advanced Video policy templates. |
| POST | /api/settings/advanced-video/templates | {name,advancedVideo} | Validates and upserts a named policy template (maximum 20). |
| DELETE | /api/settings/advanced-video/templates/{name} | Template name | Deletes one Advanced Video policy template. |
| GET | /api/settings/presets | — | Lists saved preset names and values. |
| POST | /api/settings/presets | {name, options} | Creates or replaces a named preset. |
| DELETE | /api/settings/presets/{name} | Preset name | Deletes one preset. |
| GET | /api/settings/presets/export/{name} | Preset name | Downloads one preset as JSON. |
| POST | /api/settings/presets/import | Exported preset JSON | Validates and imports a preset. |
| Method | Path | Inputs | Purpose / response |
|---|---|---|---|
| GET | /api/auto-scan/config | — | Schedule, watch folders, last scan, pause state, exclusions. |
| POST | /api/auto-scan/enabled | {enabled} | Enables/disables scheduled scans. |
| POST | /api/auto-scan/interval | {intervalMinutes} | Sets the scan interval. |
| POST | /api/auto-scan/directories | {path} | Adds an allowed watch directory. |
| DELETE | /api/auto-scan/directories | {path} | Removes a watch directory. |
| POST | /api/auto-scan/trigger | — | Starts an immediate background scan. |
| POST | /api/auto-scan/clear-history | — | Broad reset: clears persisted processing history. |
| GET | /api/auto-scan/exclusions | — | Returns current ExclusionRules. |
| POST | /api/auto-scan/exclusions | {filenamePatterns,minSizeGBToSkip,excludeResolutions} | Saves exclusion rules. |
| Method | Path | Inputs | Purpose / response |
|---|---|---|---|
| GET | /api/auth/config | — | Returns only enabled, username, and hasPassword. |
| POST | /api/auth/config | {enabled,username,password,currentPassword} | Saves auth; null/empty password preserves the existing hash. While sign-in is active, currentPassword is required to change the username or password or to disable sign-in. Clears the current cookie and ends every other session when the password changes. |
| GET | /api/auth/apikey | — | Returns the stored API key. A key supplied via SNACKS_API_KEY is never exposed here. |
| POST | /api/auth/apikey/generate | — | Generates and persists a new stored API key, replacing any previous one. |
| DELETE | /api/auth/apikey | — | Removes the stored API key. A key set via SNACKS_API_KEY stays valid. |
| GET | /api/auth/embed | — | Returns the stored iframe-only token and concrete CSP origin allowlist. |
| POST | /api/auth/embed/generate | — | Generates a new token accepted only by read-only /iframe/* pages. |
| DELETE | /api/auth/embed | — | Revokes the iframe-only token. |
| POST | /api/auth/embed/origins | {origins:["https://homarr.example"]} | Replaces and normalizes the HTTP(S) origins allowed by iframe CSP. |
| GET | /api/notifications/config | — | Full destination and event-toggle configuration. |
| POST | /api/notifications/config | Notification config | Saves destinations and toggles. |
| POST | /api/notifications/test | One destination object | Sends a test notification. |
| GET | /api/integrations/config | — | Returns Plex, Jellyfin, Sonarr, Radarr, TVDB, TMDb, and non-secret Luna preferences. |
| POST | /api/integrations/config | Integration config | Saves third-party configuration. |
| GET | /api/integrations/luna/status | — | Safe Luna connection health and advertised capabilities; never returns access or refresh tokens. |
| POST | /api/integrations/luna/connect | {baseUrl,email,password,deviceName?} | Exchanges credentials once for a restricted outbound connector session; the password is not persisted. |
| POST | /api/integrations/luna/disconnect | — | Revokes the scoped Luna session and removes its primary and backup credential files. |
| POST | /api/integrations/test/plex | {baseUrl,token} | Tests Plex credentials/connectivity without saving. |
| POST | /api/integrations/test/jellyfin | {baseUrl,token} | Tests Jellyfin credentials/connectivity without saving. |
| POST | /api/integrations/test/sonarr | {baseUrl,apiKey} | Tests Sonarr credentials/connectivity without saving. |
| POST | /api/integrations/test/radarr | {baseUrl,apiKey} | Tests Radarr credentials/connectivity without saving. |
| POST | /api/integrations/test/lidarr | {baseUrl,apiKey} | Tests Lidarr credentials/connectivity without saving. |
| POST | /api/integrations/test/tvdb | {apiKey,pin} | Tests TVDB authentication without saving. |
| POST | /api/integrations/test/tmdb | {apiKey} | Tests TMDb authentication without saving; an empty apiKey tests Snacks' built-in key. |
| GET | /api/networking | — | Returns cluster transfer concurrency, rate, and chunk settings. |
| POST | /api/networking | NetworkingSettings | Saves validated master-side transfer limits. |
No API endpoints match the current filter.
Dashboard GET routes accept optional kind=video|music. Windowed routes clamp days to 1–365.
| Method | Path | Inputs | Purpose |
|---|---|---|---|
| GET | /api/dashboard/summary | kind | Lifetime hero totals. |
| GET | /api/dashboard/savings-over-time | days=30, kind | Continuous daily savings series. |
| GET | /api/dashboard/device-utilization | days=30, kind | Per-device work totals. |
| GET | /api/dashboard/codec-mix | days=30, kind | Output codec distribution. |
| GET | /api/dashboard/node-throughput | days=30, kind | Per-node leaderboard. |
| GET | /api/dashboard/recent | limit=25, kind | Recent successful encodes. |
| GET | /api/dashboard/top-savings | limit=10, days=365, kind | Largest compression wins. |
| DELETE | /api/dashboard/history | — | Destructive to history: deletes the complete encode-history ledger. |
The v1 routes are Snacks-native read models. The v2 routes intentionally reproduce only
the case-sensitive Tdarr response shapes consumed by Homarr. Although three Tdarr probes
use POST, every compatibility action is read-only. When sign-in is enabled these routes
accept the API key as X-Api-Key, a bearer token, or the compatibility-only
?apiKey= query parameter. See the setup and supported
data before treating this subset as a general Tdarr API.
| Method | Path | Inputs | Purpose |
|---|---|---|---|
| GET | /api/v1/system/status | — | Version, instance, runtime, role, node, uptime, and auth status. |
| GET | /api/v1/stats | — | Lifetime history plus DB-backed current queue statistics. |
| GET | /api/v1/queue | page=1, pageSize=10 (max 100) | Active jobs, the complete SQLite pending queue, and recent terminal records. |
| GET | /api/v1/workers | — | Deduplicated local and cluster worker/job snapshots. |
| POST | /api/v2/is-server-alive | — | Homarr Tdarr-adapter connection probe. |
| POST | /api/v2/stats/get-pies | {data:{libraryId:""}} | Tdarr-shaped queue, history, codec, resolution, and saved-space statistics. |
| GET | /api/v2/get-nodes | — | Tdarr-shaped node and active-worker dictionaries. |
| POST | /api/v2/client/status-tables | {data:{start,pageSize,opts:{table}}} | table1 is the DB-backed transcode queue; unsupported health-check table4 is empty. |
| Method | Path | Inputs | Purpose |
|---|---|---|---|
| GET | /api/cluster-admin/config | — | Cluster role, identity, discovery, secret, timing (including useHttps and staleReceiveTimeoutSeconds), shared-storage and playback-chunk config (acceptPlaybackChunks, playbackDevices, playbackEncoder, each present only when set; see Playback chunks). On a node, managedPlayback {managedBy, acceptPlaybackChunks, devices:[{deviceId, displayName, maxEncodes, libraryJobs, streams}]} is what applies with the master's settings. The shared secret is never returned (hasSecret says whether one is set). |
| POST | /api/cluster-admin/config | ClusterConfig | Saves and applies cluster configuration (the whole object: post back what the GET returned). A body without a shared secret keeps the stored one; a body without a nodeId, or with a blank one, keeps the instance's identity. |
| GET | /api/cluster-admin/status | — | Local state, version, nodes, schedules, and live cluster status. While this server's media server runs, a trailing playbackSlots lists the playback-chunk slots it books: [{nodeId, used, capacity, state, devices:[{deviceId, used, capacity, encoder}]}] for this server (while it encodes playback itself) and every node that accepts playback chunks (state ready, testing, failed, stale, cooling, excluded or incompatible; excluded: the node's refusals left it no chunk, e.g. it could not read the source, retried after 10 min; detail, when present, says more — media source refused: connected from X, registered as Y while its reads of the media source come from another address than the one it is registered at; a node's devices[].encoder, when present, names the playback encoder on that device — VideoToolbox, NVENC (self-test passed), libx264, and on cpu a GPU encoder that failed with its reason, libx264 — NVENC failed its self-test: …). On a node that accepts playback chunks (its media server off), playbackSlots is that node's own entry only: the chunks it encodes now, per device, against the caps it advertises, and its self-test state. Without either the member is absent and the response is unchanged. In a cluster, nodeLinks {nodeId: url} gives every other node's web UI (http(s)://address:port/, absent while its address is unknown): its name on the cluster card opens it in a new tab. |
| GET | /api/cluster-admin/workers | — | Connected/discovered worker list. |
| POST | /api/cluster-admin/node-paused | {nodeId,paused} | Pauses/resumes one worker. |
| POST | /api/cluster-admin/local-encoding-paused | {paused} | Pauses/resumes encoding on the master itself. |
| GET | /api/cluster-admin/node-settings | — | Per-node devices, slot limits, and schedules. |
| POST | /api/cluster-admin/node-settings | NodeSettings | Saves settings for one node, merged into what is stored: only the members the body names change (null clears one), every other member keeps its stored value; deviceSettings is one member (naming it replaces every device's entry). Members include acceptPlaybackChunks (null = the node's own) and per device deviceSettings → {enabled, maxConcurrency, maxEncodes, streams} (Library jobs 0–16, Max encodes 1–64, Streams 0–32; null = default). 400 when Library jobs or Streams are more than Max encodes. Nodes pick these up from GET /api/cluster/cluster-state. |
| DELETE | /api/cluster-admin/node-settings | {nodeId} | Removes stored settings for a node. |
| POST | /api/cluster-admin/folder-settings | {path, encodingOverrides} | Saves or clears per-folder encoder overrides for a watched folder. |
| GET | /api/cluster-admin/master-time | — | Returns master time for schedule diagnostics. |
| GET | /api/cluster-admin/integration-sync | — | Shows worker integration-sync state. |
| POST | /api/cluster-admin/integration-sync/refresh | — | Forces an integration-data refresh. |
| Method | Path | Inputs | Purpose |
|---|---|---|---|
| GET | /api/health | — | Unauthenticated liveness JSON with UTC timestamp and version. |
| GET | /metrics | — | Unauthenticated Prometheus text exposition. |
| GET | /api/diagnostics/log | lines=200 (1–5000), optional nodeId | Latest operation-log tail, local or proxied. |
| GET | /api/diagnostics/logs.zip | Optional nodeId | Downloads local or remote logs as ZIP. |
| POST | /api/restart | — | Interruptive: stops active work, clears the queue process, and exits for host restart. |
| GET | /api/updates/status | — | Current and latest version, the update settings in effect (on a worker: its master's, with managedBy), and how to update this install (see Updates). |
| POST | /api/updates/settings | { checkEnabled, autoUpdate } | Saves the release-check and automatic-update switches. 409 on a worker: its master owns them. |
| POST | /api/updates/restart | { mode: "now" | "idle" | "force" } | Self-updating installs (the desktop app, a container with the in-container updater): installs a downloaded update. now and idle wind down first (no new encodes start or are dispatched) and restart once the running ones finish; force restarts at once and runs them again afterwards. 400 when nothing is downloaded. |
| POST | /api/updates/notes/sandbox/dismiss | — | Remembers on this install that the note about the Linux AppImage running without Chromium's sandbox was read. |
Connect an ASP.NET Core SignalR client to /transcodingHub. Browser clients
automatically send the Snacks session cookie. The hub supports
JoinGroupAsync(groupName) and LeaveGroupAsync(groupName);
current application broadcasts are predominantly global.
| Event | Typical arguments | Use |
|---|---|---|
WorkItemUpdated | Work item object | Status, progress, transfer, assignment, completion updates. |
WorkItemRemoved | Work item ID | Remove an item from the live UI. |
QueueChanged | None | Refetch paginated queue state. |
TranscodingLog | Work item ID, line | Append a live FFmpeg/log line. |
HardwareDetected | Hardware descriptor | Refresh encoder/device UI. |
ScanProgress | Progress object | Update background scan progress. |
AutoScanCompleted | New-file count, total seen | Refresh scan summary and queue. |
HistoryCleared | None | Refresh catalog/queue after auto-scan history reset. |
EncodeHistoryAdded | Encode-history record | Refresh dashboard analytics. |
EncodeHistoryCleared | None | Clear dashboard client state. |
WorkerConnected | Cluster node | Add a worker to cluster status. |
WorkerUpdated | Cluster node | Update node health, slots, and activity. |
WorkerDisconnected | Node ID | Mark/remove a disconnected worker. |
ClusterConfigChanged | Config-change summary | Refresh cluster mode UI. |
NodeSettingsChanged | Node settings | Refresh device/schedule state. |
ClusterNodePaused | Boolean | Update worker pause state. |
ClusterWarning | Warning message | Surface dispatch/network warnings. |
const connection = new signalR.HubConnectionBuilder()
.withUrl("/transcodingHub")
.withAutomaticReconnect()
.build();
connection.on("WorkItemUpdated", item => console.log(item.id, item.status, item.progress));
connection.on("QueueChanged", () => refreshQueue());
await connection.start();
/api/cluster/*
coordinate trusted Snacks nodes and may change with cluster protocol changes. Prefer
/api/cluster-admin/* for administrative automation.
Every cluster-internal request requires
X-Snacks-Secret: Base64(UTF-8(shared secret)). Credential-sync routes add
LAN-source and active-node checks. The protocol covers:
playback
object to the capabilities of its heartbeat, handshake and capabilities responses (chunk protocol and
compatibility id, ffmpeg build, playback filters and hwaccels, per-encoder self-test results and speed seeds,
validated tone mappers, per-device playback caps). It is absent while the node does not accept chunks, so older
masters and nodes see exactly the payload they always did.
The node routes exist only while the node accepts playback chunks: otherwise every one answers a plain
404, before the secret is checked. They need X-Snacks-Secret like the rest of
/api/cluster/*. Chunk ids are mc_ + 22 letters or digits and segment indexes are decimal;
anything else is a 400 before the node touches its disk. Error bodies are
{"error", "detail", "reason"?, "outcome"?} and never contain a media-source token or the secret (a node's
ffmpeg error text in outcome.error/outcome.standardError can name a path on that node, which
is cluster-internal; the token in any URL it prints is replaced by tok_…). The media-source
route lives on the master, answers only while its media server is enabled, and is authorized by the capability token in
its path instead of the secret (the node's ffmpeg reads it and never holds the secret).
| Method | Path | Inputs | Purpose / response |
|---|---|---|---|
| POST | /api/cluster/media-chunks | Node; chunk work v1 (JSON, at most 4 MB): protocol and compatibility id, chunk id, producer (encoder signature), source (file version plus a shared path or a media-source token), plan, plan hash, k, m (1–64 segments), rung spec and its canonical text, seek preroll, burn-in .sup (base64, at most 2 MB) and offset, deadline seconds | 202 {chunkId, existing}; 400 bad_request; 409 incompatible (another build: protocol, compatibility id, plan hash or spec text differ), signature_mismatch, unsupported (tone mapper, overlay or filter not validated here), source_changed, source_unavailable (also when the node's check of the media-source URL fails — over HTTPS the master's certificate must chain to the CA bundle the node's ffmpeg uses); 413 too_large; 422 unavailable (the subtitle is not PGS); 503 busy with reason chunks, device, disk or testing. The node rebuilds the ffmpeg arguments from exactly this plan and spec. |
| GET | /api/cluster/media-chunks/{chunkId} | Node; wait 0–20 s (default 0) | {chunkId, state, start, end, init, segments, outcome?}, after waiting up to wait for the chunk to end; 404 for an unknown chunk. The master's playback liveness probe asks for a chunk id no master issues (22 zeros) with wait=0 every 2 s while its media server runs: any answer means the node is alive. |
| GET | /api/cluster/media-chunks/{chunkId}/init | Node; wait 0–20 s (default 20) | The chunk's init, streamed from the node's file, with X-Snacks-Content-Sha256 and X-Snacks-Init-Hash; 204 with Retry-After: 0 when it is not there within wait; 409 failed or source_changed, 410 stopped, 422 unavailable (with the outcome) when the chunk ended without it. |
| GET | /api/cluster/media-chunks/{chunkId}/segments/{n} | Node; wait 0–20 s (default 20) | Segment n, streamed, with X-Snacks-Content-Sha256 and X-Snacks-Segment-Info (index, bytes, samples, first PTS, duration, plan start, sync, elapsed ms, base media decode time); the same 204 and terminal answers as the init; 404 when n is outside the chunk. |
| DELETE | /api/cluster/media-chunks/{chunkId} | Node | 204: the chunk's ffmpeg is killed and its files are deleted (also for an unknown chunk). |
| GET HEAD | /api/cluster/media-source/{token} | Master; the capability token; optional Range (one range: bytes=a-b, bytes=a- or bytes=-n) | The bytes of one library file version for one node's ffmpeg: 200/206 with Accept-Ranges: bytes; 416 for several ranges, another unit or a range outside the file; 409 source_changed when the file changed on disk (checked through the opened file, so a file renamed over the path is caught; every token of the file is revoked and keeps answering 409 until it expires or its chunk ends); 404 for an unknown, expired or revoked token, or a request from another address than the node's when the master knows the node's address (its IP, or the addresses its registered host name resolves to; a node known only by a name that does not resolve gets tokens without the address check, logged once). The address is the request's TCP peer (no forwarded header is read), so reads through a reverse proxy in front of the master are refused. Tokens are 256-bit random, held in memory, scoped to the file version and node, and expire at most 120 s after the chunk's deadline. The node's ffmpeg reads this route with redirects off, no proxy, and — when the cluster uses HTTPS — the master's certificate verified against the platform's CA bundle (/etc/ssl/cert.pem on macOS, the distribution's bundle on Linux, or SSL_CERT_FILE); a node without one answers 409 source_unavailable to token chunks. |
SECRET_HEADER=$(printf '%s' "$SNACKS_SHARED_SECRET" | base64 | tr -d '\n')
curl -fsS \
-H "X-Snacks-Secret: $SECRET_HEADER" \
"$BASE/api/cluster/heartbeat"
Besides transcoding, Snacks can serve your movies, shows and music to the Snacks Player desktop app and Snacks for Fire TV,
keeping watch progress, profiles and parental controls in its own database. The media server is
off by default. While it is off, Snacks is a transcoder only: no
mediaserver.db is created, no media-server background work runs (its playback engine is not
even built), the Media Server menu is not shown, the control panel downloads none of the
media server's page scripts (they load when one of its pages or its Settings tab is opened), and every
/api/media/v1 route answers 404 with {"error":"server_disabled"}.
config/mediaserver.db; if that fails, the tab shows why and the media
server stays off. Disabling stops the media server's background work and returns the player
API to server_disabled. Transcoding is unaffected either way, and the media server
never reads or writes snacks.db.
SNACKS_MEDIA_Enabled=true. Any
mediaserver.json property can be pinned with SNACKS_MEDIA_<Property>
(see Environment-variable overrides under Data & backups); pinned
settings show a lock in the tab.
| What | Default location | Notes |
|---|---|---|
| Database | <work>/config/mediaserver.db | Libraries, catalog, player accounts and watch state. Back it up with the rest of config/. |
| Metadata folder | <work>/config/media-metadata | Persistent: artwork, subtitle and keyframe caches, thumbnails. Inside the config volume, so Docker/Unraid installs already persist it. |
| Transcode cache | <work>/transcode-cache | Disposable, size-limited video segments. Use a dedicated empty folder: old cache files are deleted to stay within the size limit. The cache marks its folder (.snacks-transcode-cache) and only ever deletes the files it made; a filesystem root, the work, config or metadata folder, a library folder, or a non-empty folder that is not a cache is refused. |
Both folders can be moved in the Media Server tab; relative paths resolve against the work directory. A path that cannot be created or written is rejected before anything is saved.
In Docker the default transcode cache (/app/work/transcode-cache) is inside the container: map it to a
dedicated host folder on a fast disk (or a tmpfs), so segments are not written into the container's own layer.
The repository's docker-compose.media.yml override does that and pins
SNACKS_MEDIA_Enabled=true; Unraid users can install unraid/snacks-media-server.xml.
Media libraries must lie inside /app/work/uploads (mount extra shares below it, read-only is fine),
and players connect to the web port, 6767.
Players sign in with player accounts, which are separate from the control-panel login and can
never manage Snacks: a player token sent to any other endpoint is refused with 403.
By default players must be on the local network (the same address ranges the control panel
accepts without a login). Allow players outside my local network admits remote
players only while control-panel sign-in is enabled; publish Snacks through your own HTTPS reverse
proxy for that. SNACKS_ALLOW_REMOTE_WITHOUT_AUTH does not apply to players.
Player accounts are created by the administrator only (there is no self-registration) on
Media Server → Players & households or through /api/media-server/players.
A player signs in once per device with a username and password; the device keeps a sign-in (refresh token)
that slides forward for 90 days whenever it is used and gets short-lived (12-hour) access tokens from it.
Snacks stores only SHA-256 hashes of tokens and PBKDF2-SHA256 hashes of passwords (600,000 iterations — older
hashes are upgraded at the next sign-in) and PINs; no API ever returns them.
The Players & households page lists every profile with its avatar, badges (household, restricted,
PIN, cannot sign in), what it may watch and when it was last seen. Add player and Edit set the display
name, username, password (a new one signs the player out everywhere), avatar color, household flag, whether it may sign
in, the maximum movie and TV rating, unrated titles, library access and the PIN. While control-panel sign-in is off the
page locks the parental controls and PIN (removing what is set still works) and links to Settings → System → Security;
if restrictions exist then, it warns that they are not tamper-proof. Devices lists where the player is signed
in (platform, last seen, household device) with Sign out per device and Sign out everywhere;
Delete names what goes with the profile and asks for its username. An open player hears about every such
change at once over its event stream (auth.revoked).
A library is a named set of folders holding one kind of media, video (movies and shows) or music. Add them under Media Server → Libraries. Folders must lie inside the folders Snacks may read (the same rule as the transcoder's library browser); a folder may belong to two libraries, which the page points out because it is usually a mistake.
ProbeParallelism at a time). Music albums are built from tags once every track of a
folder has been read. Files still being copied are checked again a little later.
MissingFileGraceDays; renamed and moved files are recognised and keep
their watch progress — also when a library's folder is changed to the same files at a new path (a
new mount point). Files are not marked missing under a folder that cannot be read, a library folder
that is absent or empty, or an empty folder that used to hold sub-folders (an unmounted share inside
a library folder); the page warns instead. If more than MissingFileGuardPercent of a
library's files would become unavailable in one scan — missing, or left in no library (an unmounted
drive, a mistyped folder) — the scan
changes nothing and the page shows a warning with a Scan anyway button; a scheduled scan is
then retried after 15 minutes, and "last scanned" keeps the time of the last scan that was applied.
revision; players are told which library
and which titles changed, so they refresh only what is affected.
mediaserver.json)| Property | Default | Meaning |
|---|---|---|
Enabled | false | Runs the media server. |
ServerName | empty (“Snacks”) | Name players show (at most 64 characters). |
AllowRemotePlayers | false | Admit players from outside the local network (requires control-panel sign-in). |
MaxSessionsPerAccount | 3 | Simultaneous video playback sessions per player account (1–50), pending transcodes included; one more answers 429 stream_limit. Music never counts. |
TranscodeThroughputPercent | 70 | Share (10–100 %) of each encoder's measured capacity playback transcodes may reserve. A session reserves the time its top quality needs on its encoder (1 / measured speed, by encoder, source, quality and pipeline — seeded by a short benchmark when the media server starts, refined by every chunk). A new session that does not fit is offered fewer, lower qualities, else answered 503 capacity; running sessions keep theirs. |
TranscodeCacheMaxGb | 20 | Transcode cache size limit (1–100000 GB). |
PlaybackLocalMaxConcurrency | 2 | Video transcodes for players this server runs at once (1–16); more wait in a queue ordered by when their segments are needed. One session may use every slot no one else needs — its next chunks inside the ~2 minutes it buffers ahead are encoded side by side — and gives one up at once to another session's first chunk. |
PlaybackLocalMaxCopyRuns | 8 | Remux and audio-conversion runs for players this server lets write ahead at once (1–64); counted separately from transcodes (a transcoded session also runs one of these for its AAC audio). A run fills its player's buffer and then waits for the player; a waiting run does not count here. While a new player waits for its first segment and every run is taken, each run already more than 30 s ahead of its own player pauses and gives its place up, so simultaneous starts queue only behind other first segments, never behind read-ahead. A remux copies (an AAC track too); converting AC-3, E-AC-3, DTS or TrueHD to AAC runs at 25–105× realtime per core (measured), about 1–4 % of a core per playing session. These runs always stay on this server, also when cluster nodes encode the video. |
PlaybackLocalMaxResidentRuns | 256 | Remux and audio processes kept alive for players at once, waiting ones included (1–4096): one per HLS session — a Direct Stream copy and its audio share one on Linux and macOS, two on Windows — about 10 MB each. At the limit the one that has waited longest stops (it starts again where its player needs it), and a new HLS session whose processes would not fit is answered 503 capacity with reason: "busy". |
PlaybackEgressLimitMbps | 0 | Total upload playback may use, in Mb/s (0 = unlimited). A new session whose top quality would exceed what is left gets lower qualities (a Direct Play version is transcoded under a cap), else 503 capacity. |
PlaybackEncodeAheadLowerRung | false | Also encode ahead the quality just below the one a player watches, at the lowest priority and only while playback encoders are otherwise idle. |
PlaybackLocalEncodingEnabled | true | Encode playback chunks on this server too. Off sends every playback transcode to the cluster nodes that accept playback chunks (this machine's encoders stay free for batch work) and never falls back to this server: with none ready, new transcoded sessions get 503 capacity and running ones wait for a node. Direct Play, Direct Stream copies and audio always stay on this server. |
PlaybackLeaseWaitSeconds | 120 | How long (0–1800 s) the transcoder waits for a player to stop reading a file before it replaces it after an encode, or before Library Health deletes it; afterwards it proceeds and that playback ends with source_changed. Files nobody plays never wait. |
ArtworkCacheMaxMb | 2048 | Size limit (64–1048576 MB) for resized artwork. |
TrickplayCacheMaxGb | 20 | Size limit (1–100000 GB) of seek thumbnails (about 9–25 MB per two-hour film). The least recently used titles' thumbnails are removed beyond it, never those of a title someone is playing or used within the last hour; they are made again the next time the title plays. |
PreviewsEnabled | true | Motion previews on players' Home: about 20 s of a title, muted, at most 1920×1080 and about 11 MB, made in the background for the titles Home shows. Off: none are made and Home shows the still picture. |
PreviewsBackfill | true | Also make previews for the rest of the library while idle, newest first, until previews use 80 % of PreviewCacheMaxGb. Off: only the titles Home shows and recent additions get one. |
PreviewCacheMaxGb | 10 | Size limit (1–100000 GB) of motion previews (about 900 at 10 GB); the least recently shown are removed beyond it. |
MediaJobConcurrency | 1 | Background extras (thumbnails, previews, resume frames) made at the same time (1–4), on the CPU at the lowest process priority. Applies the next time the media server starts. |
MediaJobsPaused | false | Pauses background extras: queued work waits; thumbnails for a title someone starts playing are still made. |
MetadataPath | empty (default folder) | Metadata folder. |
TranscodeCachePath | empty (default folder) | Transcode cache folder: a dedicated folder (empty, or one the cache already marked); saving refuses one that overlaps the work, config, metadata or a library folder. |
DefaultScanIntervalMinutes | 360 | Scan interval for new libraries (5–10080 minutes); 0 = manual. |
MissingFileGraceDays | 30 | How long (1–365 days) missing files are kept before purge. Watch progress stays on the title. |
MissingFileGuardPercent | 20 | A scan that would mark more of a library missing (1–100 %) changes nothing and warns instead. |
ProbeParallelism | 2 | Files probed in parallel during scans (1–16). |
FetchTmdbMetadata | true | Match titles with TMDB and fetch their titles, descriptions, cast and artwork. Off keeps everything local: nothing is sent to TMDB, titles use their folder and file names, and what was already fetched stays; turning it back on queues unmatched titles at once. |
FetchMusicMetadata | true | Match music with MusicBrainz and fetch artist photos, biographies, genres and missing album covers (MusicBrainz, Cover Art Archive, Wikipedia, Wikimedia Commons, and fanart.tv). Off keeps music local: nothing is sent, names and covers come from the files, and what was already fetched stays; turning it back on queues music at once. |
MetadataLanguage | en-US | Language of titles, descriptions and title logos fetched from TMDB (two-letter language, optional region: de-DE, fr). Missing translations fall back to English. |
RatingCountry | US | Whose content ratings parental controls use: US, GB, CA, AU, NZ, IE, DE, FR or NL. Titles without a rating for that country use their US rating. |
HomeMinGenreRowItems | 4 | Fewest titles (1–20) a genre row on players' Home needs. A thinner genre is skipped and the next of the profile's larger genres takes its place, so Home never shows one-card genre rows. |
PinRenewalRequiresPlaying | true | A PIN profile's token is renewed during playback only while a session of it on the device reported an advancing playing position within PinRenewalPlayingWindowMinutes: a progress report with state playing more than 0.5 s past the position the session last recorded (paused and buffering reports never count), and while the latest report of the device's live sessions of the profile is not paused (a pause renews nothing at once). A paused profile goes to the PIN screen when its token runs out; the next playing report lets renewals succeed again. Another device's playing, an ended session and one past its lease never count. false: a live session is enough, paused or not. |
PinRenewalPlayingWindowMinutes | 10 | The window (1–120 minutes) of PinRenewalRequiresPlaying. |
AccessTokenLifetimeMinutes | 720 | How long (3–10080 minutes) a player's access token lasts; a PIN profile asks for its PIN again when it runs out (unless renewed while playing). Applies to tokens issued after saving. |
PinRenewedTokenLifetimeMinutes | 30 | How long (3–1440 minutes) a PIN profile's token renewed while playing lasts. |
PinRenewalHorizonHours | 24 | No renewal lasts past this long (1–168 hours) after the PIN was entered. It bounds renewals only: a sign-in with the PIN itself lasts AccessTokenLifetimeMinutes, even when that is longer. |
TokenRequestBurst / TokenRequestRefillSeconds | 10 / 6 | POST /auth/token calls a device may make in a burst (1–1000), and how often (1–3600 s) one more becomes available. |
PinLockoutFreeFailures / PinLockoutInitialSeconds / PinLockoutMaxMinutes | 3 / 5 / 15 | Wrong PINs before a lock (0–20; the last of them starts the first lock, and 0 and 1 both lock at the first wrong PIN), the first lock (1–3600 s; each further wrong PIN doubles it) and the longest (1–1440 minutes, at least the first). |
PlaybackLeaseSeconds | 60 | A playback session with no progress report for this long (30–600 s) ends expired; the create answer's leaseSeconds. |
PlaybackStallTimeoutSeconds | 30 | A playback producer that writes nothing for this long (10–600 s; more for long segments and leads) is stopped and restarted. A cluster node's chunk gets at least its node segment wait (ClusterNodeSegmentTimeoutSeconds) plus 5 s: that wait is what ends it. |
PlaybackLeadGraceSeconds | 120 | How long (0–1800 s; 0 = never) a left quality's far-start decode is kept; it yields to any start a viewer waits for. |
ClusterNodeSegmentTimeoutSeconds | 10 | How long (5–300 s) past twice a segment's expected encode time (and its chunk's decode lead) a cluster node's next playback segment is waited for before the chunk goes to another producer. The whole range takes effect: the wait is capped at 3 minutes plus whatever this adds above its default 10 s (before the decode lead); the stalled-producer check (PlaybackStallTimeoutSeconds) waits at least this long plus 5 s for a node's chunk, and the node's deadline for the chunk grows by what this adds above 10 s, so neither ends a stalled chunk first. This wait is for a node that stalls, not one that keeps producing below its speed: a chunk the node is still producing at the deadline it had before the raise (4 × its expected time + 60 s) goes to another producer then and the node cools off — judged as of that deadline, not at the next long-poll after it — and so does, before that deadline too, a chunk two of whose files (its init included) each took longer than the default wait's bound to come (a node producing below the default wait's pace; counted per chunk, an on-time file in between does not start the count over); only a chunk silent longer than the default wait's bound at that deadline is waited for, up to the rest of this wait (a node frozen from the start, or whose stall never ends, brings no late file) — so below the one-hour cap every node chunk ends by its node's deadline. At the hour cap — a chunk expected to take more than (3 540 s − the raise) ÷ 4, 13½ to 15 min: a far start in a film with very few keyframes — the node's one-hour deadline (+30 s grace) can end a chunk before this wait does (a stall that began late, or a decode lead above the hour and the node's 30 s grace less the wait's own part: ~3 380 s at a 250 s wait; at the default wait only where its own part — 10 s plus twice a segment's expected time — is over the 30 s grace, a long segment or a slow node, since the wait counts at most the hour of lead); the rest is then made elsewhere. This wait applies only while no viewer needs the chunk's next file within 10 s: a node chunk a viewer is held on that delivers nothing for about 1.5 × that file's expected time + 0.75 s (at least 2.5 s) goes elsewhere at once whenever another producer can take it; only with nothing else to make it does a viewer wait out this wait behind a node whose encoder stalled. A node that stops answering altogether is caught in seconds, whatever this is. |
ArtworkPrerenderEnabled | true | Make Home's artwork widths in the background as images arrive; the work waits while a playback starts or decodes a lead on this server (a cluster node's work does not count), resuming 3 s after, at least one image per 30 s — and that image waits before each of its steps for a moment with no encode on this server before its first segment (at most a minute per step: at worst ~270 s per image, the 30 s floor and four steps); a resize running when a playback starts pauses between its steps and goes on with what it made, nothing done twice. An image whose resize keeps failing — or whose original can no longer be decoded — is put off on its own and skipped after three failures in a row until its content changes (a rescan of the same image does not count); a player's request for an original whose decode was refused is answered "no image" at once, without decoding it again, until its content changes (a refusal that may pass — an image too large for the memory free at the time, or a resize or encoder that returned nothing — is not remembered: it is decoded again, with a warning; a variant of the image made later forgets a refusal). An original that is there but cannot be read (no permission, a file another program holds locked, a network share's read error) is answered like missing artwork ("no image") with one warning per original naming it — not remembered, so the next request reads it again and is served once it can be read. Off: each width is made when first asked for. |
PinRenewalCapToRuntime | false | A renewal never lasts past the moment the title being played would end if watched straight through from where its stream started, plus 30 minutes (and never past 24 hours after the PIN). Without the two rules, whoever holds both a device's refresh token and a PIN-verified token can keep that profile unlocked up to 24 hours after the PIN by keeping a stream open (12 hours more than the token alone); a device sign-out or a PIN change ends it at once. |
artwork/), named by its content. Only JPEG, PNG and WebP images up to 20 MB and
40 megapixels are accepted, never SVG, and images from the internet come only from https://image.tmdb.org.
Resized copies are made the first time they are shown and kept within ArtworkCacheMaxMb (least
recently used first out); an original that no title or person uses any more is removed a day later. If you move
the metadata folder, move its artwork/ folder with it. Episode stills and backdrops are fetched at
their full size, and up to four backdrops without a burned-in title are kept per movie or show for players'
Home (about three more images per title the first time it is matched). Each title logo's ink (light or dark) is
measured once when it is stored.
cover, folder,
front or album image (JPEG, PNG or WebP) next to the tracks, else the picture embedded in
a track. An artist's image is a mosaic of its four newest album covers (or its newest cover). With
Fetch music info and artwork online on, albums without a cover and artists also get artwork online (see
Music below). A cover image added to an album that has none is picked up within a few hours; a replaced cover image
is picked up the next time the album's tracks are scanned as changed.
RatingCountry; seasons and episodes use their show's
rating, and music is never rated.
SNACKS_DEMO_MODE=1 with
SNACKS_DEMO_FIXTURES=<folder> (a folder holding fixtures/movies.json and
fixtures/tv.json, e.g. SnacksPlayer's demo/) takes metadata and artwork from those
local files instead of TMDB, even when a key is configured, and never uses the network.
Movies and shows start under the name of their folder or file. In the background Snacks then looks each one up (TMDB, or the demo fixtures) and fills in its title, description, artwork (poster, backdrop, title logo, episode stills, cast photos), cast and crew, genres, keywords, trailers, content rating and episode titles. Open Media Server → Catalog & matching to see how titles were recognized and to correct them.
{tmdb-123} / [tmdbid-123] tag, Sonarr's or
Radarr's own id for the file, an IMDb / TVDB id (tag or Sonarr/Radarr) translated by TMDB, else a search by title
and year. A search result is used only when exactly one title has the same name (or, failing that, the same
original name) and the same year — within one year — and movies need a year. When several titles match, or none
does, the title stays unmatched with the reason shown on the page; it is never guessed.
While the media server is on, Snacks makes three kinds of pictures in the background, on this server's CPU at the lowest process priority (below batch encodes and below playback), one at a time by default. Background work yields to playback between steps (one thumbnail sheet, one preview encode): while players need the encoders the next step waits, and a title someone starts playing stops a running encode at once so its seek thumbnails come first (the stopped job starts again afterwards). The batch queue, its slots and the dashboard are unaffected. Nothing of this runs while the media server is off, and a cluster node never makes any.
PreviewsBackfill) the rest of the library. One encode takes seconds (1080p) to about a minute (4K HDR) on
an idle server.
Their URLs carry random keys that cannot be derived from anything a player knows, and they appear only in responses a
profile may see (a restricted profile never gets one for a title it cannot see). Disk: TrickplayCacheMaxGb
and PreviewCacheMaxGb under the metadata folder (trickplay/, previews/); resume frames
live with the artwork. A kind never stays above 110 % of its limit (the least recently used go first, never what a live
session uses), and new work for it waits while it is full. Extras of a file that left every library go at the next
clean-up; those of a file missing from disk go after a day; those an older version of Snacks made go at the first clean-up
after an upgrade (and are made again when needed). A job whose file changes size or date on disk stops within seconds; a
file that is only out of reach for a moment (a network share reconnecting) keeps its job and its extras, and seek thumbnails,
a preview or a resume frame whose file goes out of reach while it is being read (also during an MPEG-TS's keyframe scan
or a preview's encode) are put back and made later — never published half-made. A file that stays out of reach for
several minutes fails the job like any other failure: it is tried again later, and after three failures only
Retry failed or a new file version starts it again.
Media Server → Background jobs shows what runs and waits, disk per kind against its limit and recent
problems, pauses or resumes the work and retries failed jobs. Background FFmpeg runs are judged by the processor time they
get, never by the clock alone: one that waits behind busy encoders for processor time (or for its file) is put back without
counting as a failure. Only an FFmpeg error, one that keeps using processor time without making progress, or one that uses
far more than such a job ever needs counts (three, then it is not tried again until Retry failed or a new file
version).
While control-panel sign-in is off (the default), anyone on your network can open Now playing and see what every profile is watching right now; the page says so. History — a lasting record of every profile's viewing, kids included — is shown only while sign-in is on (like parental controls). Turn sign-in on under Settings → System → Security to protect them.
No API endpoints match the current filter.
Two route families. /api/media-server/* are control-panel endpoints: they use the
same authentication as the rest of /api/* and work while the media server is off.
/api/media/v1/* is the versioned player API: it ignores the control-panel cookie and
API key, accepts only player tokens (Authorization: Bearer) on routes that need one,
applies the local-network rule described in Who can connect, and while
the media server is off answers every request with 404 server_disabled.
Every error under /api/media/v1 uses one envelope:
{"error":"<code>","message":"…","retryAfterSeconds":n} (retryAfterSeconds
only when relevant). The /api/media-server routes use the same envelope for the errors the
media server itself produces (invalid input, unknown ids, server_disabled, server
failures); control-panel sign-in failures on those routes (401/403 when you are not signed in) are the
transcoder's usual responses, the same as for the rest of /api/*. A /api/media-server request
with a method other than GET/HEAD must carry X-Requested-With: XMLHttpRequest (the control panel sends
it), a JSON Content-Type, an X-Api-Key or an Authorization header, else
403 forbidden — a page on another site cannot send any of them, so it cannot post to these routes even
while control-panel sign-in is off. Codes include
bad_request (400), admin_auth_required (400, admin routes),
unauthorized (401), pin_required, pin_invalid and
forbidden (403), not_found and server_disabled (404),
device_limit (409, with devices), media_unavailable (409), session_expired (410),
dolby_vision_p5_unsupported, hdr_tonemap_unavailable, transcode_unavailable and
no_video (422, a version this device cannot play), subtitle_burnin_unavailable (422, an
image subtitle this server cannot burn in — a format other than PGS, VobSub and DVB, such as XSUB, or no overlay filter), stream_limit (429, with
activeSessions), bad_request with status 413 (a player request
body over 16 KB on sign-in routes or 64 KB elsewhere), with status 408 (a request body that stopped arriving: slower than the server's
minimum request-body rate once its 5 s grace is over) and with status 400 (any other body the server rejects while reading it), unsupported_media_type (415, a body
that is not JSON or is compressed), too_many_attempts (429), server_error (500) and
capacity (503). Throttled and busy answers carry retryAfterSeconds and a
Retry-After header.
| Method | Path | Inputs | Purpose / response |
|---|---|---|---|
| GET | /api/media-server/settings | — | {settings, envLocked, envWarnings, defaults:{metadataPath, transcodeCachePath}, status}; envLocked lists camelCase properties pinned by SNACKS_MEDIA_*; envWarnings lists each SNACKS_MEDIA_* value the server cannot use, with the value it runs instead: {variable, field, value, message, using} — out of range: the default; breaking a rule against a saved value (the longest PIN lock shorter than the first): the default while the saved value cannot hold it; not a value of its setting's type at all (a number that is not one): skipped, the field's own value runs and stays editable (not in envLocked). |
| PUT | /api/media-server/settings | Complete settings object (camelCase mediaserver.json properties) | Saves and applies at once (enable/disable without a restart); returns the same shape as GET. Out-of-range values and unwritable storage paths return 400 bad_request and nothing is saved. Every rule is judged on the values the server runs, so a SNACKS_MEDIA_* value never refuses a save (it is listed in envWarnings); a submitted value that breaks a rule against an environment value in force is refused beside its field (fieldErrors), the message naming the variable, its value and what the server runs — a submitted value is never replaced silently. So does a body that is not a complete settings object: a member the settings do not have (such as the GET answer's {settings, envLocked, …} sent back as is, or a misspelt name) or no enabled. Env-pinned properties keep their values. |
| GET | /api/media-server/status | — | {state: off|starting|on|error, enabled, configuredEnabled, nodeRole, reason, error, adminAuthEnabled, remotePlayers:{setting, effective}, database:{path, exists, sizeBytes}, storage:{metadata, transcodeCache}, counts}; counts (libraries, catalog items, files, players, devices) only while running. |
| GET | /media-server/fragments | — | HTML for the control panel (not JSON): the navbar's Media Server menu (#mediaServerNav) and the Settings → Media Server pane (#mediaServerSettingsPanel), whatever the media server's state. A control-panel page rendered while the media server is off carries neither and loads them from here when the Settings tab is first shown or the media server is turned on. |
| GET | /api/media-server/libraries | — | {items:[Library], defaultScanIntervalMinutes}. Library = {id, name, kind: video|music, folders, scanIntervalMinutes, trickplayEnabled, createdAt, lastScanStartedAt, lastScanCompletedAt, nextScanAt, revision, scan:{state: idle|scanning|probing|matching, startedAt, completedAt, folder, queued, counts:{filesSeen, filesAdded, filesChanged, filesMissing, filesReturned, filesRebound, filesDeferred, filesPurged, itemsPurged}, probePending, itemsFound, itemsMatched}, counts:{movies, shows, seasons, episodes, artists, albums, tracks, files, missingFiles, probeErrors}, error, warnings, missingGuardTripped, overlaps, probeErrors:[{fileId, path, error, attempts, nextAttemptAt}]} (up to 5 failed-probe examples). |
| POST | /api/media-server/libraries | {name, kind, folders, scanIntervalMinutes?, trickplayEnabled?} | Creates a library and queues its first scan: 201 {library, warnings}. Folders must be absolute, exist and lie inside the folders this server may read; folders shared with another library are allowed and listed in warnings. scanIntervalMinutes: 0 = manual, 5–10080, default from settings. trickplayEnabled defaults to false. Invalid input (including an unknown kind) → 400 bad_request naming every problem. |
| GET | /api/media-server/libraries/{id} | Library ID | One Library (shape above) or 404 not_found. |
| PUT | /api/media-server/libraries/{id} | {name?, folders?, scanIntervalMinutes?, trickplayEnabled?} | Updates a library (its kind cannot change); omitted fields keep their values. Changing folders queues a scan; files under removed folders leave the library, and the same files found under a new folder keep their ids and progress (unless the originals are still in place in a folder of another library that holds them: they then stay with that library, and the copies are indexed as new files). If more than MissingFileGuardPercent of the library's files would become unavailable (missing, or left in no library), that scan is refused like any other until Scan anyway. 200 {library, warnings}. |
| DELETE | /api/media-server/libraries/{id} | Library ID | Deletes the library: 200 {id, deleted: true}. Movies, shows, music, watch progress and history are kept; files no other library holds become unavailable and are removed after the missing-file grace period. Titles no library holds any more leave players' browse lists, letter index, facets and search at once; a profile that played or listed one still sees it (greyed) in its own Continue watching, My List and history. |
| GET | /api/media-server/libraries/{id}/status | Library ID | {libraryId, scan, warnings, missingGuardTripped, error} — the live part of Library. |
| POST | /api/media-server/libraries/{id}/scan | {folder?, ignoreMissingGuard?} | Queues a full scan, or with folder (inside the library's folders) a rescan of that folder only: 202 {libraryId, folder, ignoreMissingGuard}. ignoreMissingGuard: true applies changes the missing-file guard refused ("Scan anyway"). |
| POST | /api/media-server/libraries/{id}/retry-probes | Library ID | Probes every file whose last probe failed again now: 200 {libraryId, files}. |
| GET | /api/media-server/catalog/status | type | {matcher:{state: idle|matching|waiting|paused|unavailable, providerState, provider: tmdb|fixtures|null, demoMode, message, startedAt, current, processed, written, notMatched, retryAt, lastPassAt}, counts:{unmatched, ambiguous, matched, manual, locked, pendingEpisodes}, arr:{radarr, sonarr}}; type (as the list's; default movie,show) chooses what counts cover, music:{on} says whether artists and albums are matched with MusicBrainz, pendingEpisodes = episodes of matched shows TMDB has no details for yet; arr.* = {configured, refreshedAt, titles, files, lastError, nextAttemptAt}. The matcher part is also pushed live as the SignalR event MediaServerCatalogStatus. |
| GET | /api/media-server/catalog/items | state (attention [default] | unmatched | ambiguous | matched | manual | locked | all), type (comma list of movie, show, album, artist; default movie,show), libraryId, q (title contains, ≤ 200), skip, take (1–200, default 60) | {items:[CatalogEntry], total} by sort title. CatalogEntry = {id, type, title, originalTitle, year, artist, matchState: unmatched|matched|manual|local, locked, issue: notfound|ambiguous|needsyear|gone|providererror|null, note, attempts, nextAttemptAt, tmdbId, imdbId, tvdbId, musicBrainzId, posterKey, available, addedAt, refreshedAt, libraries, counts:{children, episodes, unmatchedEpisodes, files}}. attention = unmatched and not locked, or with a recorded problem. |
| GET | /api/media-server/catalog/items/{id} | Item ID | {item: CatalogEntry, overview, backdropKey, logoKey, colorsJson, contentRating, files, seasons, tracks}: a movie's (or episode's, track's) files = [{id, path, fileName, sizeBytes, width, height, videoCodec, edition, durationSeconds, available}]; a show's seasons = [{id, index, title, episodes:[{id, index, parentIndex, title, matchState, note, thumbKey, files}]}]; an album's tracks in the episode shape. 404 not_found for an unknown id. |
| GET | /api/media-server/catalog/search | type (movie | show | album | artist), q (1–200 characters), year, artist (albums) | Searches TMDB (or the demo fixtures) for the fix-match picker: {provider, results:[{tmdbId, type, title, originalTitle, year, releaseDate, overview}]} (text only; no images are fetched). Artists and albums search MusicBrainz, ahead of the background matching: {provider: "musicbrainz", results:[{musicBrainzId, type, title, year, kind, disambiguation, country, artist}]}; music turned off → 400 bad_request. No provider → 400 bad_request with the reason; TMDB unreachable or busy → 503 capacity with retryAfterSeconds. |
| POST | /api/media-server/catalog/items/{id}/match | {tmdbId} or {musicBrainzId} | Fix match for a movie or show: fetches the TMDB title and its artwork, re-keys the item (a show moves with all its seasons, episodes and files) and writes it as a manual, locked match. If another title already has that TMDB id, the two are merged and every player's progress, watched marks, My List and history are kept: 200 {item, mergedInto, message} (mergedInto = the surviving id when it is not {id}). Unknown TMDB id → 404 not_found; transient TMDB failure → 503 capacity. For an artist or album, musicBrainzId (an id or musicbrainz.org link: the artist, or the album's release group or one of its releases) is fetched now and written as a manual, locked match; tag names and local art stay. |
| POST | /api/media-server/catalog/items/{id}/unmatch | Item ID (artist or album) | Removes the MusicBrainz match and everything fetched online for it (genres, biography, credits, online photo or cover, background, logo) and keeps it as it is (locked) until it is refreshed or its match is fixed; tag names and local art stay: 200 {item, message}. |
| POST | /api/media-server/catalog/items/{id}/split | {fileId, tmdbId?, title?, year?, season?, episode?} | Moves one file (version) of the movie, episode or track {id} onto the item it really is; watch progress stays on {id}. Movies: tmdbId (matched and locked like a fix match) or title + year (a separate title, locked); episodes: season + episode of the same show; tracks: title of a separate, locked track at the same position. 200 {item, message} with the item the file now belongs to; a file not linked to {id} → 400 bad_request. |
| PUT | /api/media-server/catalog/items/{id}/lock | {locked} | Locks a title (automatic matching never changes it; an unmatched title keeps its local name) or unlocks it (an unmatched title is retried at once): 200 {item, message}. |
| POST | /api/media-server/catalog/items/{id}/refresh | Item ID (movie, show, artist or album) | Re-reads the title from TMDB now, bypassing cached responses and fetching its images again (an unmatched title is searched again; a locked manual match is refreshed and stays locked): 200 {item, message}; transient TMDB failure → 503 capacity. Artists and albums are re-read from MusicBrainz the same way; one kept as it is or unmatched is unlocked and matched again. |
| POST | /api/media-server/catalog/refresh | — | Retries every unlocked unmatched title and refreshes every unlocked match in the background, ignoring cached TMDB answers (images already stored are reused), artists and albums too while online music info is on: 202 {queued}. Without either (music off, and no metadata provider: TMDB turned off in the media server settings, a key of your own that can't be used, demo fixtures missing) nothing is queued: 400 bad_request with the reason. |
| GET | /api/media-server/artwork/{key}?w= | key: 64 lower-case hex characters (the SHA-256 of the stored original); w: 32, 92, 185, 342, 500, 780, 1280, 1920, 2560 or 3840 (omitted = the largest) | Artwork for the control panel's catalog pages. Served at w, or at the original's own width when the original is narrower (never enlarged and never cut down to a smaller listed width; omitted w = 3840 or the original's width; an original narrower than 32 px is served as is); WebP, or PNG for images with transparency. Cache-Control: private, max-age=31536000, immutable and an ETag (If-None-Match → 304). Unknown or malformed key → 404 not_found; any other w → 400 bad_request. Reads files only, never the database. |
| GET | /api/media-server/players | — | {items:[Player], adminAuthEnabled, notTamperProof, ratingCountry, ratings:{movie:[{label, rank}], tv:[{label, rank}]}, libraries:[{id, name, kind}], rules:{usernamePattern, passwordMinLength, pinPattern, maxDevicesPerUser, displayNameMaxLength, avatarPalette}} (avatarPalette = the #rrggbb colors automatic avatars use). Player = {id, username, displayName, avatar:{color, initials}, avatarColor, isHouseholdProfile, enabled, hasPin, restricted, maxMovieRank, maxMovieRating, maxTvRank, maxTvRating, allowUnrated, allLibraries, libraryIds, createdAt, lastSeenAt, activeDevices} (ratings are labels of the configured rating country). notTamperProof = restrictions exist while control-panel sign-in is off. Never contains password, PIN or token hashes. |
| POST | /api/media-server/players | {username, password, displayName?, pin?, avatarColor?, isHouseholdProfile?, enabled?, maxMovieRank?, maxTvRank?, allowUnrated?, allLibraries?, libraryIds?} | Creates a player profile: 201 PlayerDetail ({player, devices, counts:{devices, activeDevices, itemStates, history}}). Usernames: 3–64 letters, digits, . _ -, case-insensitive and unique; passwords 8–1024 characters; PINs 4–8 digits; ranks 0–18 or a certification of the rating country (e.g. "PG-13"); allLibraries: false needs at least one known libraryIds. Invalid input → 400 bad_request naming every problem. A rating limit, allowUnrated: false, a library restriction or a PIN while control-panel sign-in is off → 400 admin_auth_required. |
| GET | /api/media-server/players/{id} | Player ID | PlayerDetail; counts say what deleting the player would remove. Unknown id → 404 not_found. |
| PUT | /api/media-server/players/{id} | {username?, displayName?, avatarColor?, isHouseholdProfile?, enabled?, maxMovieRank?, maxTvRank?, allowUnrated?, allLibraries?, libraryIds?} | Partial update: omitted members keep their value; null removes a rating limit. Adding or changing a restriction needs control-panel sign-in (400 admin_auth_required); removing one does not. Changing the household flag, enabled state, ratings, unrated or library access makes the player's access tokens fail at once; disabling also signs every device out. 200 PlayerDetail. |
| DELETE | /api/media-server/players/{id} | Query confirm = the player's username | Deletes the player with its tokens, devices, watch progress / watched / My List rows, history and library access: 200 {id, deleted: true, removed:{devices, activeDevices, itemStates, history}}. Other players' history on its devices is kept. Missing or wrong confirm → 400 bad_request. |
| PUT | /api/media-server/players/{id}/password | {password} | Sets a new password (8–1024 characters) and signs every device of the player out: 200 PlayerDetail. |
| PUT | /api/media-server/players/{id}/pin | {pin} | Sets or changes the PIN (4–8 digits; needs control-panel sign-in, else 400 admin_auth_required). The player's access tokens fail at once; devices stay signed in and ask for the new PIN. 200 PlayerDetail. |
| DELETE | /api/media-server/players/{id}/pin | Player ID | Removes the PIN (access tokens fail at once; the profile then unlocks without a PIN): 200 PlayerDetail. |
| GET | /api/media-server/players/{id}/devices | Player ID | {items:[{id, name, platform, createdAt, lastSeenAt, expiresAt, revokedAt, householdScoped, active}]}, most recently seen first (lastSeenAt is updated at most hourly). |
| DELETE | /api/media-server/players/{id}/devices/{deviceId} | Player ID, device ID | Signs that device out (its sign-in and every access token minted on it): 200 PlayerDetail; a device of another player → 404 not_found. |
| POST | /api/media-server/players/{id}/sign-out | Player ID | "Sign out everywhere": every device of the player is signed out and every access token of the player stops working, including on household devices of other players: 200 PlayerDetail. |
| GET | /api/media-server/sessions | — | Live playback sessions, oldest first: {items:[{sessionId, userId, deviceId, deviceName, itemId, title, versionId, method, transcodeReason, positionSeconds, startedAt, expiresAt, planMode, sourceClass, videoRange, toneMapper, burnInSubtitleId, audioIndex, subtitleId, limitedBy, activeVariantId, pipeline, measuredSpeed, measuredChunks, clientState, playhead, jobs, variants:[{id, width, height, bitrate, codec, frameRate, encoder, pipeline, toneMapper, burnIn, device, expectedSpeed, speedBasis}], reservation:{device, share, egressBitsPerSecond, pinnedBytes}}], created, ended, admission:{throughputShare, egressBitsPerSecond, cacheBytes, reserved:{sessions, deviceShares, egressBitsPerSecond, pinnedBytes}}, engine}. Per session: planMode copy (Direct Stream) / twoLevel (transcode) / fixed (not indexed yet), null for Direct Play; videoRange SDR/PQ/HLG; pipeline of the variant the client fetches (activeVariantId, else the top one): direct, copy, plain, burnin, tonemap-{mapper}, tonemap-{mapper}+burnin; measuredSpeed = the session's transcode chunks in × realtime (moving average, null until one finished); each variant's expectedSpeed is what admission books (speedBasis measured, benchmark or default); reservation = its share of the encode device, upload and cache (null once released). created/ended count since Snacks started; engine is the playback engine's snapshot (slots, jobs, stream sets, cache, counters); among engine.counters for films whose keyframes are minutes apart: sequentialRuns, preparingAnswers (requests answered reason: "preparing"), indexScans (keyframe scans asked for because a file without an index found no keyframe), leadGraceKept (qualities kept decoding after the player left them) and leadGraceYielded (of those, the ones stopped because a viewer waited for something else). Cluster playback adds, per session, producers:[{producer, nodeId, device, encoder, segments, share, runningChunks}] (who made its transcoded segments so far: local is this server, otherwise a node's host name and id; share 0–1; most segments first), mainProducer and transcodeNodes (the host names of the nodes that may produce its qualities now; players see the same nodes as opaque labels node- + 8 hex characters in transcode.nodes); each running transcode job in engine.jobs names its producer, nodeId, device and encoder, and engine.producers totals segments and running chunks per producer since start. The response adds cluster:{localEncodingEnabled, localRunning, localCapacity, placedLocal, placedRemote, transcodeSlots, playbackRows, mediaSourceTokens, mediaSourceBytes, nodes:[{nodeId, name, state, compatible, sourceRoute, overheadSeconds, encoders, running, capacity, devices:[{device, running, capacity}], sourceBytes, lastHeartbeat}]}: this server's local playback encoding, every node that accepts playback chunks with its state (ready, testing, failed, incompatible, stale, cooling, excluded), slots per device, source route (shared or token) and measured overhead, the playback slots booked in all and the live media-source tokens (a count, never a token). Each session also carries profileName (the profile's display name), itemType, an episode's showTitle, seasonNumber and episodeNumber, durationSeconds and readyAheadSeconds — how far past playhead the segments of the variant the player fetches are ready on this server without a gap (the server-side buffer; null for Direct Play and before the first video request). The names are one database read (two while an episode plays), made only while sessions exist. Used by Media Server → Now playing, which reads it when sessions start or end (the MediaServerPlaybackStatus SignalR event) and every 2 s while sessions exist and the page is visible. |
| DELETE | /api/media-server/sessions/{sessionId} | Session ID | Ends a playback session (204): its FFmpeg processes stop and its player hears session.ended {reason: "admin"}. Unknown → 404 not_found. |
| GET | /api/media-server/history | userId, deviceId, itemId (integers); from (inclusive) and to (exclusive): ISO 8601 instants; skip (≥ 0), take (1–200, default 50) | Every profile's playback history, newest first (Media Server → History): {items:[{id, userId, profileName, deviceId, deviceName, platform, itemId, itemType, title, showTitle, seasonNumber, episodeNumber, versionId, startedAt, endedAt, startPositionSeconds, endPositionSeconds, watchedSeconds, elapsedSeconds, durationSeconds, completed, method, videoNode}], total, skip, take, profiles:[{id, name}], devices:[{id, name, platform, userId, revoked}]}. title is the title as it was when it played; showTitle an episode's show (a track's artist); method directPlay, directStream or transcode (music plays are directPlay); videoNode the producer that made most of a transcode's video once a cluster node took part (local = this server), else null; watchedSeconds = end − start position (never below 0; seeking makes it an estimate); elapsedSeconds = wall time, pauses included. A deleted device leaves deviceId/deviceName null; the row stays. profiles and devices (≤ 500, most recently seen first) feed the page's filters. Invalid input → 400 bad_request naming every problem. A player's own GET /api/media/v1/me/history is unchanged (policy-filtered). While control-panel sign-in is off → 400 admin_auth_required (a lasting log of every profile's viewing, kids included, is not readable by the whole network; Now playing stays readable). |
| GET | /api/media-server/encoders | — | This server's playback encoders for Media Server → Encoders: {probed, buildHash, h264Encoder, hevcEncoder, zscaleFilter, overlayFilter, benchmarking, encoders:[{encoder, signatureId, device, role, testing, offered, hdrSelfTest, selfTest:{signatureId, encoder, usable, forcedIdrReliable, initStable, codec, error, testedAt, elapsedMilliseconds, transient}}], toneMappers:[{mapper, consumer, passed, darkLuma, brightLuma, error, validatedAt, elapsedMilliseconds, transient}], speeds:[{signatureId, encoder, producer, sourceClass, rungClass, pipeline, speed, samples, updatedAt}], nodes:[{nodeId, name, state, encoders, selfTests}]}. role h264, hevc or fallback (libx264); selfTest null until the encoder was first used or tested; a tone-mapper consumer is software or hw:{encoder}, with +hlg for the HLG pattern; a cluster producer's speed names it in producer (node · encoder). Memory only: nothing is started; right after start it waits at most 3 s for the FFmpeg probe and otherwise answers probed: false. |
| GET | /api/media-server/jobs | — | Background extras (seek thumbnails, motion previews, resume frames) for Media Server → Background jobs: {running, paused, pausedSetting, pausedPinned, yieldingToPlayback, concurrency, active:[{assetId, kind, priority, libraryFileId, fileName, title, progress, units, startedAt, waiting}], queued:{kind:{priority:count}}, queuedTotal, disk:[{kind, assets, bytes, capBytes}], completed, failed, preempted, deferred, failedAssets, evicted, recentFailures:[{assetId, kind, libraryFileId, title, error, at}], lastMaintenanceAt, settings:{trickplayCacheMaxGb, previewsEnabled, previewsBackfill, previewCacheMaxGb, mediaJobConcurrency, mediaJobsPaused}, libraries:[{id, name, trickplayEnabled}]}. Kinds trickplay, preview, resumeFrame; priorities (first runs first) playing, interactive, homeCandidate, recent, backfill; waiting = the job waits at a step boundary while playback needs the encoders, the work is paused, or its file is out of reach; resume frames live in the artwork store (capBytes 0). preempted = jobs stopped for a playing title (or better work) and queued again; deferred = jobs put back because their FFmpeg made no progress for 15 minutes without using processor time (starved behind busy encoders, or blocked on its file), their file could not be read for a minute or went out of reach while it was being read, or the keyframe-index builder was busy (no failed attempt is counted; more than four in a row without progress, or more than sixteen in all, are a failure); failedAssets = failed jobs waiting now (POST …/jobs/retry-failed queues them again). Counters count since the media server started; recentFailures holds the last 20 (an error's text never carries a file path under the metadata folder). |
| POST | /api/media-server/jobs/pause | — | Pauses background extras and saves MediaJobsPaused = true: 200 with the GET /api/media-server/jobs shape. A running job stops at its next step (one thumbnail sheet, one preview encode); thumbnails for a title someone is playing are still made (only while it plays). When SNACKS_MEDIA_MediaJobsPaused pins the setting, the pause lasts until Snacks restarts (pausedPinned: true). |
| POST | /api/media-server/jobs/resume | — | Resumes background extras and saves MediaJobsPaused = false: 200 with the GET /api/media-server/jobs shape. A later change of mediaJobsPaused through PUT /api/media-server/settings decides again. |
| POST | /api/media-server/jobs/retry-failed | — | Queues every failed background job (thumbnail set, preview, resume frame) again with its attempts reset: 200 {retried, jobs} (jobs = the GET /api/media-server/jobs shape). A version that changed meanwhile is dropped when its turn comes; a retried job gets new URL keys. |
| POST | /api/media-server/encoders/retest | — | Re-test encoders (202 {forgotten}): forgets every playback encoder self-test and tone-mapper validation of this FFmpeg build and runs them, with the encode-speed micro-benchmark, again in the background. A failure that may pass on another try (the encoder was busy, a timeout) also runs again by itself after an hour and at every media server start. |
JSON answers that name no caching of their own are sent Cache-Control: private, no-store (one profile's data is never kept by a cache); /home, /items, /items/index and /items/{id} are private, no-cache with a weak ETag, errors no-store, and files (artwork, thumbnails, previews, media) carry their own headers below.
| Method | Path | Inputs | Purpose / response |
|---|---|---|---|
| GET | /api/media/v1/server | — (public) | {name, version, apiVersion: 1, mediaServer:{accountsConfigured, householdProfiles}, features:{directPlay, directStream, transcode, abr, hdr, subtitles, trickplay, music, cluster, accessEndReason, accessEndSignedOut, pinRenewal}}. Feature flags report only what this release implements: directPlay, directStream, transcode, abr (adaptive quality), hdr, subtitles, trickplay (seek thumbnails) and music are true; cluster is true only while this server is the cluster master and at least one compatible node (same Snacks version) is ready (its playback self-tests found a usable encoder), accepts playback chunks and is not unreachable or offline. cluster is read on every answer, so it follows the live cluster, not only the build; a missed liveness probe or a cool-down does not turn it off. accessEndReason: sessions ended by a change of the profile's or device's access end access, never revoked; accessEndSignedOut: an end that left the device unable to mint a token for the profile says signedOut on session.ended and the 410, never pinRequired. pinRenewal is an object, the PIN renewal rule as the server applies it now (read from the live settings on every answer): {requiresPlaying, playingWindowMinutes, advanceSeconds, renewedLifetimeMinutes, horizonHours, minimumExtensionSeconds, capToRuntime, runtimeSlackMinutes}. |
| POST | /api/media/v1/auth/login | — (public) {username, password, deviceName, platform} | Signs a device in: {refreshToken, accessToken|null, expiresAt|null, user: User, householdScoped}; accessToken is null when the profile has a PIN (unlock it with /auth/token). User = {id, username, displayName, hasPin, restricted, avatar:{color, initials}}. Tokens: snpr_… (device, 90 days, sliding) and snpa_… (12 hours). Wrong, unknown or disabled credentials → 401 unauthorized; more than 20 signed-in devices → 409 device_limit with devices:[{id, name, platform, createdAt, lastSeenAt}]; too many failures for the username or address (the address is the connecting one; X-Forwarded-For counts only from this machine or a proxy listed in SNACKS_TRUSTED_PROXIES; an IPv6 client counts as its /64 network), or more than 30 successful sign-ins of one username within about an hour → 429 too_many_attempts; password checks busy → 503 capacity (both with retryAfterSeconds). Bodies over 16 KB → 413. |
| POST | /api/media/v1/auth/token | — (public) {refreshToken, profileId?, pin?} | An access token for profileId (default: the profile that signed in on the device): {accessToken, expiresAt, user}. On a household device any enabled household profile may be chosen, otherwise only the signed-in one (403 forbidden). Revoked or expired device → 401 (checked before any PIN work); PIN profile without pin → 403 pin_required (with retryAfterSeconds while wrong PINs are locked out); wrong PIN → 403 pin_invalid (three free tries per device and profile, then retryAfterSeconds from 5 s doubling to 15 min; a locked-out count is remembered for a day). Minting signs every other profile out of this device. Renewal during playback: {refreshToken, profileId, renew: true} with Authorization: Bearer the PIN profile's current access token and no pin → 200 {accessToken, expiresAt, user} when that token is this device's and this profile's, unexpired and PIN-verified, and this device has a live playback session of the profile; the new token is PIN-verified, lives 30 minutes, and no chain of renewals ends later than 24 hours after the PIN was entered; a renewal that would not extend the token it renews by at least a minute (the chain's last minute, or long before that token's end) is refused; every condition is read again when the token is made; any other case → the same 403 pin_required. By default (PinRenewalRequiresPlaying, on) a renewal also needs a session of the profile on this device to have reported an advancing playing position within the last 10 minutes (PinRenewalPlayingWindowMinutes): a progress report with state playing more than 0.5 s past the position the session last recorded (its previous report of any state, a PATCH's or DELETE's position, or its start) — paused and buffering never count — and the latest report of this device's live sessions of the profile is not paused; so a paused profile is asked for its PIN when its token runs out, and the next playing report lets renewals succeed again (another device's playing, an ended session and one past its lease never count). The lifetimes, the horizon, the budget and the PIN lockout below are the settings AccessTokenLifetimeMinutes, PinRenewedTokenLifetimeMinutes, PinRenewalHorizonHours, TokenRequestBurst/TokenRequestRefillSeconds and PinLockout* (defaults given here). PinRenewalCapToRuntime (off) caps a renewal at the played title's end watched straight through + 30 minutes. A renewal is one request of the device's budget. Each device may request 10 tokens in a burst, then one every 6 seconds (429 too_many_attempts + retryAfterSeconds), and keeps at most 10 live tokens per profile (the oldest are retired). Bodies over 16 KB → 413. |
| POST | /api/media/v1/auth/logout | Authorization: Bearer <refreshToken> | Signs the device out (its refresh token and every access token minted on it): 204. |
| GET | /api/media/v1/profiles | Authorization: Bearer <refreshToken> | {items:[User]}: every enabled household profile on a household device, else just the signed-in profile. The only routes that accept a refresh token are this one and /auth/logout. |
| GET | /api/media/v1/me | Access token | The active profile: User. |
| GET | /api/media/v1/me/preferences | Access token | {audioLanguage, subtitleLanguage, subtitleMode, autoplayNext}; defaults null, null, "foreign", true. |
| PUT | /api/media/v1/me/preferences | Access token; any of the four members | Updates the members sent (others keep their value) and returns all four. Languages: ISO 639 codes of 2–3 letters (e.g. eng, fre) or null; subtitleMode: foreign | always | forced | never; autoplayNext: boolean. Anything else → 400 bad_request. Restrictions, PIN and library access are not editable by players. |
| GET | /api/media/v1/me/history | Access token; skip, take (≤ 200, default 60) | {items:[{item: ItemSummary, startedAt, endedAt, completed}], total}, newest first. Titles the profile may no longer see (a new rating limit, a library removed from its access) are left out, also from total. Video plays are recorded by playback sessions; track plays by /items/{id}/played. |
| GET | /api/media/v1/me/sessions | Access token | {items:[{sessionId, deviceName, item, startedAt, method}]} — the profile's live playback sessions on every device, oldest first (item = ItemSummary, method = directPlay, directStream or transcode). |
| DELETE | /api/media/v1/me/sessions/{sessionId} | Access token; session id | Ends one of the profile's playback sessions, e.g. on another device (204); that device hears session.ended {reason: "revoked"}. Another profile's or an unknown session → 404 not_found. |
| DELETE | /api/media/v1/me/continue/{itemId} | Access token; a movie, an episode (its show's card) or a show | Hides the title from Continue watching until the profile plays it again: StateChange (below), whose userState of the title (and, for an episode, of its show) carries hiddenFromContinue: true — so do every later userState of it and the userState.changed the profile's other apps get, until the title is played again. Other types → 400 bad_request. |
| GET | /api/media/v1/home | Access token; optional tz: the viewer's time zone (IANA name such as Europe/Berlin; malformed — over 64 characters, or a character outside letters, digits and _ + - / → 400 bad_request; a well-formed zone this server's time zone data does not know is ignored: the page and its ETag are those without tz) | {featured:[FeaturedItem], rows:[{id, title, kind: continue|posters|squares, items:[HomeItem], reason, layout, priority, landing, tags}]}. featured (≤ 8): available movies and shows with a backdrop and a logo — recently added, My List and never-watched titles, chosen per profile and stable for six hours; FeaturedItem = HomeItem + {previewUrl, playTarget:{itemId, label, positionSeconds, durationSeconds}} (its overview is the whole synopsis) (label "Play", "Resume", "Play S1 · E1", "Resume S1 · E3"; previewUrl is the title's motion preview, null while none is ready). Rows, in this order and only when not empty, ≤ 20 items each: continue (in-progress movies and one card per show — its next-up episode — by last play, at most 90 days old, minus hidden ones; shows that are caught up or were marked unwatched again have no card), recent-movies, recent-shows ("New episodes", by newest episode — for a profile limited to some libraries, the newest episode in those libraries), mylist, three genre:<name> rows (each with at least HomeMinGenreRowItems titles; thinner genres make way for the next), recent-music (albums by latest track play), recent-albums. Continue movies and episodes also carry trickplay when the seek thumbnails of the version Resume plays are ready — the trickplay manifest's shape plus timeOffsetSeconds (a stored positionSeconds p shows thumbnail floor((p + timeOffsetSeconds) / intervalSeconds)); a missing set is made in the background (at most 12 per page; the page never waits). Only Continue cards carry it, and only for a version in a library the profile may use. Motion previews: featured cards and every row card except Continue (repeated evidenceFrom cards included) carry previewUrl (/api/media/v1/previews/{key}.mp4) and previewPoster (its first frame, an artwork URL) when the title's preview is ready — a movie's from its default version, a show's from the first regular episode of the season of this profile's next episode (season 1 when not started or caught up), only of a version in a library the profile may use; a row card without one leaves both out (a featured card writes previewUrl: null). A missing preview is queued in page order (at most 12 per page, a title at most once per 10 minutes, only for a file on disk long enough to have one) and made in the background on this server's CPU at the lowest priority; the page never waits for one or starts one. Resume frames: a movie or episode in progress carries userState.resumeFrame (an artwork URL) once a playback session of this profile has ended there or a position was saved with PUT /items/{id}/state — on every card and in every userState of that title for that profile (see /items/{id}). The ETag moves when a preview, or the trickplay set of a title someone is watching (on Continue watching), becomes ready or goes, and when previews are turned on or off.
HomeItem = ItemSummary + what the decision-first Home shows when the title is focused, so it never needs /items/{id}: overview (≤ 300 user-perceived characters — text elements, so a cut never splits a letter from its marks or an emoji sequence — cut at a word with "…"; render it with dir="auto"), tagline, castPreview:[{personId, name}] (first three; an episode: its show's), directors, creators (≤ 2 names each), hasTrailer (/items/{id} lists trailers), ratings:[{source: "tmdb", value, scale: 10, votes}] (empty when unrated), reason, remainingSeconds (a movie or episode: its duration minus the resume position, or the whole duration; a show the profile has started — an episode watched, or a play recorded: the exact time left over its available regular episodes the profile may see, each default version (file) counted once less the furthest resume position on it, and nothing for a file one of whose episodes is watched; null for a show not started (its stage shows its seasons), for one with no such episode, otherwise or without durations), nextEpisode (shows: {id, type: "episode", title, parentIndex, index, runtimeMinutes, durationSeconds, releaseDate, positionSeconds, remainingSeconds, userState} — the show page's next episode, a compact episode rather than an ItemSummary, with the profile's own userState on it; null when caught up), playTarget (shows: what Play starts, as the hero's — the first episode again when caught up; null for movies, which play themselves), chapters (Continue movies and episodes: [{startSeconds, endSeconds, title}] of the version Resume plays — the one the profile last played when it is still there in a library it may use, else the default, else the best; null elsewhere), seasonCount (shows: regular seasons with an available episode the profile may see), status (shows) and endYear (an ended or canceled show's last air year). Its artwork (and its parent's and grandparent's) also carries backdrops, backdropTextless and logoTone as on /items/{id} (each only when known). Each title's evidence is written once per response: on its first card — featured first, then the rows in order. A later card of the same title carries evidenceFrom (the id of that first card's row; featured for the hero) and leaves out overview, tagline, castPreview, directors, creators, hasTrailer, ratings, remainingSeconds, nextEpisode, playTarget, seasonCount, status, endYear and the stage artwork (also on its refs); it keeps its own reason and chapters. Read the evidence from the first card with the same id.
HomeItem.reason = {kind, text, source: "rules"} or null, first match: continue ("34 min left", "S2 E4 · 34 min left"; in progress, or a Continue movie), nextEpisode ("Next episode · S2 E4", the player's wording; Continue at the episode's start), newEpisode ("2 new episodes"), episodesLeft ("6 episodes left"), recentlyAdded (recently-added rows and the hero, added in the last 14 days: "Added today", "Added Tuesday", "Added Oct 18", "New episode Tuesday"), inMyList ("On your list"), watched ("Watched last week", "Watched in March"). Texts that name a day are written only with tz (otherwise text is null and the kind stays); end times ("ends 10:42 PM") are always the player's. Reasons come only from the library and this profile's own viewing, never another profile's, and never name a title the profile may not see.
Row reason = {kind: continue | recentlyAdded | newEpisodes | inMyList | genre | recentlyPlayed, text, anchorItemId, source: "rules"}; text only when it adds to the heading ("3 added in the past week", "4 new episodes"), else null; anchorItemId is null (reserved for rows about one title, which may only ever name a title the profile may see). layout is rail; priority is the row's importance (higher first, the order sent); landing is true on Continue watching only (Home lands on its first title); tags is null (reserved for mood rows). Windows ("past week", "14 days") are measured from the start of the six-hour featured window. Weak ETag from the catalog, this profile's state and restrictions, the six-hour window, HomeMinGenreRowItems and, with tz, the zone and the viewer's date there; If-None-Match → 304. A fixed number of batched statements whatever the library's size. |
| GET | /api/media/v1/items | Access token; type (comma list of movie, show, season, episode, artist, album, track; default movie,show,artist,album), libraryId, genre, decade (e.g. 1990), contentRating (comma list), resolution (4K | HD | SD), hdr, watched (true | false | inProgress), inMyList, sort (title [default] | added | year | rating | lastPlayed | listAdded | episodeAdded | random), order (asc | desc), seed (required with random), skip, take (≤ 200, default 60) | {items:[ItemSummary], total, facets?}. ItemSummary = {id, type, title, sortTitle, year, parent, grandparent, index, parentIndex, artistName, contentRating, runtimeMinutes, durationSeconds, genres, communityRating, artwork:{poster, backdrop, logo, thumb, colors, sizes}, badges, addedAt, available, userState:{positionSeconds, completed, inMyList, playCount, lastPlayedAt, leafCount, watchedLeafCount, newLeafCount, resumeFrame?, hiddenFromContinue?}}; parent/grandparent = {id, type, title, index, artwork}. userState.resumeFrame (movies and episodes): the picture where this profile stopped — an artwork URL (append ?w=) of the keyframe at or before positionSeconds, the video's displayed size fitted into 3840×2160 (never larger than the video), made in the background after one of its playback sessions ended or a position was saved with PUT /items/{id}/state; present in every userState of the title for this profile (lists, details, /home, StateChanges) while the title is in progress and not removed from Continue watching, left out otherwise (watched, hidden). It is the frame of positionSeconds once that one is ready and, until then, the newest frame of an earlier stop (also while a session on another device moves the position); a frame of a file since replaced is never shown. Its URL is served Cache-Control: private, no-store (see /artwork/{key}). When it appears or changes the profile gets userState.changed and its ETags move. userState.hiddenFromContinue (movies, episodes, shows): true while the profile has removed the title from Continue watching (DELETE /me/continue/{id}) and not played it since; left out otherwise. userState.durationSeconds (movies and episodes in progress): the duration of the version the position was saved in (the version played last — the one the 90 % rule and the clamp use), so a card's progress and time left follow it rather than the default version's durationSeconds; left out when not in progress or that version is unknown. Titles none of whose files is in any library any more (their library was deleted; an offline share keeps them, greyed) are left out of these lists, /items/index, the facets and /search, but stay in the profile's own Continue watching, My List (inMyList=true) and history. artwork.sizes = {poster, backdrop, logo, thumb}, each the original's {width, height} (null when the image is missing or its size unknown). facets (first page only) = {genres:[{name, count}], decades:[{decade, count}], contentRatings:[{rating, count}], resolutions:[{name, count}], hdr}, each counted with every other filter applied. For shows and seasons watched=false means some visible episode is unwatched. Missing values sort last; ties by id; random is the same order for the same seed on every page. My List = ?inMyList=true&type=movie,show&sort=listAdded&order=desc. A library the profile may not use → 404 not_found; invalid values → 400 bad_request. Weak ETag. |
| GET | /api/media/v1/items/index | Access token; the filters of /items, sort=title (any other sort → 400), optional order | {letters:[{letter: "#"|"A".."Z", offset, count}]} — all 27 letters for the alphabet rail: where each letter starts in the title order and how many titles it holds (titles not starting with a–z go under #, first). Weak ETag. |
| GET | /api/media/v1/items/{id} | Access token; item id | ItemSummary plus, by type — movie: overview, tagline, releaseDate, studio, versions, cast:[{personId, name, character, profile}], crew:[{personId, name, job}], trailers:[{name, site, key}], related (≤ 12), chapters:[{startSeconds, endSeconds, title}]; show: overview, tagline, status, seasons, nextEpisode, cast, crew, trailers, related; season: overview, show, episodes (each + overview, releaseDate); episode: overview, releaseDate, show, season, versions, previousEpisode, nextEpisode, cast, chapters; artist: overview, credits, albums, appearsOn, topTracks; album: overview, credits, artist, tracks, totalDurationSeconds (credits = {overview|poster|backdrop|logo: {source, url, license, author}} for text and pictures fetched online: show the credit next to the biography or photo, as their licences ask; artists and albums also carry their genres); track: album, artist, versions. Version = {id, label, edition, container, durationSeconds, sizeBytes, bitrate, video:{codec, profile, width, height, bitDepth, frameRate, hdr}, audio:[{index, codec, channels, language, title, default}], subtitles:[{id, source, codec, language, title, forced, default, imageBased}], episodes, playable, unplayableReason} (default version first; episodes lists the episodes of a multi-episode file). A show's nextEpisode is what to play next (the first episode when nothing was watched, null when caught up). The requested item's own artwork also carries the stage members backdrops:[{url, width, height}] (≤ 4 backdrops without a burned-in title, best first; possibly empty), backdropTextless (the first of them) and logoTone (light | dark, the logo's ink); the last two only when known. A movie or episode in progress carries userState.resumeFrame when this profile's frame of that position is ready (see /items); the ETag moves when it appears or goes (the profile's state revision). Titles the profile may not see answer exactly like missing ones: 404 not_found, with mergedInto when the id was merged into a title the profile may see. Weak ETag. |
| GET | /api/media/v1/items/{id}/children | Access token; skip, take (≤ 200, default 60) | {items:[ItemSummary], total}: a show's seasons, a season's episodes, an artist's albums or an album's tracks, in order (empty for movies, episodes and tracks). |
| GET | /api/media/v1/items/{id}/related | Access token; item id | {items:[ItemSummary]}: up to 12 available titles of the same type sharing keywords and genres (movies: also the same collection); empty for other types. |
| PUT | /api/media/v1/items/{id}/state | Access token; {positionSeconds?, completed?, inMyList?} (at least one) | Saves a resume position or watched mark (movies and episodes only, else 400) or My List (any type): StateChange = {changed:[{id, userState}], truncated, nextEpisode} — the item, its season/show (album/artist), up to 200 entries (truncated when more changed), and the show's next episode. A position at ≥ 90 % of the duration — of the version the profile last played, when known — marks the title watched (and is never kept past that version's end); a play clears "hidden from Continue watching". Also sent to the profile's other apps as userState.changed. A resume position saved here (outside a playback session) gets its userState.resumeFrame a moment later, like the end of a session does (at most 20 such frames per profile per 10 minutes; announced by userState.changed). |
| POST | /api/media/v1/items/{id}/watched | Access token; a movie, show, season or episode | Marks it — and every episode of it the profile may see — watched: StateChange. Music → 400 bad_request (plays are counted by /played). |
| DELETE | /api/media/v1/items/{id}/watched | Access token; a movie, show, season or episode | Marks it and its visible episodes unwatched (position and play count reset): StateChange. |
| POST | /api/media/v1/items/{id}/played | Access token; {secondsPlayed} | Reports listening to a track: at ≥ 50 % of the track or ≥ 240 s it counts a play (play count, last played for the track, album and artist, and a history entry) and answers the StateChange; a shorter listen changes nothing ({changed: [], truncated: false, nextEpisode: null}). Other types → 400 bad_request. |
| GET | /api/media/v1/items/{id}/stream | Access token; track id; codecs (comma list the client plays, e.g. aac,mp3,opus,flac); optional Range | The track's audio file (its default version, else its best available one — only versions in libraries the profile may use) with single-range support (206 + Content-Range; an unsatisfiable range → 416). Not a playback session and not counted against stream limits. The file always comes from the track's own library entry, never from the request. When codecs lists the track's probed codec (or is omitted) the original is served byte for byte, and the file is leased while the response reads it (a transcode replacing it waits, see PlaybackLeaseWaitSeconds); otherwise a whole-file transcode made once and cached by file version in the transcode cache — FLAC for lossless sources (ALAC, AIFF/WAV PCM, APE, WavPack, DSD …) when codecs has flac, else AAC in MP4 with +faststart — with the same Range support (audio/flac or audio/mp4). Concurrent first requests share one conversion; a conversion that fails answers 503 capacity. The decision uses the probed codec, never the file extension. Not a track → 400 bad_request; file missing or offline → 409 media_unavailable. |
| HEAD | /api/media/v1/items/{id}/stream | Access token; track id | The headers of the same response (Content-Type, Content-Length, Accept-Ranges) without the audio. |
| GET | /api/media/v1/people/{id} | Access token; person id | {person:{id, name, profile}, items:[ItemSummary]}: the person's movies and shows the profile may see, newest first. Unknown, or none visible → 404 not_found. |
| GET | /api/media/v1/search | Access token; q (≤ 200), types (comma list; default movie,show,episode,artist,album,track), take (per group, ≤ 50, default 8) | {query, groups:[{type, items:[ItemSummary]}]} — one group per requested type, in that order, empty groups included. Every word is matched as a prefix of a title, original title, artist or (episodes) show title, accents ignored; exact and leading title matches first. |
| GET | /api/media/v1/libraries | Access token | {items:[{id, name, kind: video|music, itemCounts:{movie, show, album, artist}, scan:{state: idle|scanning|probing|matching, itemsFound, itemsMatched, startedAt}}]} — only the libraries the profile may use; counts include only titles it may see. |
| GET | /api/media/v1/artwork/{key}?w= | Access token; key: the 64 lower-case hex token of an artwork or profile URL; w: 32, 92, 185, 342, 500, 780, 1280, 1920, 2560 or 3840 (omitted = the largest) | The image at w, or at the original's own width when the original is narrower (never enlarged, and never cut down to a smaller listed width: a 499 px logo asked for at 500 is sent at 499); omitted w = 3840 or the original's width. WebP, or PNG for transparency. Each image has at most one size outside the list (its own width); its ETag names the width served. Cache-Control: private, max-age=31536000, immutable (private: no shared cache in front of the server keeps one) and an ETag (If-None-Match → 304); a resume frame's URL (userState.resumeFrame, one profile's picture) is answered Cache-Control: private, no-store, so a shared device's cache never keeps it after a profile switch or a sign-out. The token is the image's content key encrypted with this server's secret (config/mediaserver.artwork.key; resume frames use a second key derived from it, same shape), so it only comes from responses the profile may see and cannot be computed from a public image; a content key itself is not accepted. The route reads files only. Unknown token → 404 not_found; any other w → 400 bad_request. The widths Home asks for (342, 500, 780, 1920) are made in the background when an image arrives (one at a time, resting twice each resize's time: at most about a third of a core; waiting while a playback starts or decodes a lead, at least one per 30 s; off with ArtworkPrerenderEnabled); a width not made yet is answered at once with the nearest larger width already made (at most twice the width asked for; its own ETag, Cache-Control: private, max-age=60) while the exact one is made. |
| GET HEAD | /api/media/v1/trickplay/{key}.jpg | Access token; key: 64 lower-case hex from a trickplay manifest or a Continue card's trickplay.sheets | One thumbnail sheet (JPEG, under 8 MB). Cache-Control: private, max-age=31536000, immutable and ETag "{key}"; one byte range at most (one that cannot be satisfied → 416; several → the whole sheet). The key derives from a random key the server made for that set of thumbnails (never from an id, a file or a content hash), so it only comes from responses the profile may see; the route reads files only. Unknown, malformed or upper-case key → 404 not_found. Least recently used sets beyond TrickplayCacheMaxGb (default 20) are removed (never a set a live session uses; above 110 % also recently used ones); they are made again on the next play. |
| GET HEAD | /api/media/v1/previews/{key}.mp4 | Access token; key: the 43 base64url characters of a /home card's previewUrl | A title's muted motion preview: H.264 High, 8-bit 4:2:0, BT.709 SDR (HDR is tone-mapped), no audio track, about 20 s, the picture's displayed size fitted into 1920×1080 (never larger than the video; ≤ 30 fps), moov first, at most 11.5 MiB. Chosen from the middle of the title: after the intro chapter and the first 8 %, ending before the credits chapter and two thirds of the runtime, a window without black, frozen or flashing pictures (none → no preview; titles under about 40 seconds have none). video/mp4, Cache-Control: private, max-age=31536000, immutable and ETag "{key}"; one byte range at most (one that cannot be satisfied → 416; several → the whole file). The key is the base64url form of a random key the server made for that preview (never from an id, a file or a content hash), accepted only in its one canonical form, so it only comes from responses the profile may see; the route reads files only. Unknown or malformed key → 404 not_found. Settings: PreviewsEnabled (default on; off = no previews listed or made), PreviewsBackfill (default on: idle time also covers the rest of the library, newest first, until 80 % of the size limit), PreviewCacheMaxGb (default 10; the least recently shown are removed beyond it and made again when Home shows the title). |
| GET | /api/media/v1/events | Access token; Accept: text/event-stream | A server-sent event stream (text/event-stream, Cache-Control: no-store) for the profile, opened with a :ok comment and kept alive by a :ping comment every 25 seconds. Events (event: name, one JSON data: line, no ids — revalidate after reconnecting): library.changed {libraryId, revision} (+ removed: true when the library was deleted) and items.changed {ids:[≤ 200]} or {all: true}, only for libraries and titles the profile may see; userState.changed = the profile's own StateChange — each changed[] entry of a write made by a playback session's progress report or DELETE carries writer: {sessionId} (absent for every other write); session.ended {sessionId, reason} when a playback session of the profile ends without the player asking — expired (no progress for 60 s), access (the profile's or device's access changed: its PIN set, changed or removed, its rating or library limits or household flag changed, the profile disabled, the device switched to another profile — recreate it at its position: the new start checks access again; tokenRevoked: true says the change also revoked this device's access token for the profile, so get a new one first — the PIN pad for a PIN profile, POST /auth/token with the refresh token for any other — then recreate; false: the token still works, recreate at once; beside tokenRevoked: true, when the change was to the profile itself, pinRequired says whether signing back in needs the PIN — true: the PIN pad at once, false: a silent POST /auth/token; absent: what the player knows stands; and when no token for the profile can be minted on the device any more, signedOut says so instead of pinRequired — device: the device was signed out, go straight to sign-in; profile: the device is signed in but may no longer use the profile (disabled, deleted or out of the household while on another account's household device), go to the profile picker), revoked (the profile stopped it from another device — tokenRevoked: false — or its device was signed out — its own sign-out, an administrator's, a password change, "Sign out everywhere": tokenRevoked: true); both always written ahead of the auth.revoked that closes the stream, source_changed (an encode replaced or Library Health deleted the file) or admin; auth.revoked {reason} when the access token is revoked — device (signed out, revoked, profile deleted, disabled or its password reset: sign in again) or profile (restrictions, PIN or household flag changed, or another profile activated on the device: get a new access token) — and server.disabled {} when the media server is turned off; the stream ends after either. A stream ends without an event about 30 seconds before its access token expires, when that token was replaced by a newer one of the same profile, and (for a client outside the local network) when remote players stop being allowed — reconnect with the current token. Changes to titles that are offline everywhere reach profiles that may use every library as items.changed (no library.changed). At most 8 streams per profile (opening another closes the oldest). A client that stops reading gets its pending events collapsed into one items.changed {all: true}; one that blocks a write for 30 seconds is disconnected. Streams close without an event when Snacks shuts down. |
| POST | /api/media/v1/playback/sessions | Access token; JSON {itemId, versionId?, startPositionSeconds?, audioIndex?, subtitleId?, quality?, maxBitrate?, profile} | Starts a video playback session for a movie or episode and answers the session: {sessionId, itemId, versionId, method, playbackUrl, mimeType, durationSeconds, startPositionSeconds, variants, audioTracks, subtitleTracks, chapters, markers, trickplayUrl, next, heartbeatSeconds, expiresAt, leaseSeconds, serverTime, transcode} — leaseSeconds the session's configured lease (every progress report renews it: expiresAt = its serverTime + the lease), serverTime the server's clock when it answered; each subtitleTracks[] entry names its codec as the version's subtitles[].codec does. The device profile (Direct Play containers/codecs, MSE codecs with H.264 level and HEVC bit depth, HDR formats, maximum size and audio channels, audio track switching) decides directPlay (the original file over Range at …/file), directStream (video copied into fMP4 HLS as the orig variant plus every transcoded rung lower than it in class, or of its class but cheaper than the copied video, audio as AAC renditions) or transcode (the rungs alone). Rungs: 1080p 8 Mb/s, 720p 4 Mb/s and 480p 1.5 Mb/s, each the source's shape fitted into its 16:9 box and never upscaled (bitrate scaled by pixels), at or below the device maximum and a quality cap. One rule classes every picture: its class is the smallest standard 16:9 box (854×480, 1280×720, 1920×1080, 3840×2160) that holds its displayed size (a picture of up to 1080 lines wider than 1920 — 1998×1080, 2560×1080 — is still 1080); a numeric quality keeps the Original only when its class is at most that quality (a 2.76:1 1920×696 file at 720 is transcoded to 1280×464, a 1998×1080 one at 1080 is kept), rungs are fitted into its box, and every variants[].label names the class (Original · 1080p, 720p, 4K); H.264, or HEVC for the 1080 class when the device plays HEVC and the server has a hardware HEVC encoder; under maxBitrate every rung is capped and rungs that are then no cheaper are dropped. The cap is compared with what each method sends: Direct Play the whole file's bitrate, Direct Stream the copied video's measured average plus the selected audio rendition (a copy that only the file's rate put above the cap — interleaved audio tracks — is measured and kept). A Direct Stream rung targets at most the copied video's average, so no encode sends more than the free copy. Every rung is listed in the master (hls.js adapts; picking one is a client-side level lock). HDR: a PQ source (HDR10, HDR10+, Dolby Vision 7/8.1) plays as PQ on a device whose profile.hdr lists hdr10, an HLG source (HLG, Dolby Vision 8.4) as HLG where it lists hlg (one VIDEO-RANGE per session; Dolby Vision is copied as HEVC with its RPUs stripped, never Direct Played); otherwise every rung is tone-mapped to SDR BT.709 with the best tone mapper this server validated on its own FFmpeg (VideoToolbox scale_vt on macOS, then libplacebo, OpenCL, tonemapx, Quick Sync, software zscale) — none → 422 hdr_tonemap_unavailable; Dolby Vision profile 5 plays only through a Dolby-Vision-aware libplacebo. An image subtitle (PGS, VobSub or DVB, embedded or a .sup / .idx+.sub sidecar) in subtitleId — or chosen by the preferences, e.g. a forced PGS or VobSub track — is burned in: the session is transcode with the track in every rung (transcode.reason “image subtitles are burned in”); the track is extracted once per file version, and a PGS track's segments needed before that finishes read only the few seconds of the file around them (a large file's first segment does not wait for a whole-file read; a VobSub or DVB track's first segments wait for its extraction). When the video cannot be copied, transcode.reason says why, e.g. “keyframes are up to 30 s apart”, “the file runs 27 s past its last keyframe” (copied segments hold at most 20 s or 96 MB; when the audio runs on past the video's end, the transcoded video holds its last frame to the end of the timeline), “the keyframe index is not ready yet” (its first play) or “the file's keyframes could not be read to its end” (read again after an hour). When the server's capacity (TranscodeThroughputPercent, PlaybackEgressLimitMbps, the cache) cannot take the top rungs they are left out and transcode.limitedBy says why (encode, bandwidth, cache). versionId null = the version last played, else the first the device can Direct Play, else the best within its size; startPositionSeconds null = resume (0 when watched, or when another edition or a duration more than 3 % off was played last); audioIndex/subtitleId null = from the profile's preferences (subtitleId: "off" = none; an image track in another format, such as XSUB → 422 subtitle_burnin_unavailable). Positions, chapters, markers and subtitle cues are playback time (source timestamps for MP4/MOV/Matroska/WebM starting within 10 s — a file whose container starts at 1.4 s has a 1.4 s lead, whose first frame segment 0 shows from 0; for MPEG-TS, AVI … and files starting later, time starts at the file). Stored resume positions count from the container start. Errors: 404 not_found (no such visible title or version), 409 media_unavailable, 422 dolby_vision_p5_unsupported / hdr_tonemap_unavailable / transcode_unavailable / no_video / subtitle_burnin_unavailable / duration_unsupported (HLS needed and the file claims a timeline longer than any playback plan, about 4.6 days: a duration neither its streams nor its keyframes confirm), 429 stream_limit with activeSessions:[{sessionId, deviceName, item, startedAt, method}] (more than MaxSessionsPerAccount sessions), 429 too_many_attempts + Retry-After (more than 20 creates in a burst, then one per second), 401 unauthorized (the profile's sign-in changed meanwhile), 503 capacity + Retry-After (every playback encoder busy or the server's playback capacity used up, too many titles being indexed, or the file changed on disk and is being re-read — then Retry-After: 2); where the cause is known the body adds reason: busy (the encoders, the upload or cache budget, or the remux and audio processes this server keeps — PlaybackLocalMaxResidentRuns — are taken: try again) or no_encoder (a transcode is needed and no playback encoder is online: local encoding off and no node ready). An ASS/SSA text track also has subtitleTracks[].assUrl (its original script, for a player that renders ASS itself; url, the WebVTT, stays the default) and, once the server has extracted it, styled (it uses more than bold, italic and underline); the session then has subtitleFontsUrl (the version's font attachments). The session also carries firstFrameSeconds (where the file's first picture is on its timeline: its container start, usually 0) and each variants[] entry its quality class (original, or the rung's class 1080, 720 or 480). variants[].bitrate is the video's: a rung's target, a copied Original's measured average over its plan (as its AVERAGE-BANDWIDTH less the audio), the file's bitrate only for Direct Play. Admission reserves the same for upload (a copy: its average plus the audio). A Direct Stream session of a Matroska file played for the first time waits up to about 1 s for the file's one-time video packet scan, so the copy's bitrate counts its video only (not the interleaved audio tracks) — only when the read rate this server measured for such scans can finish it in time (a large file on a NAS starts at once); a longer scan finishes in the background, below normal priority, for the file's next sessions. The same scan measures a copied AAC track a Matroska file gives no bitrate for, and its rendition declares that rate (not the 160 kb/s nominal). An image subtitle that cannot be burned in (empty, malformed, or an oversized or overly dense PGS track) → 422 subtitle_burnin_unavailable when it was asked for; a default choice is dropped instead. The same holds when no encoder the cluster has can burn the track's format (with local encoding off); while the node that can is only cooling down after a failed chunk, self-testing or suspect, the answer is 503 capacity reason: "busy" + Retry-After instead (try again; a default track is kept). Every answer carries Server-Timing: create;dur=<ms>, the server's own time for it in milliseconds — its errors too: a body that is not JSON, a missing or expired token (401), the media server off. The session's start is logged once (Information): the milliseconds from the create to its decision, its answer, the first master, the video's first init and its first media byte (with that segment's producer) — never the audio rendition's — and the 503 capacity answers to its master, video and audio before it, by kind (no 422 or 410) — session id and path kind only. |
| PATCH | /api/media/v1/playback/sessions/{sessionId} | Access token; JSON {audioIndex?, subtitleId?, quality?, maxBitrate?, versionId?, positionSeconds} | Changes what a session plays when the player cannot do it itself — an audio track not in the playlist (a Direct Play session switching to a track the device cannot decode), a bitrate cap, original, another version — and answers the full session (with leaseSeconds and serverTime; same sessionId; reload at positionSeconds when playbackUrl, method or the renditions changed; the previous renditions keep answering a few seconds). A text subtitleId only changes the selection; an image (PGS, VobSub or DVB) one turns burn-in on — every rung is transcoded with it, and the rung the client was playing is prepared first — and "off" or a text track turns it off again (decided anew, e.g. back to Direct Play); an image track in another format (XSUB) → 422 subtitle_burnin_unavailable, the session unchanged. More than 30 PATCHes in a burst (then two per second) → 429 too_many_attempts + Retry-After. |
| POST | /api/media/v1/playback/sessions/{sessionId}/progress | Access token; JSON {positionSeconds, state: "playing"|"paused"|"buffering", variantId?, bufferedSeconds?} | Heartbeat (every heartbeatSeconds = 10 and at once on pause/seek): renews the session's 60-second lease (only progress renews it), moves the server's playhead (what it prepares ahead) and saves the profile's resume point with the version actually played; ≥ 90 % of that version's duration (or past the credits marker) completes the title once per session → {expiresAt, serverTime, stored, lastPlayedAt?}: serverTime the server's clock (expiresAt − the lease), stored whether this report wrote the profile's state, and, when it did, lastPlayedAt exactly as that write's userState.changed carries it. stored: false for a report within 2 s of the last saved one in the same state, one below the 10 s resume threshold that is no completion, and a save that failed without ending the session (still 200: the lease was renewed; counted as progressSaveFailures). A report within a second of where the session last saved (or started) saves nothing (stored: false) and sends no userState.changed: a player left paused keeps its session without putting back a position, or un-watching a title, another device stored since. An expired or ended session → 410 session_expired, also for a report in flight when the session ended (even when its position was saved first). A report already sent when its session ended whose body came only after the end (within 5 s) is saved first too, like a late final position — never over a later play of the title or a position the session wrote after the report was sent — and answered the same 410. Whether it is saved depends on the session's own profile: it is refused when the end moved that profile's version or removed it (signed out everywhere, a password change, a PIN set, changed or removed, new rating limits or library access, the household flag, a disabled profile, a removed profile); another profile's session on a device such a change signed out or reset keeps its own profile's version, so its report is saved, as after a device's sign-out, a profile switch on the device, an administrator's end, a stream stopped from another device (DELETE /me/sessions/{id}) or a lapsed lease. A report whose body stops arriving (slower than the server's minimum request-body rate once its 5 s grace is over) → 408 bad_request, never a 500. |
| DELETE | /api/media/v1/playback/sessions/{sessionId} | Access token; optional ?positionSeconds= | Ends the session after saving positionSeconds (204); its FFmpeg processes are stopped, its file lease is released and a history entry is written. Repeating it for an ended session is harmless (204): a late position is saved when nothing else played the title since that session's last save (another device's progress or a watched mark wins) and it is more than a second from that save, and late positions ask for one new resume frame, made a few seconds after the last of them at the position stored then (once per ended session). |
| GET | /api/media/v1/playback/sessions/{sessionId}/master.m3u8 | Access token (the session's profile) | The HLS master playlist (application/vnd.apple.mpegurl): one EXT-X-STREAM-INF per variant (orig = the copied original, or the transcoded rung named by its height) with BANDWIDTH (copy: the copied video's peak segment rate + the largest audio rendition — a copied AAC track at its measured rate — from the keyframe index's video bytes, for Matroska its one-time video packet scan; a transcoded rung: its encoder's rate bound over the shortest counted window, ≈ 1.35–1.6 × its target — a Direct Stream ladder's rungs are planned under the copy's peak, so the copy is the top level), AVERAGE-BANDWIDTH, CODECS, RESOLUTION, FRAME-RATE and VIDEO-RANGE, and one AAC rendition per audio track in the aud group. Every variant of a session has one VIDEO-RANGE: an HDR passthrough session's rungs, when it has them, are HEVC Main10 (hvc1.2.4.L…) in the Original's own PQ or HLG — only where this server's or a node's HEVC encoder passed the HDR self-test and the profile's MSE plays 10-bit HEVC; otherwise such a session lists the Original only. URIs are relative. Hot path: authorized in memory (no database query); another profile's or an unknown session → 404 not_found, an ended one → 410 session_expired with reason (deleted, expired, revoked, source_changed, admin, access, disabled or shutdown; for access and revoked also tokenRevoked, as on session.ended but answered for the token the request carries: true only while that token no longer works, false for a token that works — one minted when the player signed in again — and beside true the end's pinRequired or signedOut). A Direct Stream master waits for its Original's init (needed now: within 6 s); while it is not there the master answers 503 capacity with that init's reason (preparing with readyInSeconds / X-Snacks-Ready-In, busy, no_encoder). |
| GET | /api/media/v1/playback/sessions/{sessionId}/video/{variantId}/{planHash}/index.m3u8 | Access token; variant and key from the master | A video variant's VOD media playlist: EXT-X-VERSION:7, one EXT-X-MAP:URI="init.mp4" — or, for a rung whose segments may come from encoders with different inits (an encoder whose self-test found its init unstable), EXT-X-MAP:URI="init/{n}.mp4" before every segment — every segment listed up front as {n}.m4s with its planned duration, EXT-X-ENDLIST. {planHash} is an opaque key that changes whenever the bytes behind the URL would. |
| GET | /api/media/v1/playback/sessions/{sessionId}/video/{variantId}/{planHash}/init.mp4 | Access token | The variant's fMP4 init segment (video/mp4); waits like a segment, and answers like the first segment it is written with (from the soonest of the quality's producers, with no encode in its estimate; it simply waits while one of them is past its decode): while that segment is being prepared (a start far into a film whose keyframes are minutes apart, or while the server reads an MPEG-TS recording's keyframes) it answers 503 capacity with reason: "preparing" after about 5 s, with the same Retry-After, X-Snacks-Ready-In and readyInSeconds rules as the segment (players such as hls.js ask for a quality's init beside its first fragment: handle both alike). |
| GET | /api/media/v1/playback/sessions/{sessionId}/video/{variantId}/{planHash}/init/{n}.mp4 | Access token; segment index | The init of whichever encoder produced segment n (contract v2.1): waits for segment n, then answers its producer's init, recorded per segment by content; for a rung with one producer that is the variant's init.mp4. Playlists reference it only for rungs that may mix encoders. Like the segment, it names segment n's producer in X-Snacks-Producer when known. Until segment n is there it is answered exactly as the segment is: the same 503 capacity with the same reason (busy, no_encoder, or preparing after about 5 s while the segment's producer decodes from a keyframe minutes before it), the same Retry-After, and the same X-Snacks-Ready-In / readyInSeconds estimate; once the segment is there it is served at once. |
| GET | /api/media/v1/playback/sessions/{sessionId}/video/{variantId}/{planHash}/{n}.m4s | Access token; segment index | One media segment (video/iso.segment), produced on demand: a segment the session needs now (it starts within 10 s of the session's playhead) is answered within 6 seconds — the segment as soon as it is there, else 503 capacity naming why — and one further ahead waits up to about 20 seconds; then it answers 503 capacity with Retry-After and reason: "busy" (also, without a reason, for a segment whose production keeps failing — the session is never ended by it). A quality that no online encoder can make (every cluster node that could is offline, cooling down or excluded, none is still testing one, and this server does not encode it) is answered within about a second with 503 capacity, reason: "no_encoder" and Retry-After: 2: step down to another quality. The response names who produced the segment in X-Snacks-Producer: local (this server) or a cluster node's opaque label (node- + 8 hex characters, as in transcode.nodes); absent for a segment found in the cache after a restart. Never 404/410 while the session lives (a segment number outside the playlist → 404). In a file whose keyframes are minutes apart (one keyframe for the whole film) the video is made by one run from where playback starts, decoding the file from the keyframe before it: a start or seek far into it answers 503 capacity with reason: "preparing" and Retry-After (after about 5 s; 2 to 10 s, the estimate rounded up less 2 s — the retry is held and answered the moment the segment is there — 1 s without one, so a segment that comes a moment later is not kept back) until that decode reaches it (about 30 s at 1600 s into a 1080p film on Apple Silicon, longer for 4K HEVC), then plays on normally; once the server has measured the decode, X-Snacks-Ready-In (and readyInSeconds in the body) gives its estimate in whole seconds — from the decode speed of the last 10 s, counting down between the decoder's progress reports, and left out while the decode has not advanced for a few of them (at least 2 s). A request whose estimate falls within its hold waits for the segment instead. preparing lasts only while that decode runs: a producer still queued for a slot answers busy, and one that failed or was stopped answers what replaces it. Any producer that runs and makes the segment — a piece here or on a node, a run past its decode, a copy or audio run — answers preparing at the bound, never busy, with an estimate from what that producer's recent first segments took (each node and encoder on its own), counted down and left out once overdue. Whether a request is needed now follows a seek or a stall: after a buffering report the server counts the player as playing on from it (its next report may come only with the heartbeat). Keep the quality and ask again: a lower quality decodes the same file from the same keyframe (a quality the player keeps asking for — it asks again within the Retry-After it was given, also for two or three qualities at once — is never treated as left; one the player asked for and left during that decode keeps decoding for two minutes while playback stays near it, so coming back to it is not a new wait — unless a viewer waits on this server meanwhile for another decode of minutes, such as the quality it stepped down to: that one then has the CPU to itself, and coming back decodes again; another viewer's ordinary start does not stop it. The quality being played is kept while the player tries a higher one). Keyframes 60 to 120 s apart: such a run covers the rest of one keyframe interval, then 30 s pieces go on. A file played before the server has read its keyframes (an MPEG-TS recording's first play) whose keyframes are too far apart to find answers reason: "preparing" while the server reads them, then plays the same way. A burned-in rung whose image track turns out unusable answers 422 subtitle_burnin_unavailable for good (no Retry-After): turn the subtitle off or choose another one. |
| GET | /api/media/v1/playback/sessions/{sessionId}/audio/{index}/{planHash}/index.m3u8 | Access token; audio stream index and key from the master | An audio rendition's media playlist (same plan as the video). |
| GET | /api/media/v1/playback/sessions/{sessionId}/audio/{index}/{planHash}/init.mp4 | Access token | An audio rendition's init segment (audio/mp4). |
| GET | /api/media/v1/playback/sessions/{sessionId}/audio/{index}/{planHash}/{n}.m4s | Access token; segment index | An audio segment (AAC-LC: copied when the source is AAC-LC, else encoded to 2.0, or 5.1 for devices with 6 channels); same waiting rules as video. |
| GET HEAD | /api/media/v1/playback/sessions/{sessionId}/file | Access token; optional Range | The original file of a Direct Play session with single-range support (206), Content-Type from the container (video/mp4, video/x-matroska …). The file is leased while the session lives. |
| GET | /api/media/v1/playback/sessions/{sessionId}/subtitles/{subtitleId}.vtt | Access token; subtitle id from subtitleTracks[].url | A text subtitle track (SRT, ASS/SSA, mov_text, WebVTT; embedded or a sidecar next to the file) as WebVTT (text/vtt; charset=utf-8), converted once per file version and kept in the metadata folder; cue times are playback time; ASS positioning and colours are dropped. A track that cannot be converted (ffmpeg refuses it; a sidecar that is a link, missing or too large) → 404 not_found, remembered per file version for 10 minutes; a busy or interrupted conversion → 503 capacity with Retry-After. |
| GET | /api/media/v1/playback/sessions/{sessionId}/subtitles/{subtitleId}.ass | Access token; an ASS/SSA track's subtitleTracks[].assUrl | The track's original ASS script (text/x-ssa; charset=utf-8) for a player that renders styled subtitles itself (libass): every style, position, colour, sign and drawing kept, which the WebVTT drops. Extracted once per file version (an embedded track by stream copy; a sidecar from a private copy, never through a link), at most 32 MB, on the same clock as the track's WebVTT (an event the shift moves before 0 starts at 0). X-Snacks-Subtitle-Styled: true|false says whether it uses anything beyond bold, italic and underline; subtitleTracks[].styled says the same once the server has extracted it. Cache-Control: no-store. A track that cannot be extracted → 404 not_found; busy → 503 capacity with Retry-After. Authorized in memory like the WebVTT. |
| GET | /api/media/v1/playback/sessions/{sessionId}/fonts | Access token; the session's subtitleFontsUrl | The fonts the session's version carries as attachments, for its ASS scripts: {fonts: [{name, contentType, size, url}]} in the file's order. Only TrueType, OpenType, font collections and WOFF (by MIME type or extension), at most 64, each at most 32 MB and 128 MB together; empty when there are none. name is the attachment's file name reduced to letters, digits, dots, dashes and underscores (display only). subtitleFontsUrl is present only when a subtitle track has an assUrl. |
| GET | /api/media/v1/playback/sessions/{sessionId}/fonts/{ordinal} | Access token; a fonts[].url | One font of that list by its position (never by a name), its bytes as the file holds them (font/ttf, font/otf, font/collection, font/woff or font/woff2), read once per file version and checked to start with a font signature; Cache-Control: private, no-store. A position outside the list, or an attachment that is not a font → 404 not_found. |
| GET | /api/media/v1/playback/sessions/{sessionId}/trickplay.json | Access token (the session's trickplayUrl) | The session's seek thumbnails: {intervalSeconds, tileWidth, tileHeight, columns, rows, sheets:["/api/media/v1/trickplay/{key}.jpg"]}; thumbnail n shows this session's playback time n·intervalSeconds (10 s; 5 s for titles under 20 minutes) and sheet i holds thumbnails [i·columns·rows, (i+1)·columns·rows), row by row (unused cells of the last sheet are black). The geometry is the server's: 640 px on the long side with the picture's display aspect (16:9 → 640×360), 5 columns, about 1800 px of rows per sheet (16:9 → 5×5). Made from keyframes only, on this server's CPU at the lowest priority, the first time a version is played or its detail page is opened (HDR is tone-mapped to SDR; none without a validated CPU tone mapper). trickplayUrl is non-null whenever the version can have them, and is always the session's manifest route with no query: the manifest describes the session's current playback, so re-read it whenever versionId, method or playbackUrl changes (after a PATCH as after a create). While they are being made the route waits up to 10 s, then answers 503 capacity with Retry-After; a version that cannot have them → 404 not_found. Cache-Control: no-store. Authorized in memory like the other session routes (404 for someone else's session, 410 after it ended). |
Unknown /api/media/v1 paths answer 404 not_found. Every route except
/server, /auth/login, /auth/token, /profiles and
/auth/logout needs an access token (Authorization: Bearer snpa_…); a missing, expired or
revoked one answers 401 unauthorized with WWW-Authenticate: Bearer. Every browse, state, stream
and history response is limited to what the profile may see: a title outside its rating limits or libraries answers
exactly like a missing one (404 not_found, never 403), and a profile limited to some
libraries only ever gets the versions (files) kept in those libraries. Weak ETags on
/home, /items, /items/index and /items/{id} change when the catalog
(offline titles included), the profile's own watch state or its restrictions change; If-None-Match: *
is ignored. /events tells an open player when to revalidate. The episodes of a multi-episode file are
marked watched or unwatched together.
Playback routes are documented here as they ship.
The backend targets .NET 10 and serves Razor views, JSON controllers, static ES modules, and SignalR. Electron 43 wraps the published backend for desktop releases.
# Build and run the unit/integration test suite
dotnet build Snacks.sln --configuration Release
dotnet test Snacks.sln --configuration Release --no-build --verbosity minimal
# Run the web backend
dotnet run --project Snacks/Snacks.csproj
# Validate Electron, browser modules, API docs, and version synchronization
npm --prefix electron-app ci
npm --prefix electron-app run check
# Validate a generated OpenAPI document from a running backend
node scripts/validate-openapi.mjs http://localhost:6767/openapi/v1.json
# After changing the Version element in Snacks/Snacks.csproj
node scripts/sync-version.mjs
# Run documented multi-process scenarios (see e2e/README.md)
./e2e/scenarios/01-sweep-memory.sh
docs/BUILDING.md, which is the maintained
guide for prerequisites, FFmpeg staging, Windows signing, macOS dylib bundling and
notarization, Docker publishing, versioning, E2E tests, and the release checklist.
Open it on GitHub.
ffmpeg.exe and ffprobe.exe in electron-app/ffmpeg/.run-electron-dev.bat for development or build-installer.bat for NSIS output.signing/snacks-signing.pfx and the gitignored signing/password.txt.brew install tesseract leptonica.electron-app/scripts/build-ffmpeg-mac.sh once per FFmpeg update. It builds FFmpeg 8.1.x with Homebrew's ffmpeg@8 options plus libzimg (HDR tonemapping) and libvorbis (Ogg Vorbis music) and stages it in electron-app/ffmpeg/; build-mac.sh refuses an FFmpeg older than 8.1.2 or one missing either library../build-mac.sh; it bundles non-system FFmpeg/OCR dylibs and produces a self-contained DMG.CSC_NAME, APPLE_ID, APPLE_APP_SPECIFIC_PASSWORD, and APPLE_TEAM_ID from electron-app/.env.mac.local.
The Windows installer and macOS DMG are written beneath electron-app/dist/.
Never commit signing certificates, passwords, or Apple credentials. The Docker
build-and-export.bat script pushes two public image names and requires an
explicit confirmation; use a normal local docker buildx build for testing.
| Area | Location | Responsibility |
|---|---|---|
| Composition | Snacks/Program.cs | DI, Kestrel, SQLite, logging, middleware, routes. |
| HTTP API | Snacks/Controllers/ | UI pages, JSON endpoints, cluster RPC. |
| Pipeline | Snacks/Services/TranscodingService.cs, VideoTransformPlanner.cs | Queue, FFmpeg execution, pure transform planning, retry, validation. |
| Cluster | Snacks/Services/Cluster*.cs | Discovery, orchestration, pure capacity policy, transfer, recovery. |
| Persistence | Snacks/Data/ | EF Core SQLite context, repositories, migrations. |
| Browser UI | Snacks/Views/, Snacks/wwwroot/ | Razor shell, ES modules, CSS, static assets. |
| Desktop | electron-app/ | Backend lifecycle, native window, packaging/signing. |
| Tests | Snacks.Tests/, electron-app/tests/, e2e/ | Pipeline/cluster regressions, browser/API-contract checks, and multi-process scenarios. |