# scorpiox-scorpioplayer-jellyfin-client — SPEC

Row 55. Jellyfin as one `sprch_handler`, RuntimeType `JELLYFIN`, plus a flat `spjelly_*` P/Invoke face.
Pure C99. Transport: the fleet `scorpiox-http.h` v1 (`SCORPIOX_HTTP_ABI 1`) behind the frozen
`scorpiox_io` v1 face (`scorpiox_io_over_http`), JSON through vendored yyjson 0.10.0.

Sources (all read-only, cited as `file:line`):

| Tag | File |
|---|---|
| `JF` | `Core/Toolkit14/MediaOrg/JellyfinFolderFileAccesssor.cs` (311 lines, reference pack) |
| `JP` | `Folders/JELLYFINPlaylistFolder.cs` (45) |
| `JH` | `Handlers/JELLYFINRuntimeConfigHandler.cs` (142) |
| `H` | `include/sprch.h`, `include/scorpiox-io.h`, `include/spffa.h`, `include/sprch_conformance.h` (verbatim from row 54 / emby row 56) |
| `T` | `include/scorpiox-http.h`, `include/scorpiox-http-util.h`, vendored transport sources (verbatim from `scorpiox-http-transport-libcurl-winhttp-fake-backends` `3ec6ea3`: B2c — an engine Authorization line passes through when the engine passed no credentials) |
| `W` | `src/spemby_wire.c` vendored from row 56 emby-client `e6aec8f` (dialect-free Jellyfin/Emby subset) |

Measured against servers run on 127.0.0.1 only: **`demo.jellyfin.org/stable`** (Jellyfin 12.1.0,
2026-09-29) and a local Jellyfin 12.1.0 container on 127.0.0.1 with the emby-row 14-file tree.
The emby row 56 oracle measured the same server images (E48/E410/JF12); rows X1-X26 there are the
Jellyfin delta that section 3 records. Section 3 is this task's measurement.

---

## 1. What the legacy app does

`JH:15-26` reads `FullUrl`, `APIKey`, `UserName`, `Password` and builds `JELLYFINPlaylistFolder`
(`JP:13-17`), which builds `new JellyfinFolderFileAccesssor(url, username, password, key)`.
Streaming (`JH:28-40`) builds the same accessor with `ItemIds = key.AsArrayEX()` and takes the first
file. `ConnectJELLYFINConnection` calls `TestJellyfinEmbyAsync(context, c, 8096, "JELLYFIN")`
(`JH:32-36`): base URL from `ServerUrl`/`ServerPort`/`UseHttps` (`JH:73-97`), then
`IsServerValidAsync` (`JH:100-110`) = the accessor's first folder or file listing, and on success
writes `FullUrl`, `RuntimeType`, and `ID` when empty (`JH:113-117`). `DownloadAsync` returns null
(`JH:28-30`).

The wire behaviour is all in `JF`:

| Step | Request (legacy) | Cite |
|---|---|---|
| auth, only when `APIKey` is empty | `POST {FullUrl}/Users/AuthenticateByName`, JSON `{"Username":u,"Pw":p}`, header `authorization: MediaBrowser Client="com.scorpioxinc.scorpioplayer", Device="NativeClient", DeviceId="XXXXXX", Version="1.0"`; token = `AccessToken` | `JF:278-296` |
| root listing | `GET {FullUrl}/Items`, header `X-Emby-Token: <token or APIKey>` | `JF:210`, `JF:234-256` |
| folder listing | `GET {FullUrl}/Items?parentId=<Id>` | `JF:240-243` |
| stream lookup | `GET {FullUrl}/Items?ids=<key>` | `JF:250-253`, `JH:35-38` |
| stream check | `GET {FullUrl}/Items/<Id>/PlaybackInfo?parentId=<Id>` (content unused, only "not empty") | `JF:80-90` |
| stream URL | `{FullUrl}/videos/<Id>/stream?static=true&api_key=<token>`; `TestUrlSizeAsync` then the same URL again with `TestUrlAsync` | `JF:91-107` |

Per item (`JF:259-266`): `Id`, `IsFolder`, `Name`; files keep every string/integer property as
`Metadata`; `MediaTitle = Name`, `MediaYear = ProductionYear`, `MediaFileSize = Size` (`JF:23-35`).

## 2. Scope

| sprch op | C | Legacy |
|---|---|---|
| `validate` | `GET /System/Info/Public`, then the credential check; fills `FullUrl`, and `ID` when empty; reports `ServerName`/`Version` | `ConnectJELLYFINConnection` = `TestJellyfinEmbyAsync` (`JH:33-36`, measured at `JH:65-125`) |
| `list` | root = the user's views, one folder = paged `/Items`, #26 item JSON | `CreateRootFolder` + `GetPlaylistSubFoldersAsync` / `GetFilesAsync` |
| `stream_url` | `{"url","headers","size",...}` for one file | `CreatePlaybackStreamAsync` |
| `download` | `SPRCH_E_NOTSUPPORTED` (caps do not declare it) | `DownloadAsync` returns null (`JH:28-30`) |

Caps: `SPRCH_CAP_VALIDATE | SPRCH_CAP_LIST | SPRCH_CAP_STREAM | SPRCH_CAP_META` (0x33). No writes.

### D1 Transport (the headers decision)

`scorpiox_io` v1 has no request-header callback, and Jellyfin 12 **requires** headers (`X3`, `X5`
below: `api_key`/`X-Emby-Token` in the query is 401, the legacy query identity is 400). Decision:
**vendor the fleet transport** `scorpiox-http.h` v1 and its backends (libcurl / WinHTTP / fake)
from `scorpiox-http-transport-libcurl-winhttp-fake-backends` `3ec6ea3` (B2c), and take the transport
from the `scorpiox_io` the shell installs with `spjelly_set_io()`:

```c
int spjelly_set_io(const scorpiox_io *io) {
    const scorpiox_http *http = scorpiox_http_of(io);   /* magic-tagged ctx */
    if (!http) return SPRCH_E_NOTSUPPORTED;             /* a foreign io: never fall back to our own */
    ...
}
```

A bare `scorpiox_io` (curl/fake built into this engine, or any backend without the magic ctx)
answers `SPRCH_E_NOTSUPPORTED` with a message naming the requirement, so a shell that hands the
engine a v1-only io fails loudly instead of silently losing headers. `spjelly_use_curl()` installs
the vendored libcurl backend directly (desktop convenience); `spjelly_use_fake()` the offline fake.
On Windows the DLL links `-lwinhttp` and never libcurl (`SPJELLY_NO_CURL` build).

## 3. Jellyfin 12 vs Emby 4.8/4.10: measured differences (this task's X-series)

Every row measured 2026-09-29 with curl against `demo.jellyfin.org/stable` (12.1.0) and the local
loopback Jellyfin 12.1.0 on 127.0.0.1:18098. The legacy consequences are the emby-row X-series
(`emby-client` SPEC section 3) re-measured here for the Jellyfin dialect.

| # | Aspect | JF12 measured | Engine consequence |
|---|---|---|---|
| X1 | auth header | `Authorization: MediaBrowser Client=…, Device=…, DeviceId=…, Version=…` required; `api_key`/`X-Emby-Token` in the **query**: 401 `Invalid token` | D3: headers only |
| X2 | `X-Emby-Authorization` header | 400 (it is an Emby-only alias) | D3: never sent |
| X3 | token on API calls | `Authorization: MediaBrowser Token=<tok>` header, or `ApiKey` query — `X-Emby-Token` header: **401**; `api_key` query: **401** | D4: `Authorization: MediaBrowser Token=` on every call; the stream URL keeps `api_key=` for player compatibility (D9) |
| X4 | auth body | JSON only (form: 415) | JSON |
| X5 | item ids | 32 hex | accept decimal, 32 hex, dashed GUID (D8) |
| X6 | unknown numeric `parentId` | **400** | `E_NOTFOUND` (existence check first) |
| X7 | non-numeric `parentId` | **400** | refused locally, `E_NOTFOUND`, no request |
| X8 | `parentId` of a file | 200 with the user's views (children carry a synthetic display ParentId, so a ParentId comparison cannot detect it); an unknown id answers 400 | D7: the folder is verified with `/Users/{uid}/Items/{id}` **before** the listing (a file answers "is a file, not a folder"), and a 400 is mapped to `E_NOTFOUND` |
| X9 | `PlaybackInfo` | GET and POST both 200 | GET; POST `{}` on 404/405 (D9) |
| X10 | `/Items?Ids=<view>&UserId=` | **empty** (`TotalRecordCount 0`) | `/Users/{uid}/Items/{id}` for the existence check (D8) |
| X11 | one-video movie folder | collapses into a single `Movie` item (no child file item) | item model is unchanged: the Movie IS the file; `stream_url` on it works |
| X12 | default order | sort name | `SortBy=SortName&SortOrder=Ascending` (D10) |
| X13 | default fields | `Name, ServerId, Id, RunTimeTicks, IsFolder, Type, ImageTags, BackdropImageTags, MediaType, UserData, LocationType, ImageBlurHashes, ChannelId` — no `Size` (only in `MediaSources`) | `Fields=ParentId,ProductionYear,Size,ProviderIds,Container` asked for (D10); size from `Size` or `MediaSources[0].Size` |
| X14 | same `DeviceId` logs in twice | **first token revoked (401)** | D3: per-install `DeviceId` from a settings key, not `XXXXXX` (L11) |
| X15 | `GET /System/Info/Public` | 200, `Version 12.1.0`, `ProductName Jellyfin Server` | `validate` step 2 |
| X16 | `GET /Users/Public` | 200 (user list) | not used (the legacy never lists users) |
| X17 | static stream auth | none required for `static=true` | URL carries `api_key` (legacy form) plus `headers.Authorization` |
| X18 | `/UserViews` under a user token | the user's views (`CollectionFolder`s, + `Playlists` when playlists exist) | root listing (D5) |
| X19 | `DateModified` | not returned | `mtime_ms` = -1 |
| X20 | stream ranged GET | 206 with the exact bytes | the ranged probe in tests only |
| X21 | wizard user | first boot auto-creates `root` with no password | oracle setup: login with empty `Pw`, then set a password |
| X22 | `X-Emby-Token` on the login request | 400 (the login takes identity only) | D3 |

## 4. Decisions

- **D2 Base URL.** `FullUrl` as given, else `HostName` + `ServerPort` (default 8096) + `UseHttps`
  (`JH:73-92`); a `FullUrl`/`ServerUrl` that parses as an absolute URI keeps only scheme://host, then
  `:port` is appended (the legacy `Uri.TryCreate` branch, `JH:82-84`). No `/emby` fallback (X1: 404).
- **D3 Identity and auth headers.** `Authorization: MediaBrowser Client="com.scorpioxinc.scorpioplayer",
  Device="NativeClient", DeviceId="<per-install>", Version="1.0"` on every request; the login adds no
  token header (X22); authenticated calls add `Authorization: MediaBrowser Token="<token>"` (X3).
  `DeviceId`: settings key `DeviceId`; when absent the engine derives one stable per-process id
  (`spjelly-<8 hex from the machine>`), never `XXXXXX` (L11/X14).
- **D4 Token.** `AccessToken` from the login body; `APIKey` (a PAT) replaces it when set (`JF:280`).
  Token cache: 16 entries keyed by (base, user, password) as emby row 56. A 401 on a cached token
  drops it and re-logs in once — on Jellyfin that also *revokes* the older install's token (X14), so
  the cache is per-DeviceId too.
- **D5 Root listing.** `GET /UserViews` (the user's views, X18); no `UserId` parameter (the token
  decides). Items are `CollectionFolder`s; `Playlists` appears when the server has any. The legacy
  root listing (`GET /Items` with no parentId) answers the same views under a user token, but it is
  the endpoint that dies on API keys and 4xx elsewhere, so the engine asks `/UserViews`.
- **D6 Folder listing.** `GET /Items?ParentId=<id>&Fields=ParentId,ProductionYear,Size,ProviderIds,Container
  &SortBy=SortName&SortOrder=Ascending&StartIndex=<n>&Limit=500`. One listing per folder (the legacy
  fetches twice, `JF:193-229`). Pages until `StartIndex >= TotalRecordCount` or a short page; duplicate
  ids across pages are dropped.
- **D7 Folder ids.** `folder_id` must be decimal (1-20 digits), 32 hex, or a dashed GUID; anything
  else is `E_NOTFOUND` without a request (X7). An unknown or file `parentId` answers 400 (X6/X8):
  the engine checks existence first with `GET /Users/{uid}/Items/{id}` (X10: `Items?Ids=` is empty
  under a user scope) and answers `E_NOTFOUND` instead of listing the root again (the legacy bug L4).
- **D8 Stream.** `entry_json` id from `"id"`, `"path"`, `"Key"`/`"key"`, `"backend_id"`; the first
  valid one wins. `GET /Users/{uid}/Items/{id}` (or `Items?Ids=` for an API key) first: absent or a
  folder => `E_NOTFOUND`. Then `GET /Items/<id>/PlaybackInfo` (GET; POST `{}` on 404/405, X9). No
  `MediaSources` => `E_NOTSUPPORTED`. URL = `<base>/videos/<id>/stream?static=true&api_key=<token>`
  (the legacy form, `JF:91-107`, kept because players need a bare URL) **plus**
  `headers.Authorization: MediaBrowser Token=<token>` in the output JSON. Size = `MediaSources[0].Size`
  (X13); the ranged probe (206) is a test assertion, not a runtime request.
- **D9 validate.** 1) base from D2; 2) `GET /System/Info/Public`; 3) `APIKey` =>
  `GET /System/Info` with the token header (200 or `E_AUTH`), else `AuthenticateByName` (X1). Output:
  `{"FullUrl":<base>}` plus `"ID":<server Id>` when the input `ID` is empty/absent, and
  `"ServerName"`/`"ServerVersion"` informational keys (the registry merges them; they are not
  RuntimeSettings keys the legacy wrote, they are conveniences). No token is written into settings.
- **D10 Errors and secrets.** As emby D13: messages never contain `Password`, `APIKey` or a token;
  URLs are redacted (`api_key=***`, `Token=***`, userinfo dropped); server bodies cut to their first
  printable line (160 bytes) and scrubbed. Error out-buffer: `{"error":"..."}`.
- **D11 Output.** List: `{"items":[...]}`. Too small a buffer => `SPRCH_E_BUFFER` and nothing past
  `cap`. The item writer is the vendored `spemby_wire.c` (#26 shape, section 5).

## 5. Item JSON (#26 shape)

```json
{"name":"Big Buck Bunny","path":"0c19a6f54d50d8bbbba00f8f4325de45","folder":false,"kind":"file","size":51709,
 "mtime_ms":-1,"id":"0c19a6f54d50d8bbbba00f8f4325de45","parent_id":"f137a2dd21bbc1b99aa5c0f6bf02a805",
 "title":"Big Buck Bunny","year":2008,"type":"Movie","media_type":"Video","container":"mkv",
 "imdb":"tt1254207","tmdb":"10378","available":true}
```

`path` = `id` = the Jellyfin item id. `size` -1 when unknown (always for folders). `year` /
`container` / `imdb` / `tmdb` / `parent_id` are `null` when absent. `available` = title and year both
present (legacy `Available`, `JF:26`).

## 6. State machine

```
settings --parse--> CONFIG_OK --(APIKey)--------------------------> TOKEN(key, user=none)
                        |--(UserName)--> cache hit? --yes--------> TOKEN(cached, user=id)
                        |                   no --> POST AuthenticateByName (headers) --200--> TOKEN (cached)
                        |                                           --401/403--> E_AUTH
TOKEN --> GET page --200 JSON--> accumulate --more?--> GET page
                    --401 (cached token, first time)--> forget, re-auth, retry once
                    --401/403--> E_AUTH   --429--> E_RATE   --5xx / transport--> E_NETWORK
                    --400/404 (folder)--> existence check --> E_NOTFOUND
                    --other 4xx--> E_PROTOCOL   --bad JSON--> E_PROTOCOL
done --> item JSON --> fits? --no--> E_BUFFER
```

## 7. Limits

| Limit | Value |
|---|---|
| page size (`Limit`) | 500 |
| items per folder | 100,000 (then `E_PROTOCOL`) |
| pages per folder | 1,000 |
| one response body | 32 MiB (the collector max); past it `E_PROTOCOL` |
| URL | 8 KiB |
| name | 1,024 bytes |
| token cache | 16 entries |
| settings JSON | 1 MiB |

## 8. Legacy defects found (L-series)

| # | Defect | Cite | Engine |
|---|---|---|---|
| L1 | a non-2xx answer (401, bad password, dead server behind a proxy) lists as an empty folder; a refused connection throws | `JF:255-275` | `E_AUTH` / `E_NETWORK`, never an empty list |
| L2 | **dead on Jellyfin 12**: `X-Emby-Token` is rejected (X3), every `/Items` is 401, the tree is empty. The legacy JELLYFIN handler is unusable on the target it names | `JF:210` | the C engine is the fix: header auth (D3/D4) |
| L3 | one hard-coded `DeviceId="XXXXXX"` for every install: on Jellyfin each login **revokes every other install's token** (X14) | `JF:151` | per-install DeviceId (D3) |
| L4 | a vanished folder lists the root again on Emby; on Jellyfin it 400s, so the recursive walker stops with an exception instead | `JF:240-243` | `E_NOTFOUND` (D7) |
| L5 | `stream` on a missing id throws `ArgumentNullException` (`FirstOrDefault` on null) | `JH:39` | `E_NOTFOUND` |
| L6 | `PlaybackInfo?parentId=<id>`: not a parameter; its answer is only tested for non-empty | `JF:82-90` | dropped (D8) |
| L7 | the stream URL is probed twice, the second probe identical to the first | `JF:91-107` | one size from PlaybackInfo |
| L8 | each folder is fetched twice (files pass + folders pass) | `JF:193-229` | once |
| L9 | no paging, no sort: one unbounded response per folder | `JF:238` | D6 |
| L10 | `MediaYear`/`MediaFileSize` empty without `Fields=` (X13): `Available` always false, size 0 | `JF:23-35` | `Fields=` (D6) |
| L11 | `X-Emby-Token` header name in `AccessTokenHeader` (`JF:186`) — the token IS the value of that header on Emby; on Jellyfin the header name is wrong AND the header itself is rejected | `JF:186` | `Authorization: MediaBrowser Token=` (D4) |
| L12 | an Emby name containing `/` would be a path separator downstream | `JF:201` | the vendored writer replaces `/` with U+2215 |

## 9. Reconstructed or assumed

- `TestJellyfinEmbyAsync` **is** shipped (`JH:65-125`): D2/D9 follow it; only the HTTP helpers it calls
  were not shipped. `tools/csharp-legacy/Shim.cs` assumes (as emby row 56): non-2xx => null (not an
  exception), transport failure => exception, `TestUrlSizeAsync` = HEAD + Content-Length, `AsArrayEX` =
  split on `,`/`;`.
- The legacy writes `ID = Guid.NewGuid()` (`JH:117`); the engine writes the **server** id instead
  (like emby D12) so two installs of the same server share an identity. Recorded as a deliberate
  divergence (section 10).

## 10. Deliberate divergences from the reference implementation

| # | Legacy | Engine | Why |
|---|---|---|---|
| V1 | query `api_key=`/`X-Emby-Token` header | `Authorization: MediaBrowser Token=` | Jellyfin 12 rejects both legacy forms (X3). The legacy is dead here (L2) |
| V2 | `DeviceId="XXXXXX"` | per-install id | X14: one shared id revokes other installs' tokens |
| V3 | no `Fields`, no paging | `Fields=` + `Limit=500` pages | X13/L10: without it `Size`/`ProductionYear` are absent |
| V4 | root = `GET /Items` | `GET /UserViews` | the same views under a user token, and the endpoint that works for both credential kinds |
| V5 | `ID = Guid.NewGuid()` | the server id | two installs of one server share an identity |
| V6 | `PlaybackInfo?parentId=` | `GET /Items/{id}/PlaybackInfo` | L6 |
| V7 | stream URL carries only `api_key=` | + `headers.Authorization` | players need the bare URL; app callers get the header too |

## 11. What was vendored, at which commit

| File | From | Commit |
|---|---|---|
| `include/scorpiox-http.h`, `include/scorpiox-http-util.h`, `include/scorpiox-http-exports.h`, `include/scorpiox-io.h` | fleet transport | `3ec6ea3` (B2c) |
| `src/scorpiox_http_util.c`, `src/scorpiox_http_fake.c`, `src/scorpiox_http_curl.c`, `src/scorpiox_http_winhttp.c`, `src/scorpiox_io_over_http.c`, `src/md5.c`, `src/md5.h` | fleet transport | `3ec6ea3` (B2c) |
| `include/sprch.h`, `include/sprch_conformance.h`, `include/spffa.h`, `src/sprch_conformance.c` | row 54 via emby row 56 | `e6aec8f` |
| `src/spemby_wire.c` (as the dialect-free wire subset) | emby row 56 | `e6aec8f` |
| `vendor/yyjson/*` | emby row 56 (yyjson 0.10.0) | `e6aec8f` |
