Skip to content

Latest commit

 

History

History
1414 lines (1185 loc) · 86.1 KB

architecture.md

File metadata and controls

1414 lines (1185 loc) · 86.1 KB

Architecture

PlexFreq is a music player for Plex Media Server and Jellyfin servers on Sailfish OS (Qt 5.6 + Silica) and desktop Linux (Qt 6 + Controls 2). This document describes how it works today, and lists the external facts it depends on with their sources. The code is authoritative wherever this document disagrees with it.

1. Overview and responsibilities

Silica (Qt5.6) / Controls2 (Qt6) QML            presentation, navigation (Session.qml)
  │  backend.command(op,args) · backend.state/cache/playback · image://plexfreq
C++ adapter (app/src)                            Backend QObject, EntryModel, ArtworkProvider,
  │  C ABI: pf_runtime_submit / pf_runtime_poll  translations, window activation
Rust runtime (src/runtime.rs)                    admission, Core worker, events
  ├─ Core (src/lib.rs + domain modules)          queue/radio, cache, offline, store
  │    └─ MediaServer (src/server.rs)            Plex | Jellyfin HTTP behind one boundary
  ├─ audio engine (src/audio)                    Symphonia decode → rubato → DSP → libpulse
  └─ platform (src/runtime/platform.rs, pulse/)  MPRIS, BlueZ, ConnMan/NM, recording hold

Rust owns everything with policy or I/O. That covers server and media HTTP, credential persistence and use, models, queue and radio policy, worker lifetime, audio decoding, DSP and transport, the cache, offline snapshots, MPRIS, Bluetooth and network facts, persistence and diagnostics. Plex and Jellyfin are two backends of one MediaServer boundary (§3): Core states what it needs semantically and only the backend knows paths, parameters and headers.

C++ is a thin adapter. It turns Rust JSON into Qt properties, keeps two list models, translates messages, serves images through a provider (the bytes come from Rust) and raises the window. It has no server endpoint, queue order or media API (no QMediaPlayer, no QThread). The only credentials it handles are what the user types (a Plex token for a manual connection, a Jellyfin password), which it forwards to Rust (§11).

QML handles presentation and navigation only. app/qml/shared holds QtQuick 2.6-compatible code used by both shells. app/qml/pages is Silica and app/qml/desktop is Controls 2. Shared QML never imports either toolkit.

The artist grid in the library list footer is shared/WindowedGrid.qml: an item of the full grid height (so the list, its scroll bar and GridPosition see every row) containing a non-interactive GridView one list viewport tall plus a one-row margin, moved along the list. Only the delegates near the viewport exist, so browsing thousands of artists does not instantiate thousands of delegates. While a Silica context menu is open the window stays put. When the columns or cell size change, the inner GridView is reset (model re-assigned, item height held) so it lays out for the new geometry; on Qt 6.11 a GridView resized far from its start otherwise kept delegates of an unrelated range (not checked on Qt 5.6).

While the library shows the grid, the list's model is GridSpacer: one row (type: "spacer") that the list delegates render with height 0, invisible and disabled, so it is neither clickable nor given a context menu. The list needs it because a ListView without rows resets its position to the start whenever the footer grows: QQuickItemViewPrivate::layout() (qtdeclarative src/quick/items/qquickitemview.cpp, Qt 5.6 and 6.x) returns early with setPosition(contentStartOffset()) when !isValid() && !visibleItems.count(), and isValid() requires a model with rows. Verified on Qt 5.6.3 and Qt 6 that a single zero-height row prevents the reset for plain and grid footers, while scrolled, at the end and during a flick. Placeholder logic reads the footer's gridCount in grid mode, not the list's count. GridPosition only reacts to what the grid and the list report (jumps, active letter); it does not store or restore positions. Pages append to the grid in place, and a fresh listing (resetView) calls positionViewAtBeginning().

Threads

Thread Role
GUI Qt event loop. Polls the runtime every 100 ms; transport controls run synchronously at admission.
plexfreq-core Runtime worker. Owns Core, handles requests, engine events, health and maintenance ticks.
plexfreq-audio Audio actor: controls, pump, DSP. Dispatches the libpulse playback mainloop without blocking.
plexfreq-decode One per current or prepared track: Symphonia demux/decode, trim, resample.
plexfreq-rt The process-wide tokio current-thread runtime (src/rt.rs).
plexfreq-rt-blk Tokio blocking pool, at most 8 threads: DNS, cache/artwork filesystem writes, libpulse diagnostic samples.
plexfreq-recording libpulse recording subscription, which uses a blocking mainloop.
plexfreq-plan-refresh Serialized refresh of download plans against a read-only Core::inspect.
plexfreq-log Captures stdout/stderr into the dated log (Sailfish only).
plexfreq-gui-watch Watchdog logging GUI poll stalls (see Logs). Stopped and joined with the Runtime.

The runtime on plexfreq-rt runs the D-Bus observers, MPRIS, the diagnostic heartbeat, cache and artwork downloads, audio HTTP readers, health probes and the download-yield task. Nothing blocking may run on it; blocking work goes through rt::unblock, and waiting on a task from the runtime thread itself is refused. Core stays synchronous: it drives Plex requests with rt::block_on on its own thread, so JSON decoding never runs on the I/O thread. A current-thread runtime needs its own thread inside Runtime::block_on for that to work (tokio Handle::block_on docs). Dropping a Task aborts it. zbus uses its tokio feature (plus proxy and service, no default runtime), so its internal tasks run on the shared runtime.

Source map

Path Content
src/runtime.rs, src/runtime/ Admission, worker loop, held-failure resolution, download yield; MPRIS, BlueZ and network observers, heartbeat, health probes, libpulse introspection and recording subscription.
src/lib.rs, src/command.rs Core: typed commands and routing, playback planning, gone navigation, cache scheduling.
src/server.rs The media-server boundary: MediaServer trait, Backend enum, Caps, semantic Query/Action, BrowseSpec, StreamPolicy; the Plex implementation of the trait and, behind the mock-backend feature, the in-memory test backend.
src/plex.rs, src/quality.rs Plex HTTP client and sign-in, plus the shared HTTP helpers (bounded bodies, URL confinement, probes, base-path URLs); bitrate policy and the codec fallback table.
src/jellyfin.rs, src/jellyfin/dto.rs Jellyfin backend: requests, sign-in (password, Quick Connect), stream rules, reporting, playlists; wire DTOs and their mapping to the neutral model.
src/queue.rs, src/radio.rs, src/health.rs, src/history.rs Queue and occurrences, radio windows, gone marks, listen qualification.
src/cache.rs, src/offline.rs, src/artwork.rs Audio cache and downloads; metadata snapshots, lyrics and artwork store; image://plexfreq ids.
src/daily.rs, features.rs, discovery.rs, filters.rs, catalogue.rs, refresh.rs Discovery, download plans, playlists, mixes, filters, insights.
src/store.rs, src/diagnostics.rs Session files; log capture and redaction.
src/audio/* Audio engine.
src/ffi.rs, app/src/ C ABI and Qt adapter.
app/qml/shared/Session.qml Routes, history, paging, sign-in polling, shared presentation helpers.

2. Runtime and command flow

C ABI

pf_runtime_new(state_dir) starts the runtime, pf_runtime_submit takes a JSON request and returns an admission reply, pf_runtime_poll returns events, playback and busy state, and pf_runtime_free stops and joins the worker. Returned strings are freed by Rust, and every entry point runs under catch_unwind, so no panic unwinds into C++. Artwork source handles and requests outlive the runtime; once the worker has exited, requests answer nothing.

Admission

The runtime parses wire JSON into a typed Command (src/command.rs) once. Malformed, unknown and _-prefixed ops fail synchronously (accepted:false); the C++ adapter also refuses _ ops before submitting. Every command has a routing class, assigned by an exhaustive match, so a new op cannot go unclassified:

Class Effect
engine Play/pause/stop/toggle/seek/volume run on the calling thread against the audio handle, without entering the worker queue. Toggle follows logical intent: a buffering, held-failure or recording-held track toggles to pause.
listing A start of 0 replaces the list and starts a new view generation; a nonzero start appends and counts as loading-more.
view_bound Listings and similar-artists. Their Plex requests are cancelled when the view moves on, and the reply is discarded.
passive Status, lyrics, timeline, checkpoints and similar. These never raise busy.
transport Play/next/previous/radio and similar. Counted as pending user actions until the worker dequeues them.
reprepare Queue edits, shuffle, repeat, quality and audio config. The gapless successor is prepared again.
resets_session Connect, select server and logout. These stop the engine and clear the presented state.

Requests go to the worker over a bounded channel (256). If it is full, the call fails with "Backend command queue is unavailable" and nothing is counted as busy. Position checkpoints from the GUI and MPRIS never block: they are kept per occurrence, newest first, and applied in order, so an older checkpoint can never move a saved position backwards.

Worker

The worker handles one request at a time, interleaved with engine events, finished health probes and the held-failure state machine. Replies whose view went stale are discarded, both when they are produced and when Qt polls them. The artwork source is updated before each reply is sent, so the reply's image ids resolve.

Maintenance runs every 5 s (position checkpoint and, while a track is loaded and playing, a playing timeline; §4.7), every 2 s (download refresh and a cache-status update) and every 30 s (history sync while online).

At a gapless transition, the plan of the new occurrence is published exactly once, by whichever of the poll and the worker sees it first. Before any track has been decoded after start, the saved resume position and duration are shown for display only; that projection never reaches checkpoints.

A Stop resets the saved position. The engine applies Stop asynchronously, so until it has, engine snapshots of the stopped occurrence are ignored and a stale position cannot overwrite the reset.

Panic containment

Core execution runs under catch_unwind, and so does each worker iteration. A panic answers the request with "Backend panic", rebuilds Core from persisted state, re-applies the audio configuration, download control and last network facts, and publishes the rebuilt status. The audible track keeps playing. Every dequeued request is guarded, so a panic can never leave the UI busy. After 3 panics within 60 s, or a panic during recovery, the worker stops. On exit it answers every queued request with an error, applies queued checkpoints, records a final position, stops the engine, clears the artwork credentials and releases the download hold.

3. Server backends

Backend boundary

src/server.rs is the only place Core meets a media server. Core states what it needs as semantic values and the backend turns them into requests:

  • Query (reads: sections, item, children, similar, nearest, browse, hubs, search, playlists, radio windows, advertised keys) with a BrowseSpec (item kind, Sort, the user's Music filter, favourites/played flags, title search, limit) and a Page window.
  • Action (writes: rate, scrobble, timeline report, playlist rename, delete, add, remove, move).
  • MediaServer, the trait every backend implements: identifier validation, advertised_key (server-handed keys must be server-relative and may not carry the backend's credential parameters), parse_url, namespace, fetch, act, playlist and radio creation, lyrics, stream_url, transcode and probe calls, capabilities, and the hooks listed below.
  • Backend, an enum (Plex, Jellyfin, plus Mock in test builds) that implements MediaServer by forwarding. Enum dispatch keeps Core a plain struct that worker threads can clone, where generics or trait objects would spread through every module.

Hooks with a neutral default that a backend overrides when it differs: children_query/children_need_kind (Plex lists children by id alone; Jellyfin by the parent's kind), filter_schema/filter_fields/filter_choices (Plex learns filter fields from the section schema; Jellyfin lists genres), smart_source, reports_start (the server counts a play when it starts) and mix_query (a server-side instant mix for a client-side radio).

Plex sign-in and discovery (PIN, resources) is the separate Account trait that only the Plex backend provides; Backend::account refuses it for Jellyfin. While a Jellyfin session is active, an account command is served by a temporary Plex client, so a Plex account can be signed in without leaving the session.

Capabilities. Caps lists what a server may lack: sonic similarity, Sonic Adventure, server stations, smart playlists, server hubs, the alphabet index, star ratings and the mood, style and minimum-rating filters. Plex offers all of it. Jellyfin offers only server hubs, which it synthesises from ordinary queries. The status JSON and the session replies (libraries, sign-in, sign-out) publish capabilities with serverKind, so a server switch updates them, and Session.qml can(name) hides the matching actions (a flag the server did not publish counts as available). Core independently refuses every command that needs a missing capability (Command::requires), so a stale or hand-sent command cannot reach an endpoint the server lacks.

StreamPolicy. The audio engine, the downloaders and the artwork loader do not hold a backend. They hold a StreamPolicy: the credential as HTTP headers (never a URL parameter) plus the backend's StreamRules (identifier rule, progressive transcode URL, whether a URL is a transcode, how to seek one, which request tears its session down, download, artwork and metadata URLs). A policy attaches its headers only to a URL on its own origin and under its base path (StreamPolicy::headers_for), so a stale, foreign or untrusted URL never receives the credential. A transcode cannot seek by byte, so a seek on one asks the rules for a restarted URL and a stop asks for the teardown request; both go through the policy. The default policy is Plex with no credential and no base (tests, local files).

Namespaces. Everything stored per server (audio cache, offline snapshots, artwork ids, download pins, play history) is scoped by the backend's namespace(conn): for Plex SHA-256 of the server URL and token; for Jellyfin SHA-256 of jellyfin, the server id and the user id. Jellyfin's scope contains neither the address nor the token, so signing in again, or reaching the same server at another address, keeps downloads and history. Signing in to another scope drops pins, downloads and the queue.

Base paths. A Plex server URL is a bare origin. A Jellyfin URL may carry a path (https://host/jellyfin), since Jellyfin is often served at a prefix behind a reverse proxy. server_url_with_base_path normalizes it to end in one / and rejects empty, dot and encoded-separator segments; server_path joins every request path below the prefix on the same origin, and StreamPolicy::covers requires it too.

Test backend. Backend::Mock(MockServer) is an in-memory MediaServer that records every Action and answers scripted Query values, for tests that drive Core without HTTP. It exists only under cfg(any(test, feature = "mock-backend")). The mock-backend feature is off by default and none of the scripts that build a release (RPM, desktop archive) enables it; tools/check.sh and CI pass --all-features to compile and test it.

Plex integration

HTTP

Every HTTP client is built by plex::client_builder: rustls with the ring crypto provider, TLS 1.2 and 1.3, ALPN http/1.1, and the Mozilla root certificates compiled in from webpki-roots, not the system trust store. reqwest 0.13's rustls feature selects aws-lc-rs (a C library) and verifies against the platform trust store; the app enables rustls-no-provider instead and hands reqwest a prebuilt rustls::ClientConfig (ClientBuilder::tls_backend_preconfigured, which uses the config as given; reqwest 0.13 source, async_impl/client.rs). That feature still compiles in reqwest's platform verifier, but no client uses it. No client falls back to a default client, which would lose the roots and the redirect policy: the shared client panics if it fails to build, the cache worker and the session closer stay inactive, and a stream reports the error.

One pooled reqwest client is shared by Core, plan refresh and artwork: 15 s total timeout, 5 s connect timeout, redirects disabled. The Plex token always travels in an X-Plex-Token request header; an open redirect could send that header to another origin, so a 3xx surfaces as a failure instead. Default headers are Accept: application/json (new clients should prefer JSON; https://developer.plex.tv/pms/), X-Plex-Product, X-Plex-Version, X-Plex-Platform and a persistent X-Plex-Client-Identifier (a UUID in the session).

JSON bodies are bounded to 8 MiB before deserialization, lyrics to 512 KiB and artwork to 4 MiB. 401/403 map to Unauthorized, other non-2xx to an HTTP error, transport errors to Network. Reqwest's per-read timeout resets after every successful read, unlike the whole-request timeout (docs.rs reqwest 0.13 ClientBuilder::read_timeout).

Plex Media Server passes tag bytes through unchanged, so a file tagged in Latin-1 or Windows-1252 puts invalid UTF-8 inside an otherwise valid JSON or lyrics body. Valid UTF-8 is kept and each invalid byte is read as Windows-1252 (the WHATWG Encoding Standard "latin1" decoder) instead of rejecting the page. Invalid bytes are all at least 0x80, so they never alter JSON structure.

URL confinement (plex.rs): a server URL must be a bare HTTP(S) origin. Request paths must be query-free and server-relative; //, \, dot segments, control characters, and literal or encoded separators/escapes (%2e %2f %5c %25 %3f %23 %00) are rejected, and the joined origin is checked. Advertised keys (station, hub and artwork keys) may carry queries, but never an X-Plex-* parameter.

Authentication and servers

  • PIN sign-in. POST https://plex.tv/api/v2/pins, then poll api/v2/pins/{id} while the user authorizes in a browser.
  • Servers. api/v2/resources?includeHttps=1&includeRelay=1 (python-plexapi myplex.py, a community implementation rather than a stability promise). The resource list mixes servers with players. Players may carry a null or missing accessToken, so only resources whose provides contains exactly server are decoded. Malformed server entries are skipped (https://www.plexopedia.com/plex-media-server/api-plextv/resources/).
  • Connecting. Connections are tried in this order: non-relay, then HTTPS, then local, using the resource's own access token. Certificate validation is never disabled.
  • Manual connect. The user enters a server origin and a token.
  • Persistence. Account and server tokens persist only in the private session (§10). Server summaries sent to the UI never include tokens.

PMS endpoints used

Music types are artist=8, album=9 and track=10. Pages use X-Plex-Container-Start and X-Plex-Container-Size, normally 100 items. Sources for this table: https://developer.plex.tv/pms/, python-plexapi (library.py, audio.py, playqueue.py, playlist.py, media.py, mixins/rating.py, mixins/played_unplayed.py) and https://plexapi.dev reference pages.

Purpose Endpoint and behaviour
Browse /library/sections/N/all, pairs in this order: filters ({kind}.genre/mood/style ids, title, {kind}.year>=/<=, {kind}.userRating>=, {kind}.viewCount=0), type, userRating=10 (favourites), sort, title (search), viewCount>>=0 (played), limit (smart playlists). Sort is field:asc/desc or random. Filter field scopes come from the section's schema (all?type&includeMeta=1&includeAdvanced=1, Meta.Type[].Field[].key, e.g. album.genre for tracks), which also advertises the genre/mood/style choice keys.
Alphabet /library/sections/N/firstCharacter (artist type, titleSort). Returns Directory groups with key/size/title; summed sizes give page offsets.
Detail / children /library/metadata/N, /children. Durations are in ms. Year and index values may be null and are parsed as signed.
Similar artists /library/metadata/N/similar. 400/404 mean unavailable. Capped at 12 numeric library artists.
Sonic /library/metadata/{ids}/nearest, section computePath?startID&endID (Sonic Adventure). Sonic analysis needs a server-admin Plex Pass on PMS ≥ 1.24 (https://support.plex.tv/articles/sonic-analysis-music/). A missing musicAnalysisVersion is not a signal; the endpoint answer is.
Stations Metadata with includeStations=1. Stations may be an array or a {size, Metadata} container. The station key becomes a play queue server://{machine}/com.plexapp.plugins.library{key} via POST /playQueues; windows come from GET /playQueues/{id}?center=&window=&includeBefore=&includeAfter=.
Hubs / search Section hubs; /hubs/search?query&limit returns Hub.Metadata. Recent hubs are identified by music.recent.added.<section> and music.recent.played.<section>.
Lyrics The Part.Stream with streamType 4 and its advertised key. The response may be plain/LRC or JSON MediaContainer.Lyrics[].Line[].Span[].text. A blank line is {} with no Span. Start times may be fractional ms.
Rating PUT /:/rate?key&identifier=com.plexapp.plugins.library&rating=0..10.
Playlists Regular items are identified by playlistItemID (uppercase on the server). Smart playlists have no occurrence ids and are read-only here. leafCount; duration may be absent for empty playlists.
Timeline POST /:/timeline with key/ratingKey, state, time, duration, continuing, plus playQueueID/playQueueItemID for stations.
Scrobble GET /:/scrobble?key&identifier=com.plexapp.plugins.library. This is the established python-plexapi form; the community OpenAPI describes POST with ratingKey.
Transcode See §4.2.

The parsers tolerate gain/albumGain as numeric strings (unusable values are omitted without invalidating the item) and radio flags given as "1".

Missing items

After a music section is re-created, old ratingKeys and Part URLs answer 404. The track comes back under a new ratingKey with the same guid=plex://track/…. PlexFreq does not look items up again by guid: a Gone item is skipped, and the user plays the new copy from the library. A transcode start.m3u8?path=/library/metadata/<stale> answers 400, not 404.

PMS's own 404 carries X-Plex-Protocol: 1.0 with an HTML body. A 404 without that header may come from a proxy and proves nothing. Only a 404 with the header counts as Gone; 401/403 is Auth; everything else is Unknown.

An emptied station answers 200 with zero items for any center. A healthy queue answers zero items for a center it no longer holds. Zero items therefore does not prove a station is dead.

Jellyfin integration

Sources: the jellyfin/jellyfin controllers on release-10.11.z and 12.z, the stable OpenAPI spec at https://api.jellyfin.org (12.4), jellyfin-web playbackmanager.js, and the Finamp and Feishin clients as other implementations. Where behaviour is not documented, the client is defensive instead of assuming it; those places are named below.

HTTP and authentication

Jellyfin shares the pooled reqwest client, timeouts, no-redirect rule and body bounds (8 MiB JSON, 512 KiB lyrics) of the Plex backend, with two differences in status mapping: 401 is Unauthorized, and a refused write (403) is reported as a permission of the account (HTTP 403), not as a stale sign-in. Requests ask for Accept: application/json and carry the user id as a userId query parameter once signed in.

The credential is one header on every request, including audio, transcode, artwork and metadata requests (through StreamPolicy):

Authorization: MediaBrowser Client="PlexFreq", Device="<host>", DeviceId="<client id>", Version="<app version>", Token="<access token>"

The server URL-decodes the values, so the client keeps them ASCII (anything else becomes _) and percent-encodes %, +, " and ,. DeviceId is the persistent client identifier. The legacy api_key query form is not used.

  • Server check. GET /System/Info/Public (anonymous) must answer ProductName "Jellyfin Server" and a Version of at least 10.9. The client relies on the Quick Connect POST /QuickConnect/Initiate, the track NormalizationGain and HasLyrics fields and the /Audio/{id}/Lyrics endpoint, which are present in the jellyfin/jellyfin release-10.9.z branch and absent from release-10.8.z (Jellyfin.Api/Controllers/QuickConnectController.cs, LyricsController.cs, MediaBrowser.Model/Dto/BaseItemDto.cs). The album gain AlbumNormalizationGain exists only in 12.x; on an older server it is absent and album gain is not available. Id is the server id of the namespace.
  • Password. POST /Users/AuthenticateByName with {Username, Pw} answers {AccessToken, ServerId, User.Id}. The password exists only in that request body: it is not stored, logged or kept.
  • Quick Connect. GET /QuickConnect/Enabled must be true; POST /QuickConnect/Initiate answers {Secret, Code}. The UI shows the code, which the user enters in an already signed-in Jellyfin client. GET /QuickConnect/Connect?secret= is polled every 2 s until Authenticated, then POST /Users/AuthenticateWithQuickConnect {Secret} returns the session. Core gives up after 9 minutes, and an unknown or expired secret (404) ends the attempt with a "Login expired; start again" notice. The UI polls in the background, one request at a time, and stops as soon as the user cancels; a poll that arrives with no login pending is answered with quickConnect: null, not an error. The secret stays in Rust.
  • Persistence. The access token, user id, server id and server kind persist in the private session (§10). Sign-out calls POST /Sessions/Logout, best effort with a 3 s bound, then clears the session as for Plex.

Jellyfin endpoints used

Item ids are 32 lowercase hex digits; dashed or uppercase GUIDs are normalized and anything else is not an id. Pages use StartIndex and Limit; the reply is {Items, TotalRecordCount, StartIndex}. Listings ask for Fields=MediaSources, Genres,DateCreated,ChildCount,PrimaryImageAspectRatio.

Purpose Endpoint and behaviour
Libraries /UserViews, keeping CollectionType music; each becomes an artist section.
Browse Artists /Artists/AlbumArtists (the spec marks it deprecated, the source does not; a 404 falls back to /Items?IncludeItemTypes=MusicArtist&Recursive=true); albums /Items?IncludeItemTypes=MusicAlbum; tracks Audio. ParentId is the library; SortBy/SortOrder map the sorts (SortName, DateCreated, ProductionYear,SortName, DatePlayed, PlayCount, Random); Filters carries IsFavorite, IsPlayed, IsUnplayed; GenreIds; Years is the comma list of the year range (at most 200 years); SearchTerm is the title condition.
Children Album tracks /Items?ParentId=album&IncludeItemTypes=Audio, ordered by disc and track number; artist albums /Items?AlbumArtistIds=artist&IncludeItemTypes=MusicAlbum; playlist items /Playlists/{id}/Items; all tracks of an artist ArtistIds=. An artist is not a folder parent of its albums, so the parent's kind selects the query and is read from the item when the UI did not supply it.
Detail /Items?Ids=id with Overview added.
Similar /Items/{id}/Similar (genre and tag overlap, not audio analysis).
Hubs Four synthesised hubs per library, each its own query: recently added (/Items/Latest, whose reply is a bare array, 12 albums), recently played (DatePlayed, IsPlayed), favourites (IsFavorite) and most played (PlayCount, IsPlayed). Identifiers are music.recent.added.<library>, music.recent.played., music.favorites., music.most.played.; keys are /hubs/jellyfin/<library>/<name>. Empty hubs are omitted. Core titles are English; the C++ adapter translates them for Jellyfin sessions only (Plex keeps its server titles).
Search Three queries so one type cannot crowd out the others: /Artists?SearchTerm, /Items?searchTerm&IncludeItemTypes=MusicAlbum and Audio, each with the limit.
Genres /Genres?ParentId=library, for the genre filter.
Instant mix /Items/{id}/InstantMix?Limit= (clamped to 1..200) for every seed kind, with each of Fields, and EnableImageTypes (Primary, Backdrop) as its own repeated parameter plus EnableImages=true and EnableUserData=true: the AudioMuse-AI action binds plain arrays, which do not split a comma list, and leaves images and user data out unless asked, while stock Jellyfin's CommaDelimitedArrayModelBinder accepts repeated values (jellyfin/jellyfin CommaDelimitedArrayModelBinder.cs). Stock Jellyfin serves this route and the per-kind ones from GetInstantMixFromItem, which draws the batch randomly from tracks sharing a genre with the seed, so each call differs (InstantMixController.cs, MusicManager.cs). InstantMix plugins order the batch by audio similarity. AudioMuse-AI (github.com/NeptuneHub/audiomuse-ai-plugin, Controller/InstantMixController.cs) and BetterMix (github.com/StergiosBinopoulos/jellyfin-plugin-bettermix, Filters/ItemInstantMixFilter.cs, BetterMixPlugin.cs) replace only this route; Harmonie (github.com/mxschll/jellyfin-harmonie, Services/HarmonieMusicManager.cs) replaces the server's music manager, so every route. AudioMuse-AI returns the seed and its nearest neighbours for a song seed, so the same song gives nearly the same batch; artist and album seeds pick random seed songs, and a short batch is filled from the stock mix. A mix radio therefore rotates seeds: when a refill's reply holds no playable track that is not queued yet, the same refill asks again with queued tracks as seeds (newest first, skipping the radio's seed, the seeds already used and tracks known to be gone), at most three requests in all. A fallback seed whose request is refused (for example 404) counts as used; a connection or 5xx failure stops the rotation without using the seed; an authorization failure fails the refill; otherwise only a failure of the radio's own seed fails it. The asked seeds are kept in Source::Mix.used (at most 64, oldest dropped; serde default, so older queue files load) and a refill that still finds nothing fails with "Radio returned no playable tracks". A refill that brings new tracks asks only the radio's own seed. With a plugin whose song mixes are stable, a refill usually takes two requests (the radio's own seed, then a queued track); they run off the runtime thread, on the radio or core thread.
Favourites POST / DELETE /UserFavoriteItems/{id}: a rating above 0 favourites, 0 removes.
Reporting POST /Sessions/Playing, /Sessions/Playing/Progress, /Sessions/Playing/Stopped; see Play reporting.
Offline plays POST /UserPlayedItems/{id}?datePlayed=<ISO 8601 UTC>.
Playlist list /Items?IncludeItemTypes=Playlist&Recursive=true&SortBy=SortName.
Playlists See Playlists.
Lyrics GET /Audio/{id}/Lyrics answers {Metadata, Lyrics:[{Text, Start}]}; 404 means none.
Artwork /Items/{id}/Images/Primary?tag=&maxWidth=1000&quality=90 (backdrops Backdrop/0), requested with the credential header like every other request.
Gone probe Status-only GET /Items/{id}.

Every id put into a path is validated, and server-handed keys are validated as for Plex, additionally rejecting api_key, ApiKey, Token, X-Emby-Token, X-MediaBrowser-Token and Authorization parameters.

Model mapping

The wire DTOs (src/jellyfin/dto.rs) default every missing or null field and skip a malformed item instead of failing its page; a playlist with a non-audio MediaType is skipped, and a playlist without MediaType is kept.

  • Identity. Id is the rating key and /Items/{id} the key. MusicArtist, MusicAlbum, Audio and Playlist map to the neutral kinds. A track's parent is its album (AlbumId) and its grandparent its first album artist (AlbumArtists, else ArtistItems); an album's parent is its artist. Track artists that differ from the album artist fill originalTitle.
  • Time. RunTimeTicks are 100 ns ticks: milliseconds are ticks / 10 000, and report positions and seeks are milliseconds * 10 000. Index, disc and year numbers may arrive as fractional numbers and are truncated.
  • Images. ImageTags.Primary gives the item's image; a track without one shows its album's (AlbumId with AlbumPrimaryImageTag). The tag and the size are part of the stored path, so the path is the whole image identity.
  • Media. The first MediaSources entry gives the container (an ffprobe family such as mov,mp4,m4a,3gp,3g2,mj2 is reduced to the first name PlexFreq decodes, else the first), the codec of the first audio stream, the bitrate (bits/s to kbps) and the size. The part key is /Audio/{id}/stream?static=true: the original bytes, with range support.
  • Gains. NormalizationGain (track) and AlbumNormalizationGain fill the gain fields Plex's loudness data fills. A server that omits them plays without leveling.
  • Lyrics. HasLyrics adds a lyric stream with key /Audio/{id}/Lyrics. Start is in ticks and absent for unsynchronised lyrics. The document's Metadata.Offset is not applied: whether Start already includes it is not documented, and applying it to a value that has it would shift every line twice.
  • Favourites. UserData.IsFavorite maps to the user rating 10 (else 0), so the favourite toggle and the Favorites listing work unchanged. There are no star ratings.
  • Entry ids. PlaylistItemId is the playlist entry id (opaque, at most 64 characters of letters, digits and -). Jellyfin does not document it as unique per occurrence of a track, so the client assumes defensively that a track listed twice may share one id and never sends an id that occurs more than once (see Playlists).

Streaming, transcoding and stopping

An original plays from /Audio/{id}/stream?static=true with the credential header, byte ranges and resume as in §5.2. A transcode is a progressive MP3:

/Audio/{id}/stream.mp3?audioCodec=mp3&audioBitRate=<bps>&startTimeTicks=<ticks>&deviceId=<client id>&playSessionId=<uuid>&static=false

The bitrate must be one of PlexFreq's quality steps and the session a UUID. A progressive transcode answers Accept-Ranges: none, so it cannot seek: a seek or restart rewrites the URL with a new startTimeTicks (milliseconds * 10 000) and a fresh playSessionId. The fresh id matters because a late stop for the old session must not kill the restarted job; one playSessionId never covers two requests.

The stop request is DELETE /Videos/ActiveEncodings?deviceId=&playSessionId= (present in the 10.11 sources, absent from the 12.4 spec). It is best effort; the server also ends a progressive job shortly after its last request. Downloads and the transcode probe use the same rules, and the probe stops its throwaway session the same way.

Play reporting

Jellyfin increments a play count when playback starts, not at the end. Core therefore reports Sessions/Playing once per playback occurrence (the first playing state), persisted in the session (playback.start_reported) so a restart that restores the queue does not count the track again. Later states go to /Sessions/Playing/Progress and the end to /Sessions/Playing/Stopped. Each body carries ItemId, MediaSourceId, PlaySessionId (the occurrence id), PositionTicks, PlayMethod (DirectPlay or Transcode), IsPaused and CanSeek. The next track starts without a command, so a transition also reports the stop of the previous one.

A qualified listen whose start was reported is already counted: its history entry is marked delivered and never scrobbled. A listen whose start was never reported (offline, or not yet sent) is replayed by the history sync through POST /UserPlayedItems/{id}?datePlayed=, oldest first, so the server records when the play happened. Plex's scrobble cannot.

Playlists

A playlist is created with POST /Playlists {Name, Ids, UserId, MediaType: "Audio"} (the reply's Id is the new playlist). Tracks are appended with POST /Playlists/{id}/Items?ids= in requests of at most 100 ids, removed with DELETE /Playlists/{id}/Items?entryIds=<PlaylistItemId> (after the pre-read below), renamed with POST /Playlists/{id} {Name} and deleted with DELETE /Items/{id}. Entries are read from /Playlists/{id}/Items in pages of 500 (at most 100 000).

Before every remove and every move, whatever its arguments (including an explicit index), the list is read as the server has it now. An entry (or after entry) that is not in it is refused with "The playlist entry was not found"; one that occurs more than once is refused with "This track is in the playlist more than once and the server cannot tell the copies apart". Both are refused before any write, because a delete by a shared id could remove any or all of its copies.

A move is POST /Playlists/{id}/Items/{PlaylistItemId}/Move/{newIndex}, 0-based. The UI names the entry to go after, so the index is derived from the pre-read list: the moved entry is taken out and the index is one past the after entry (0 when there is none; an explicit index is used as given). The server answers 204 even for an entry it does not know, so the list is read back and the move counts only if the entry now sits right after after (or at the target index when it went to the top); otherwise it is reported as not moved ("The server did not move the playlist entry"). Smart playlists do not exist.

Radio

Jellyfin has no stations. Artist, album and track radio use Source::Mix (§4.4): a client-side radio that asks the InstantMix of the seed for a batch and, on each refill, appends the tracks not queued yet. A track radio starts with its seed.

Gone detection

A deleted item answers 404 to GET /Items/{id}, and so does an item the user may not see. Only a 404 carrying the server's X-Response-Time-ms header counts as Gone, because a proxy's 404 does not carry it. That header is the mark of the server's response-time middleware, not a documented contract, so when it is absent the result is inconclusive, never a false Gone. 401 and 403 are Auth; everything else is Unknown.

Not available on Jellyfin

Sonic similarity, Sonic Adventure, server stations and station downloads, smart playlists, the alphabet jump, the mood, style and minimum-rating filters and star ratings (favourites only) have no Jellyfin counterpart. Core refuses their commands and the UI hides them (§3, Capabilities). The nearest, filter-schema, first-character, compute-path and play-queue reads answer "This server does not support this feature".

4. Playback and queue

4.1 Queue and occurrences

The queue (src/queue.rs, at most 10 000 items) holds the items and cursor, the shuffle permutation, the repeat mode (off, one, all) and history behind the cursor.

Shuffle keeps the current track and visits every item once in permutation order; Previous follows that permutation. Repeat-one applies to automatic advance only, so a user Next skips it. The queue ends with no selection unless repeat-all wraps. The queue view shows playback order as an editable linear list.

Each start of a track creates a playback occurrence, which rejects stale checkpoints. The engine works in occurrences, not rating keys: station queues repeat songs under distinct playQueueItemIDs, and playlists use playlistItemID (Jellyfin: PlaylistItemId). List row identity likewise includes these ids.

4.2 Plans, sources and quality

Core resolves the selected item into a plan: the queue, the visible track, the stream URL, the playback source (cache, stream or transcode) and the bitrate. A completed cache file is preferred before any metadata or network work. The stream URL never leaves Rust; it is stripped before anything reaches the model or Qt.

Quality settings are a Wi-Fi, a mobile and a download bitrate (each original, or one of 64/96/128/160/192/256/320 kbps) and a codec-fallback switch. The mobile choice applies only on a known cellular link; Wi-Fi, Ethernet and an unknown network use the Wi-Fi choice. The mobile default is 320 kbps when nothing is stored; an explicitly stored "original" stays original.

A plan transcodes when the streaming cap is nonzero, or when codec fallback is on and the original's (container, codec) pair is not decodable:

Codec Containers
MP3 mp3
FLAC flac
AAC mp4/m4a/m4b/aac
ALAC mp4/m4a/m4b
Vorbis ogg
PCM s16/24/32le wav

Plex reports these as lowercase identifiers; for Jellyfin the container is reduced to the first name PlexFreq decodes and the codec is that of the first audio stream, lowercased. Anything else, including empty values, is transcoded.

The transcode URL, its seek and its teardown come from the backend's StreamRules (§3). Jellyfin's are in §3 (Jellyfin integration). Plex's:

Progressive transcode (quality::transcode_url):

  • /music/:/transcode/universal/start.m3u8?path=/library/metadata/K&protocol=http
  • directPlay=0&directStream=0&directStreamAudio=0&audioCodec=mp3
  • musicBitrate, minAudioBitrate and maxAudioBitrate set to the cap
  • X-Plex-Client-Profile-Extra: an mp3 musicProfile and a bitrate upper bound
  • a fresh session UUID and an offset in seconds

With protocol=http the body is a progressive MP3, not an HLS playlist (Plex for Kodi audioobject.py; Music Assistant Plex provider). A transcode cannot seek by byte, so every load or seek creates a new session at a time offset. The old session is closed in the background with /video/:/transcode/universal/stop?session=… (OpenPHT PlexMediaServerClient.cpp); the server also expires idle sessions.

4.3 Gapless preparation

After any command that starts or changes playback, the worker computes the successor speculatively, without changing the queue or radio, and hands its plan to the engine, after the reply presenting the current track. Only one successor is predecoded at a time. Its queue position, radio refill and new occurrence are committed only when the engine reports that it became audible.

4.4 Radio

src/radio.rs owns the radio kinds and source URIs.

  • Station radio (artist and discovery stations) keeps the server playQueueID. Its window is replenished one unseen playQueueItemID per advance. History is trimmed so current, future and recent rows fit 11 rows. When a station occurrence completes naturally, a stopped timeline with continuing=1 is reported before the refill.
  • Sonic track radio chooses nearest tracks and remembers up to 200 recent seeds.
  • Mix radio (Jellyfin: artist, album and track radio) is client-side: each refill asks the server's instant mix of the seed again and appends the tracks not already queued. A track radio starts with its seed. It is not recorded as a station, so no station timeline is sent.
  • Album radio expands whole next albums and may exceed the window.
  • Unsupported seeds and failed continuations keep the previous queue (transactional).

Radio refuses shuffle and repeat. A failed completion report blocks continuation only for an authorization failure.

Offline and failure continuation. In explicit offline mode, on a known disconnected network, after a network or 5xx refill error, and at the end of the window after any non-auth refill failure (including the empty station of a re-created library), the radio window is traversed in playback order, skipping entries without complete cached audio and wrapping.

The window is not trimmed then, so cached history stays available. With nothing cached, playback ends with either the gone notice or the refill error. An ended station's Next resumes from its last audible item.

Background refill. A move whose next item has complete cached audio does not wait for the server: the refill is owed (Radio.refill.pending, at most 12, persisted with the session) and the worker fetches it on a separate thread. The worker never blocks on that request. The result is applied between worker messages, and only to the state it was fetched for: the same radio instance (random per radio), source version, queue revision and server. Otherwise it is fetched again. It only appends, so queued queue commands keep their indices. A prepared successor of the same radio state receives the same items, so its commit keeps them; a successor already shown waits for its commit and a new fetch. A failed background refill clears the debt; the next move refills as usual. A move onto an uncached successor or at the end of the window still refills before moving, so its network-failure fallback above applies. The station completion report of an automatic move is still sent before the move.

Refill center. The refill is centred on the current item if it is not gone. Otherwise it uses the last held non-gone item, because PMS answers nothing after a centre it no longer holds.

Refresh warnings. Failed refresh requests, cached metadata fallbacks during refill, station responses with no unseen occurrences, and known disconnection raise a transient warning for the UI and system notifications (§8.6). It reports a failed refresh attempt, not proof that a cached loop became audible: a real request made while preparing a successor can warn even if that successor is discarded. Explicit offline mode suppresses it. Stale results and worker failures are rejected using the Core instance, radio, source, server and queue identity; a successor already presented waits for its commit. The warning is drained once by the worker, independently of navigation and playback-plan publication. Queue continuation policy is unaffected.

4.5 Health and gone items

Checks start only after a failure: a cache-ahead download answered 404 (or 400 for a transcode), a gapless successor failed to pre-load, the current stream failed after the cache and transcode fallbacks, or a metadata fetch answered 404. The check is the backend's status-only existence probe (Plex GET /library/metadata/{key}, Jellyfin GET /Items/{id}; 5 s, credential in a header). At most 10 probes run per rolling minute and 2 at a time, with part of that budget reserved for current-track failures. A key is not probed again for 60 s after an inconclusive result, and an Auth result suspends probing. Results from before a queue, server or Core change are discarded.

Gone marks (src/health.rs) last 10 minutes, because a rescan can restore an item. They are cleared on connect, select server and logout, and dropped when a queue replacement succeeds. An explicit Select, Play or Resume of a gone item clears its mark and retries it.

Next (manual or automatic), Previous, removing the active item and successor preparation step over gone items that are not served from the cache, in the direction of travel. Forward with nothing playable left is a natural end with a gone notice, leaving the cursor on the last audible item; backward with nothing behind is an error, and the queue is restored. Cache-ahead looks past gone keys, so its window keeps its size. Gone rows are dimmed and labelled "No longer on the server" on both shells. A successor that fails to pre-load is dropped silently and checked, and preparation continues past it once the verdict is Gone, so a run of deleted tracks is found while the current track still plays.

Current-track verdict. A Gone verdict skips automatically only if the item is still current, no user playback request is pending, and the target needs no metadata fetch. Otherwise the user sees "This track is no longer on the server". If the verdict is inconclusive, or none arrives within 8 s, the original error is shown.

4.6 Held stream failures and restarts

A current-track stream failure is held instead of discarded, so recovery can never override a later user control. When the current decoder fails, the successor is dropped, the output plays what was already submitted, and the engine publishes a held state that preserves position, listened time and play intent. While a failure is held, Play/Pause change the held intent, Seek moves the held position, and Stop or a new load end it. The worker resolves it (recover, replace or abandon); a failure that nothing resolves is given up after 60 s. Toggle and MPRIS status count buffering and held failures as Playing.

The recovery chain for the current item:

  1. Cache. The complete cached file, if one exists.
  2. Transcode restart (only when the failing source was a transcode). The stream restarts at the held position, never within 5 s + crossfade of the end. A restart needs new audio from the failed attempt; at most 4 attempts are made without 10 s of new audio, with backoff 0, 2, 4 and 8 s. While paused or known offline, the restart waits for Play or the network without spending an attempt. A pending user request decides instead of a restart.
  3. Transcode of an original that failed.
  4. Gone check (§4.5), then skip or report.

Early transcode end. PMS can end a transcode cleanly before the track's duration. That is treated as truncation and restarted as above, even when the start buffer had released no audio yet; a stream that decoded nothing stays a plain failure. If a restart's decoded audio ends early again within 1 s of where the previous attempt's did, the media is shorter than its metadata, and it is treated as the real end: the listen is recorded and playback advances (keeping a paused state), or ends without a banner if nothing follows.

4.7 Listens, history and timelines

The audio engine computes listened time per occurrence from output frames, so seeks do not count; Core qualifies and records it. A play qualifies at ≥ min(half the duration, 240 s). Qualified plays are stored in listens (at most 10 000, for insights) and in the history outbox (at most 2 000). Delivered entries are evicted first; when the outbox is full of undelivered plays, recording fails until a sync.

History sync delivers up to 20 undelivered plays per pass, oldest first. It runs every 30 s while online, and when the user asks. Plex's scrobble endpoint cannot restore the original listen time, and an acknowledgement lost in transit can cause a duplicate. A backend that counts a play when it starts (Jellyfin) hears the start once per occurrence, persisted so a restart does not repeat it; a listen whose start was reported is marked delivered without a scrobble, and one whose start was not is delivered with its original time (§3, Jellyfin integration).

While a track is loaded and playing, a playing timeline is sent about every 5 s, within the "normally every 10 s" guidance at https://developer.plex.tv/pms/. Timelines are not sent for cached playback, in explicit offline mode, or on a known-offline network. Jellyfin receives the same states as session reports (§3, Jellyfin integration).

5. Audio engine

5.1 Structure

plexfreq-audio actor: controls, pump, DSP, crossfade, PulseAudio mainloop dispatch
  ├─ Decoder (current)   ── plexfreq-decode: Symphonia → trim → stereo → rubato 48 kHz
  │     └─ http::Source (blocking Read+Seek) ⇐ byte window ⇐ async reader task (plexfreq-rt)
  ├─ Decoder (successor) ── same pipeline, 1 MiB window until promoted
  └─ Output: PulseAudio stream | Fake (real-time, silent) | Capture (instant, recorded)

Controls reach the actor over a bounded channel; the engine publishes a snapshot and a change watch (transport fields without position) that drives MPRIS, the heartbeat and the download yield without polling. PLEXFREQ_AUDIO_SINK=fake selects the fake sink.

Output is fixed at 48 kHz, stereo, float32. There is no bit-perfect or sample-rate-matching claim.

5.2 HTTP input (src/audio/http.rs)

An async reader appends response bytes to a bounded window: 4 MiB for the current track and 1 MiB for a successor until promotion. It has a 5 s connect timeout and a 10 s read timeout, with redirects disabled. The credential headers of the track's StreamPolicy are sent, and only to a URL the policy covers (§3); the decoder never sees a URL. A read outside the window, or more than 64 KiB ahead of it, starts a new request at that offset, and bytes of a superseded request are never used.

Ranged resume follows RFC 9110 (§13.1.5 If-Range, §14.4 Content-Range, §15.3.7): a nonzero offset requires a strong ETag or Last-Modified validator and is sent with Range + If-Range; Content-Range is validated, including * for an unknown total; if the server ignores the range and answers 200, the prefix is skipped only when the validator matches.

Retries:

  • Until bytes have entered the window, 3 retries are allowed (4 requests in total, 1/2/4 s apart). Exhausting them fails the decoder, so the runtime can choose a fallback. Entering the window is the only proof required; it does not imply successful decoding or audible output.
  • After that, transient network and 5xx failures of a byte-resumable original keep retrying the same representation, backing off 1/2/4/8 s (capped at 8 s), until a seek or Stop. A response that makes no progress loses this status.
  • A progressive transcode is not resumable by bytes. Its broken transfer is a stream failure, handled by the restart in §4.6.

A broken transfer still hands over the bytes it already received, so playback continues to the heard position before the failure surfaces.

5.3 Decoding (src/audio/decode.rs, mp4.rs, resample.rs)

Symphonia 0.6.1 is built pure Rust, with default features off and flac, mp3, aac, alac, isomp4, ogg, vorbis, wav, pcm enabled. It has no Opus or WMA decoder (docs.rs/symphonia 0.6.1; crate sources).

Each decoder picks the first audio track with a compiled decoder (ignoring cover-art video tracks) and seeks sample-accurately for resume. Mono is duplicated to stereo; more than 2 channels get an ITU-style downmix normalized to full scale, with LFE dropped. Symphonia's probe treats a read error as end of stream, so an HTTP failure during probing is logged alongside the "no suitable format reader" error.

Gapless trimming.

  • Packet trim_start/trim_end are applied where the decoder does not already do it. MP3 (LAME/Xing delay) and Vorbis trim in the decoder; AAC does not.
  • Symphonia's MP4 demuxer parses elst but does not apply it ("Since edits are not currently supported", symphonia-format-isomp4). mp4.rs therefore taps the bytes the demuxer already reads, with no extra HTTP request, and derives delay and valid length from iTunSMPB or the first non-empty edit.

Resampling. rubato 5.0.1 asynchronous sinc resampler (128 taps, no FFT dependency; rubato README and Async source). Edges are extended rather than zero-padded, the filter delay is discarded, and the output length is exactly round(n × ratio).

5.4 Flow control and buffering (src/audio/mod.rs)

Decoders keep 2 s of PCM ahead plus the crossfade tail. A remote successor of a remote current track is not opened until the current track is well buffered or close to its end, so the successor never competes with the audible stream for bandwidth. Local successors start at once.

Resume gates. A fresh remote load or seek stays corked until 500 ms is decoded (the Start gate), above the 300 ms prebuffer. When nothing is pushable and the output is starved, the stream corks (the Stall gate) and resumes with 5 s of playable audio, at the decoded end, or after 15 s of unpaused waiting with ≥ 500 ms buffered. A slow link therefore gives a few long pauses instead of repeated 300 ms stutters. Local streams are never gated. The engine reports starved when play is intended and a Stall gate is set or a Start gate has lasted over 1 s; this drives the download yield (§6.1). If the output starves during a crossfade wait, that boundary's fade is dropped.

Crossfade. Equal-power, 0–12 s, off by default. It is suppressed between tracks of the same album and never exceeds a short, fully decoded successor.

Position. pa_stream_get_time gives the server read index minus sink latency, interpolated with INTERPOLATE_TIMING + AUTO_TIMING_UPDATE. The reported position never exceeds submitted audio, small backward jitter is clamped, and a backward jump of at least 1 s rebases it.

5.5 PulseAudio output (src/audio/pulse.rs, output.rs)

Each engine has one libpulse context on a non-threaded pa_mainloop, dispatched by the actor without blocking, so all callbacks run on the actor thread. Each dispatch iterates until no event source fires: on a socket-only transport (no shm/srbchannel), libpulse's pstream.c reads one packet per iteration (libpulse 16.1 do_pstream_read_write).

Each load or seek creates a float32 stereo 48 kHz playback stream, started corked.

  • Buffer attributes: tlength = 300 ms, minreq = 20 ms, prebuf = -1 (the server default, capped at tlength − minreq + one frame; PulseAudio protocol-native.c fix_playback_buffer_attr), maxlength = server maximum.
  • ADJUST_LATENCY is not set, so tlength is the stream's own buffer rather than total latency including the sink (PulseAudio 17.0 pulse/stream.h, def.h).
  • The actor writes while pa_stream_writable_size() > 0, rather than trusting a client-side estimate that drifts on Bluetooth and after a sink move.

Stream properties: media.role = x-maemo when /etc/os-release has ID=sailfishos, otherwise music; media.name and application.name = PlexFreq; application.id = harbour-plexfreq.

On Sailfish, mainvolume and stream-restore recognize x-maemo (/etc/pulse/mainvolume-listening-time-notifier.conf role-list = x-maemo; pulseaudio-modules-nemo module-meego-mainvolume.c). The user-session policy then owns volume keys and routing. The app writes no policy.

Pause, a recording hold, the gates and a stuck output cork the stream; load, seek and stop disconnect it, discarding queued audio. A policy request-cork event clears play intent; request-uncork is ignored, because it is not permission to undo a user or disconnect pause. A stream failure (daemon restart) reports "Audio output is unavailable", and the next load reconnects. Volume is Rust DSP gain, not a stream volume.

Stuck output. PulseAudio's module-suspend-on-idle suspends a sink with no uncorked input and resumes it when one appears (PulseAudio 16 src/modules/module-suspend-on-idle.c); libpulse reports the connected sink's suspension through pa_stream_is_suspended, updated from the create reply and PLAYBACK_STREAM_SUSPENDED/MOVED (pulse/stream.c). A sink that stays suspended under an uncorked input has stopped taking audio for another suspend cause the app cannot clear: an A2DP sink that failed to resume while its BlueZ transport stays active, a user or pasuspender suspend, or a lost session.

The engine counts a window while play is intended, no recording hold, resume gate or held-failure drain owns the stream, the stream is uncorked, its sink is suspended, and the Bluetooth route is not idle. A BlueZ MediaTransport1 that is idle while none is active is treated as an expected suspension, whether the remote end or the local sink released it (§8.2); a resume that fails back to an idle transport is therefore not detected. The window restarts whenever any condition fails or the position advances by 100 ms. After 10 s the engine looks up its sink input; a session policy may cork it on the server without a request-cork event, and that is the policy's pause, so the window restarts. Otherwise the engine clears play intent and corks the stream, keeping the track, decoders and queued audio, and the runtime shows "Audio output stopped responding; reconnect the audio device, then press Play". It does not retry, recreate the stream or move it; Play uncorks again and starts a new window. These facts are PulseAudio's; PipeWire's pulse server has not been verified to report them the same way.

5.6 DSP (src/audio/dsp.rs)

  • 10-band peaking EQ at Q = 1, ±12 dB per band.
  • Normalization from the Part stream gain/albumGain: Track; Album (falling back to track gain); Auto (album gain for identified single-album queues and album radio, track gain otherwise).
  • Optional headroom of 0–12 dB, then volume gain. Float peaks above full scale are preserved and non-finite samples are sanitized.

Invalid configurations are rejected with "Audio settings exceed the supported range".

6. Caching and offline

6.1 Audio cache (src/cache.rs)

The cache lives in <state-dir>/audio-cache (directory 0700, files 0600, one process-exclusive writer). The default budget is 512 MiB with 5 tracks of look-ahead. Entries are namespaced by the backend's namespace (§3: Plex SHA-256(server URL ‖ token), Jellyfin SHA-256 of jellyfin, the server id and the user id), so different servers or accounts never share them, and keyed by ratingKey, Part path and quality, so original and transcoded media never share a key. The index stores no token or authenticated URL.

Each download batch is the queue's actual upcoming order plus explicit downloads; a new schedule replaces it. Validators, ranges and Content-Range follow the same rules as streaming, and responses must be identity-encoded audio. The advertised part size is only a hint (PMS Part.size): the served byte count can differ, so the received size is what is committed. Completion is an atomic rename plus index commit, and partial files are never handed to a decoder.

A transcoded partial restarts rather than byte-resumes. Originals that cannot be decoded locally are downloaded as 320 kbps MP3 transcodes when the download quality is "original".

Eviction and housekeeping:

  • LRU eviction protects the scheduled batch (normally the current track and the look-ahead; automatic originals are not scheduled under a streaming cap, see "Mobile cap") and permanent pins.
  • The quota includes partial files and excludes symlink targets.
  • Downloads of unknown size reserve space in windows of at least 4 MiB.
  • A malformed index is quarantined to a backup. Unindexed media is preserved for 7 days for re-indexing.

A batch makes up to 4 passes, waiting 30 s after a pass that left transient failures (interrupted, incomplete, network, 5xx). Cancellation and holds are not failures.

Cache diagnostics. With diagnostics enabled the worker logs cache batch start (epoch, items, quality_kbps), cache item done (key, bytes, ms, resumed; only for real downloads), cache item failed (key, class, retryable, pass), cache item skipped (key, class=cooldown) and cache batch end (epoch, completed, cached, failed, skipped, pass, reason). Items that already had a complete copy are only counted (cached). The reason is done (no retryable failure remains; non-retryable failures can still be counted in failed), superseded, gate_closed or retries_exhausted. ms measures the final transfer, not hold waits. Failure classes derive from the failure variant, never from message text: interrupted, incomplete, restart, http_<status>, network, cache_full, too_large, io, other. Core logs cache schedule (item count, manual count, quality, first key, cellular cap) or cache schedule skipped reason= (disabled, cache_suspended, offline_mode, downloads_paused, waiting_wifi, cellular_cap, empty_window) only when the outcome differs from the previous one, and cache schedule rejected when the cache refuses the request. No URL, path, token or error text is logged.

Refusal cooldown. Refusals that would only repeat on retry (HTTP 4xx except 401, 404, 408 and 429; non-audio or content-encoded responses) are remembered for 30 min per item and quality. Later batches skip them and show the stored error. The cooldown is cleared by any explicit download command, by changing the cache settings, and by clearing the cache. Local errors (disk, capacity) never cool down.

Gate and hold. Downloads wait while the Wi-Fi-only policy meets a non-Wi-Fi network, while the user has paused them, in explicit offline mode, and during the yield hold.

The yield hold is set while the engine reports starved (§5.4). It is released after 10 s of healthy playing, at once when nothing plays, and at exit. It never cancels downloads or resets progress:

  • An original with a validator and known size drops its connection at once and resumes by range after release, spending no attempt.
  • Other downloads finish their current item.
  • Every item waits for release before it starts.

The Downloads pages show "Downloads wait while the stream catches up" while held with work pending.

Mobile cap. Automatic cache-ahead of originals is skipped while a streaming cap applies and download quality is original. Explicit downloads follow their own policy.

6.2 Download plans and groups (src/daily.rs)

Pinned groups are albums, playlists, single tracks, server stations (Plex), and artist, album and track radio plans. Each keeps its membership and track plans in the session. Plan refresh runs transactionally on its own thread, never replaces the playback queue, and honours the network gates. Automatic refresh attempts for a group are at least 900 s apart, in addition to the configured refresh interval (fixed throttling, not exponential backoff).

Permanent pins are protected independently of the scheduled batch. Overlapping groups keep shared downloads when one group is removed. On restart, protection is rebuilt and retained plans are scheduled again.

6.3 Offline metadata and browsing (src/offline.rs)

Raw responses are stored as private snapshots scoped to the credential, up to 64 MiB including saved lyrics. When over the limit, files with the oldest modification time are pruned first; reading a snapshot refreshes its time at most once an hour, so pruning approximates least recent use.

On network or 5xx failures, saved pages may be used and the reply is flagged offline; a search with no saved page searches the offline library instead. Such a fallback never enters explicit offline mode, so the next request tries the server again. Authorization failures never fall back silently. Explicit offline mode bypasses the server and cancels plan refresh, audio downloads and artwork downloads. Offline browsing merges saved metadata with the completed-audio catalogue, 100 items per page, sorted by lowercase title then ratingKey so pages agree on one order. Details use saved pages or known parent-child relationships; unvisited data is never claimed to exist.

When saving snapshots fails, the Downloads pages show "Offline library data could not be saved: …".

6.4 Artwork

Rust references each image as a file:// URL of the private artwork cache when the file is cached, otherwise (online with a token) as a credential-free id image://plexfreq/<first 16 hex of the namespace>/<hex of the server-relative path> after the path has passed URL confinement, otherwise not at all. The namespace prefix keeps the same path on another server or account a distinct image in Qt's cache.

The Rust artwork source holds the credential snapshot. It is updated before every reply, empty while signed out or offline, and cleared on exit, so a retained image provider cannot keep loading with the credential. Requests reject ids that are malformed or belong to another namespace and discard the result if the account changed meanwhile.

One store (src/artwork.rs) serves the image provider and the offline prefetch:

  • Prefetch. Core queues the artwork of returned items while downloads are allowed (one job at a time, yielding to a starving stream like audio downloads) into the offline budget, 128 MiB.
  • Browsing. Images the UI asks for are always saved, in browse/ with their own 64 MiB budget, so browsing never evicts artwork kept for offline use. A prefetch of an image already browsed moves the file instead of downloading it again.
  • Loading. A cached file is read first. Otherwise one download serves every concurrent load of the same image (4 downloads at once): the credential goes in headers (from the StreamPolicy, only to a covered URL), with a 5 s timeout, image/* only, at most 4 MiB, and redirects disabled. A load whose requesters all cancelled before its download started downloads nothing. A follower whose leader ends without an answer starts over.
  • Saving. Pruning and writing are one transaction per cache directory, oldest first. Showing a cached image refreshes its age at most hourly. Clearing the cache drops downloads already running; a new download policy cancels queued prefetch, but not saving what the UI asked for.

MPRIS exports only file: artwork.

The C++ provider is a QQuickAsyncImageProvider, available since Qt 5.6 (Qt 5.6 QQuickAsyncImageProvider docs). Each response starts a Rust request (pf_artwork_request) whose callback, on the Rust runtime thread, copies the bytes and queues finished. Cancelling or deleting the response cancels the request, and Rust guarantees the callback never runs afterwards. Qt decodes on its image reader thread. Sources over 8192 px per side or 16 Mpx are refused, and images are only ever scaled down (1024 px on the longest side by default, never above 2048 px).

7. Network policy

The network observer reports three facts for the default route (online, Wi-Fi, cellular). It re-queries on D-Bus signals and every 15 s, with a 2 s deadline per call.

  • ConnMan. net.connman.Manager.GetServices returns services sorted favourite-first. The first ready/online service is the default route. vpn services are skipped so the carrier link underneath decides. wifi is Type == "wifi" and cellular is Type == "cellular". Sources: ConnMan doc/manager-api.txt and service-api.txt.
  • NetworkManager is the fallback when ConnMan does not answer within 2 s. PrimaryConnectionType is 802-11-wireless for Wi-Fi and gsm/cdma for cellular, and State ≥ 50 means online (NM_STATE_CONNECTED_LOCAL). For NM's own VPNs the primary connection type is that of the underlying link; a VPN-typed primary counts as neither Wi-Fi nor cellular. Source: https://networkmanager.dev/docs/api/latest/gdbus-org.freedesktop.NetworkManager.html and nm-dbus-types.html.
  • Not cellular. Bluetooth tethering and Wi-Fi hotspots count as not cellular.

A failed or late query is unknown, never offline, and the last known facts are kept. On a change, Core updates the download gate, reschedules cache-ahead, cancels refresh and artwork downloads when downloads are no longer allowed, and restarts plan refresh when coming online.

Facts are not persisted, so the Wi-Fi quality choice applies until the first observation after start. A successor prepared before a network change keeps its quality.

8. Platform integration

8.1 MPRIS

org.mpris.MediaPlayer2.plexfreq on the session bus, at /org/mpris/MediaPlayer2, exports Root and Player through zbus. Spec: https://specifications.freedesktop.org/mpris-spec/latest/Player_Interface.html.

PlaybackStatus follows logical intent: Playing while loaded with play intent (including buffering, gated or held failure), Paused when paused, Stopped otherwise. Metadata carries title, album, artist, length and a track id per occurrence; mpris:artUrl is a local file: URL only. Next/Previous keep the paused state, as the spec requires, and Raise brings the window to the front. PropertiesChanged carries only properties whose value actually changed, so pause, volume and queue changes never re-send Metadata. Position is read on demand; user seeks emit Seeked.

AVRCP resync. On Sailfish, BlueZ's mpris-proxy bridges MPRIS to AVRCP. In BlueZ profiles/audio/media.c, every received Metadata ends with mp->position = 0; g_timer_start(mp->timer) plus a track-changed event, even when the track did not change. BlueZ tools/mpris-proxy.c forwards PropertiesChanged and every Player signal verbatim, and runs GetAll only at registration (BlueZ upstream 5.87; Sailfish fork github.com/sailfishos/bluez5). Re-sending Metadata mid-track would therefore reset the car's position to 0:00. So after each Metadata emission PlexFreq sends a Seeked carrying the real position of the track that Metadata named (skipped in the first second). The spec defines Seeked as a position change inconsistent with normal playback, so a scrobbler may see this resync as a seek.

8.2 Bluetooth

The BlueZ observer reads org.bluez.Device1 objects with audio UUIDs (A2DP sink 110b, headset 1108, handsfree 111e) and org.bluez.MediaTransport1 states through org.freedesktop.DBus.ObjectManager (BlueZ doc/org.bluez.Device.rst, org.bluez.MediaTransport.rst).

Playback pauses when a tracked device disconnects or its audio transport disappears while playing. Device1 can stay connected through another profile after the audio profile is gone. An idle transport, a read error or an unknown fact is not a disconnect. Switching between accessories forgets the previous route, and reconnection never resumes playback.

The same observations tell the audio engine whether the route is idle (a transport idle and none active), so a suspended Bluetooth sink is then not reported as a stuck output (§5.5).

8.3 Recording hold

A read-only libpulse subscription watches sources and source-outputs. An uncorked source-output on a non-monitor source is an active recording. Only indexes and flags are read, never samples or stream properties, and a failed query keeps the last state.

While something records, the output freezes and the player shows paused. When the recording ends, only the retained intent resumes: a Pause, Stop or Bluetooth-disconnect pause during the hold cancels the resume, and Play during the hold stays inaudible until release.

Under Sailjail the Audio permission exposes the PulseAudio socket (sailfishos/sailjail-permissions permissions/Audio.permission).

8.4 Diagnostics observers

A periodic heartbeat logs transport state, BlueZ counts and PulseAudio facts from read-only libpulse samples. It never creates streams, starts a daemon or changes routing, and it logs technical fields only, with sink names reduced to a class. pactl is not available inside the Sailjail namespace, which is why this uses libpulse. examples/pulse-diagnostics.rs probes the same code.

8.5 Sailfish specifics

  • Foundation. Qt 5.6, QtQuick 2.6, Silica and libsailfishapp (https://docs.sailfishos.org/Develop/Apps/).
  • QML API limits. Not available on Qt 5.6: Controls 2, new-style Connections, Column.forceLayout, Qt.callLater.
  • Silica quirks. BackgroundItem reparents children into a content item, so bind to explicit ids rather than parent. SectionHeader adds an x margin. SliderBase writes value imperatively while dragging, which breaks bindings. Loader geometry is applied to the loaded item, so IntrinsicLoader sizes from implicitHeight (Qt 5.6 Loader docs).
  • Permissions. The desktop file declares [X-Sailjail] Permissions=Internet;Audio;Bluetooth with OrganizationName=org.plexfreq and ApplicationName=harbour-plexfreq (https://docs.sailfishos.org/Develop/Apps/Application_Permissions/). Sandboxing applies only to a normally installed app launched through Sailjail. Sailjail rejects an Exec that does not match the installed desktop file, so an unpacked binary cannot be tested in the sandbox.
  • Harbour libraries. Harbour validation (mb2 check --suites harbour) rejects libgstreamer-1.0, libgstbase-1.0 and libgstapp-1.0, and accepts libpulse. The allowed NEEDED set is libsailfishapp, libpulse, Qt5 Quick/Gui/Qml/Core, libstdc++, libm, libgcc_s, libc and ld-linux.

Build, toolchain and packaging details are in development.md.

8.6 Error notifications

The Qt adapter translates global command/playback errors and radio-refresh warnings, then passes only their presentation text through pf_runtime_notify. Lyrics and similar-artist errors remain local to those views. A radio warning does not overwrite a more specific in-app error. Rust owns delivery, lifetime, coalescing and throttling in src/runtime/notifications.rs; it sends no request echo, media URL or track metadata to the notification service.

Two slots retain the latest application error and radio warning separately. New text replaces the slot's notification; identical text is ignored for five minutes from admission, using a monotonic clock. Ingress is coalesced per slot. Dismissal clears the replacement ID without resetting the throttle. Recovery and application exit do not close notifications. IDs are not persisted across application launches, so a later launch may create another notification.

Delivery uses the session-bus org.freedesktop.Notifications service with expiration 0, transient=false, suppress-sound=true, normal urgency and no actions. These request silent retention; the system notification service controls actual presentation and persistence. Setup and each Notify call have two-second deadlines, including activation of an installed on-demand desktop service, and runtime teardown cancels the owned task. Replacement IDs belong to the resolved unique service owner and are cleared on owner change. There are no automatic delivery retries. If creation has an unknown outcome, further creation in that slot is suppressed for that owner rather than risking duplicate retained rows. A lost bus connection ends delivery for that runtime; in-app errors remain available. Diagnostics for delivery failure are static and rate-limited. Oversized or credential-shaped text is refused; notification body markup is escaped when supported, otherwise stripped.

Sources: the freedesktop notification protocol defines Notify, replacement IDs, expiration and close signals; Notifications.permission grants service access under Sailjail and is included automatically by Base.permission. Notifications is therefore not an explicit desktop-file permission (Harbour rejects that declaration). Nemo's notification.cpp uses x-nemo-owner for application ownership and does not close a notification when its wrapper is destroyed. PlexFreq uses harbour-plexfreq for that hint.

9. UI adapter

Backend (app/src/backend.*) creates the runtime with the state directory (QStandardPaths::AppDataLocation, or PLEXFREQ_STATE_DIR for isolated tests) and polls it every 100 ms. It exposes the merged reply state, cache status, busy/error flags, playback fields, the browse and queue lists and two list models, notifying only on change. Lyric and similar-artist replies never enter the shared state, and their failures never set the global error.

Reader contract. Qt 5.6 converts the whole value of a QVariantMap or QVariantList property to JavaScript on every QML read, so a scalar read from a map that also holds rows costs as much as the rows. So:

  • state and cache hold scalars and small maps only (the track, queue scalars current/repeat/shuffled, settings, one jobs row per download group). The browse rows and the queue rows never live in them, and the cache key lists and per-key maps (readyKeys, goneKeys, pinnedKeys, pinnedGroups, readyBytes, errors) are removed from cache.
  • The rows live in the two EntryModels, the single source of truth, exposed as items/queueItems (QVariantList, notified by itemsChanged / queueItemsChanged) and the scalars itemCount/queueCount. Only Session.qml reads items/queueItems, into its cached items property and the playlist editor default; delegates, actions and bindings use music.items, itemCount or queueCount. tools/test_qml_readers.py enforces this.
  • Cache keys are QSets behind isReady, isGone, isPinned and isPinnedGroup. Bindings that call them also read cacheRevision (bumped only when a set changes) so they re-evaluate.
  • A reply is applied in this order: itemsChanged/queueItemsChanged, then stateChanged, then completed. A browse append adds to the model once. The completed payload never carries items; it carries itemCount (and queue replies the scalars and queueCount), so handlers do not convert rows. Equal lists and unchanged scalars emit nothing.
  • Silica pages: every page keeps one stable EntryModel fed from view.items (Session's cached array while live, the snapshot taken at freeze afterwards), so a page's list is never rebuilt by a model switch. The conversion happens once per items change on live pages, never per state change.

EntryModel reconciles immutable lists by identity (type, ratingKey, key, playQueueItemID, playlistItemID), so existing rows survive updates.

Session.qml owns routes, history, paging, search debounce, alphabet rail offsets, sign-in polling (Plex PIN, Jellyfin Quick Connect every 2 s) and shared presentation helpers. It reads the status serverKind and capabilities; the sign-in form has a server type choice (Plex, Jellyfin) and, for Jellyfin, a URL with optional base path, user name, password and a Quick Connect button that shows the code. Actions and filters the server lacks are hidden through can(...), and the favourites destination is labelled "Favorites" on Jellyfin and "Favorites · 5 stars" on Plex. Navigation.qml is the shared destination/action catalogue.

Translations (app/src/i18n.cpp). The locale is taken from PLEXFREQ_LANGUAGE, then the environment, then (on Sailfish, when no locale variable is set, for example in an SSH launch) LC_MESSAGES or LANG from /etc/locale.conf (https://man7.org/linux/man-pages/man5/locale.conf.5.html), with codeset and modifier suffixes stripped. The base-language catalogue is installed before the territory one, with English as the fallback. Rust error strings are translated in the Core context, including parameterized forms ("Server returned HTTP %1").

10. Persistence and diagnostics

Session files (src/store.rs)

File Content
session.json Settings and the playback checkpoint, including the client id, the server kind, id and user id and the account/server tokens (Jellyfin: the access token), and the occurrence whose start was reported. Rewritten atomically only when its bytes change.
queue.json Queue and radio. Rewritten only when they change. A queue revision mirrored in session.json ensures a saved position is never applied to another queue.
listens.jsonl, history.jsonl Append-only, with the same caps as in memory. Damaged lines are skipped, and the files are compacted atomically when damaged or too large.

Writes go to a synced 0600 temp file that is renamed into place, then the directory is synced. Stale temp files, which may contain tokens, are removed at startup. A malformed document is saved to a unique 0600 corruption backup before defaults are used. The read-only inspect mode never writes, migrates or compacts.

Logs (src/diagnostics.rs)

On Sailfish, PlexFreq keeps a persistent log unless PLEXFREQ_STATE_DIR is set. The log directory is ~/Documents/PlexFreq if it can be created, otherwise <AppDataLocation>/logs. There is one file per local date (plexfreq-YYYY-MM-DD.log), each at most 8 MiB with one backup, and 7 dates are kept. On the desktop, output goes to the terminal.

GUI stall log. Runtime::poll records the time of each poll. A watchdog thread owned by the Runtime (not the worker and not the shared tokio runtime, so a busy or blocked worker cannot hide a stall) checks once a second and, when the gap since the last poll exceeds 2 s, logs once per stall gui poll stalled ms=<n> worker_op=<op|idle>, naming the request the worker is running (set where core request begin is logged). Nothing is logged before the first poll. When polling resumes, poll logs gui poll resumed gap_ms=<n>. Only timings and fixed operation names are logged.

Redaction removes full URLs and the rest of any line carrying a token-like value. It is best effort: framework output may still carry media URLs, so log files are not treated as redacted and should be checked before sharing.

11. Security and credential handling

  • Where tokens live. Rust owns credential persistence and use; tokens (the Plex tokens, the Jellyfin access token) are stored only in the 0600 session files. Published models and replies omit credentials: stream URLs are stripped from plans, server summaries omit tokens, and artwork uses image://plexfreq ids resolved in Rust. The one exceptions are the manual "connect directly" form and the Jellyfin sign-in form, where QML collects the token or password the user types and the C++ adapter forwards it to Rust in the command (app/qml/pages/SettingsPage.qml, app/qml/desktop/Main.qml, app/src/backend.cpp). A Jellyfin password is used once, in the sign-in request body, and is neither stored nor logged; the forms clear their password field right after submitting. A reply echoes the request back to the adapter without its password and token fields (without_secrets in src/runtime.rs), so neither comes back across the FFI.
  • How tokens travel. In headers (Plex X-Plex-Token, Jellyfin Authorization: MediaBrowser ...), never in a URL, on clients with redirects disabled, to origin-confined paths. The audio reader, transcode stop, downloader and artwork loader attach the credential headers of their StreamPolicy only to a URL with the policy's origin and under its base path (StreamPolicy::headers_for in src/server.rs). Server-advertised keys (hub, filter-choice and station keys) are validated by the backend (MediaServer::advertised_key): they must be server-relative and may not carry the backend's credential parameters (Plex: X-Plex-*).
  • Isolation. Response bodies are size-bounded (§3), and cache, offline snapshots and artwork are namespaced per server scope (§3, §6).
  • Read-only platform access. No root, privileged helper or system-service modification. Platform access is read-only (ConnMan/NM, BlueZ, libpulse introspection) except the app's own playback stream and its MPRIS name.