# scorpiox-scorpioplayer-emby-client — SPEC

Row 56. Emby as one `sprch_handler`, RuntimeType `EMBY`, plus a flat `spemby_*` P/Invoke face.
Pure C99, `scorpiox_io` v1 is the only transport, JSON through vendored yyjson 0.10.0.

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

| Tag | File |
|---|---|
| `JF` | `reference/scorpiox-scorpioplayer-emby-client/csharp-reference/MediaOrg/JellyfinFolderFileAccesssor.cs` (311 lines) |
| `EH` | `reference/scorpiox-scorpioplayer-emby-client/csharp-reference/Handlers/EMBYRuntimeConfigHandler.cs` (53 lines) |
| `EP` | `reference/scorpiox-scorpioplayer-emby-client/csharp-reference/Folders/EMBYPlaylistFolder.cs` (67 lines) |
| `H` | `include/sprch.h`, `include/scorpiox-io.h`, `include/spffa.h`, `include/sprch_conformance.h` (verbatim) |

Measured against servers run on 127.0.0.1 only: `emby/embyserver:4.8.11.0` (the target), `emby/embyserver:latest`
(reports `4.10.0.40`) and, for the Jellyfin side of the table, `jellyfin/jellyfin:latest` (reports `12.1.0`).
Every server has the same 14-file tree (`tools/oracle/gen_media.sh`). Section 3 is that measurement.

---

## 1. What the legacy app does

The legacy app has no Emby client. `EH:13-22` reads `FullUrl`, `APIKey`, `UserName`, `Password` and builds
`EMBYPlaylistFolder` (`EP:13-17`), which builds `new JellyfinFolderFileAccesssor(url, username, password, key)`
and labels it `ContentSource.Emby` (`EP:22`). Streaming (`EH:28-40`) builds the same accessor with
`ItemIds = key.AsArrayEX()` and takes the first file. `TestEMBYConnection` calls
`JELLYFINRuntimeConfigHandler.TestJellyfinEmbyAsync(context, c, 8096, "EMBY")` (`EH:45-51`), which was **not
shipped** in `reference/`. `DownloadAsync` returns null (`EH:23-26`).

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:149-155`, `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`, `EH:37-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`, `JF:198-203`): `Id`, `IsFolder` (`"True"` -> folder), `Name`; files keep every string
or integer property as `Metadata`; `MediaTitle = Name`, `MediaYear = ProductionYear`, `MediaFileSize = Size`
(`JF:23-35`). Files and folders are two passes over two identical `GET`s (`JF:193-229`).

## 2. Scope

| sprch op | C | Legacy |
|---|---|---|
| `validate` | `GET /System/Info/Public` (+ `/emby` fallback), then the credential check; fills `FullUrl`, and `ID` when empty | `TestEMBYConnection` (not shipped, D12) |
| `list` | one folder, all pages, #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 |

Caps: `SPRCH_CAP_VALIDATE | SPRCH_CAP_LIST | SPRCH_CAP_STREAM | SPRCH_CAP_META` (0x33). No writes: nothing in
this engine adds, deletes or modifies a server item (SKILL decision 4). `AuthenticateByName` creates a
session on the server, as the legacy app does; that is the only server-side state it causes.

## 3. Emby vs Jellyfin: measured differences

`E48` = Emby 4.8.11.0, `E410` = Emby 4.10.0.40, `JF12` = Jellyfin 12.1.0. "Legacy" = what the request in
section 1 gets. Every row was measured with curl and, where it touches the legacy path, with the legacy C#
compiled unmodified (`tools/csharp-legacy`). Transcripts: `tools/oracle/results/`.

| # | Aspect | E48 | E410 | JF12 | Engine consequence |
|---|---|---|---|---|---|
| X1 | `/emby` path prefix | optional (both work; also `/mediabrowser`, `/emby/emby`) | optional | **404** | FullUrl used as given; `validate` falls back to `<FullUrl>/emby` on 404 (D6) |
| X2 | `AuthenticateByName` body | `Pw` (plain). `Password` alone: **401**. `Pw`+`Password`: 200 | same | `Pw` | send `Pw` only (D4) |
| X3 | client identity for auth | `authorization: MediaBrowser ...`, `X-Emby-Authorization`, **or query** `X-Emby-Client/Device-Name/Device-Id/Client-Version`; none: 400 `appName` | same | `Authorization` header only; `X-Emby-Authorization`: 400; query: 400 | query identity (D3): works over `scorpiox_io` v1, which has no request headers |
| X4 | auth body encoding | JSON or form | JSON or form | JSON only (form: 415) | JSON |
| X5 | token on API calls | `X-Emby-Token` header, `api_key` / `X-Emby-Token` / `api_Key` query; `ApiKey` query: **401** | same | `Authorization: MediaBrowser Token=` or `ApiKey` query only; `X-Emby-Token` header and `api_key` query: **401** | `api_key` query (D3). **The legacy request is dead on JF12**: every `/Items` is 401 and the legacy tree is empty |
| X6 | static stream auth | `api_key` query or `X-Emby-Token` header required (else 401) | same | **none required** for `static=true` | URL carries `api_key` (legacy form) plus `headers.X-Emby-Token` |
| X7 | `PlaybackInfo` | GET and POST both 200 (`/emby` too) | GET and POST both 200 | GET and POST both 200 | GET; POST `{}` only on 404/405 (D9) |
| X8 | `PlaybackInfo` on a folder / missing id | **500** (cast error / NullReference) | 500 | 404 | `?ids=` lookup first (D9) |
| X9 | `GET /Items` without `UserId`, admin token | the **physical** root folders `movies`, `tv`, `homevideos` (`Type: Folder`, ids 4/6/8) | same | user token: the user's views (`CollectionFolder` + `Playlists`); API key: the physical folders + `Playlists` | legacy tree kept (D7) |
| X10 | same, library-restricted user (Movies only) | **all three physical folders, every file listed and streamable** (legacy walk: 31 of 31 items) | only `Movies` (view, id 3; legacy walk: 14 items) | the user's views | `UserId` sent for password logins (D7) |
| X11 | `UserId` of another user with a non-admin token | answered with **the other user's** views | not measured | not measured | only the id `AuthenticateByName` returned is ever sent |
| X12 | unknown numeric `parentId` | **200 with the root listing** | same | 400 | ParentId check + `?ids=` confirm (D8) |
| X13 | non-numeric `parentId` (`abc`) | **500** "Guid should contain 32 digits" | same | 400 | ids validated locally: `E_NOTFOUND` without a request (D8) |
| X14 | `parentId` of a file | 404 | 404 | 400 | `E_NOTFOUND` |
| X15 | item id shape | decimal (`"20"`) | decimal | 32 hex | accept decimal, 32 hex, dashed GUID (D8) |
| X16 | default fields on `/Items` | `Name, ServerId, Id, RunTimeTicks, IsFolder, Type, ImageTags, BackdropImageTags, MediaType` (no `ProductionYear`, no `Size`) | same | + `UserData`, `LocationType`, `ImageBlurHashes`, `ChannelId` | `Fields=` asked for (D10); legacy `MediaYear` is always null on Emby, so `Available` is always false |
| X17 | `Fields=Size` | top-level `Size` | same | absent (only in `MediaSources`) | size from `Size`; `PlaybackInfo` size in `stream_url` |
| X18 | `DateModified` | not returned | not returned | not returned | `mtime_ms` = -1 |
| X19 | same `DeviceId` logs in twice | both tokens stay valid | both valid | **first token revoked (401)** | Emby: legacy `DeviceId="XXXXXX"` kept. A Jellyfin engine must not share one DeviceId across installs |
| X20 | default `/Items` order | insertion order, differs 4.8 vs 4.10 | differs | sort name | `SortBy=SortName` (D10) |
| X21 | error body | `text/html` or `text/plain` one line ("Access token is invalid or expired.") | `text/plain` | empty 401, RFC 9110 problem JSON on 400 | first printable line, redacted (D13) |
| X22 | `/System/Info/Public` | `Id, ServerName, Version, LocalAddresses, RemoteAddresses` | same | + `ProductName: "Jellyfin Server"`, `StartupWizardCompleted` | `ProductName` containing "Jellyfin" => `E_CONFIG` "use the JELLYFIN handler" (D12) |
| X23 | season folder names | folder `Season 01` -> item `Season 1` | same | `Season 1` | none (names are the server's) |
| X24 | `/Items?Ids=<view id>&UserId=` | the view | **empty** | not measured | user-scoped existence via `/Users/<uid>/Items/<id>` (D8) |
| X25 | `/Users/<restricted uid>/Items/<id>` of an item outside the user's libraries | **200 with its metadata** | not measured | not measured | none: the listing under `UserId` is empty there; metadata only, the engine never lists or streams it |
| X26 | a movie folder holding one video (`movies/Sintel (2010)/Sintel (2010).mp4`) | a `Folder` item `Sintel (2010)` containing a `Movie` item `Sintel` | same | one `Movie` item `Sintel (2010)`, not a folder (tree: 26 items vs Emby's 31) | none (the server's tree); a Jellyfin tree is shallower by one level per movie |

Not reproduced: "older Emby servers take `Password` as SHA1" (task text). 4.8.11.0 ignores `Password`
entirely (X2); no pre-4.x image was run. `Pw` is what every server measured accepts.

## 4. Decisions (deliberate divergences from the reference)

- **D1 One request shape per operation, `scorpiox_io` v1 only.** No request headers exist in v1; everything
  the server needs goes in the query (D3). No `scorpiox-http.h` dependency (the proposal from the WebDAV engine).
- **D2 Settings.** The legacy keys `FullUrl`, `UserName`, `Password`, `APIKey` (`EH:15-18`). `APIKey` wins
  when non-empty, exactly as `JF:280` (no auth request). Neither `APIKey` nor `UserName` => `E_CONFIG` (legacy
  posts `{"Username":null}` and lists nothing). Empty `Password` is allowed (passwordless users).
  `FullUrl` absent: built from `ServerUrl` or `HostName` + `ServerPort` (default 8096, the `EH:49` argument) +
  `UseHttps` (D12, ASSUMED). The base URL is http(s) only, without a query, fragment or userinfo. Its host
  holds only unreserved characters, `%` or UTF-8 (or an IPv6 literal), and its path has no `@` (a mistyped userinfo
  would otherwise ride in every request URL). Optional new key `EmbyTree`: `"legacy"` or `"user"` (D7). Unknown keys are left
  alone: `validate` returns only the keys it changed.
- **D3 Query-string auth.** Auth request: `POST <base>/Users/AuthenticateByName?X-Emby-Client=com.scorpioxinc.scorpioplayer&X-Emby-Device-Name=NativeClient&X-Emby-Device-Id=XXXXXX&X-Emby-Client-Version=1.0`
  with `application/json` body `{"Username":u,"Pw":p}` — the legacy identity (`JF:149-155`) moved from the
  header into the query (X3). API calls: `&api_key=<token>` (X5). Tokens in URLs are what the legacy stream URL
  already does (`JF:93`); every URL that can reach an error message goes through `spemby_redact` (D13).
- **D4 `Pw` only.** X2.
- **D5 Token cache.** Password logins are cached in-process by (base, UserName, Password), 16 entries, under a
  mutex. A 401 on a cached token forgets it, re-authenticates once and retries once. The legacy app
  re-authenticates for every root folder it creates. `spemby_forget_tokens()` clears the cache.
- **D6 `/emby` fallback.** `validate` probes `<FullUrl>/System/Info/Public`; on 404 it probes
  `<FullUrl>/emby/System/Info/Public` and, if that answers, returns `FullUrl = <FullUrl>/emby` (a reverse proxy
  that forwards only `/emby/`). `list` / `stream_url` use `FullUrl` as given, like the legacy app.
- **D7 Tree scope.** API-key configs (no user) and `EmbyTree=legacy`: the legacy request, no `UserId`:
  the physical tree (X9), identical to the legacy walk. Password configs by default (`EmbyTree` absent or
  `"user"`): `UserId=<the id AuthenticateByName returned>` on every `/Items` and `PlaybackInfo`, because E48
  ignores the user's library access without it (X10: a restricted account sees and streams every library).
  With `UserId` the root is the user's views (`Movies`, ids 3/5/7) instead of the physical folders
  (`movies`, ids 4/6/8); every level below the root has the same items and ids (section 8). This is the one
  place the default C tree differs from the legacy tree.
- **D8 Folder ids.** `folder_id` must be decimal (1-20 digits), 32 hex, or a dashed GUID; anything else is
  `E_NOTFOUND` without a request (X13: the server would answer 500). Missing folders: E48 answers an unknown
  numeric `parentId` with the root listing (X12). Every listing asks for `ParentId`; if any item's `ParentId`
  differs from `folder_id`, or the page is empty, an existence check decides: `GET /Users/<uid>/Items/<id>`
  under a user scope (E410 answers `/Items?Ids=<view>&UserId=` with nothing, X24), `GET /Items?Ids=<id>`
  otherwise; no item or a non-folder => `E_NOTFOUND`. (A view's children carry the physical folder's
  `ParentId`, so a mismatch alone is not proof.) The legacy app shows the root again inside a vanished
  folder, which loops a recursive walker.
- **D9 Stream.** `entry_json` id from `"id"`, `"path"`, `"Key"`/`"key"` (the legacy `TheFile.Key`) or
  `"backend_id"`; the first valid one wins. `GET /Items?ids=<id>` first (the legacy lookup, `EH:37-38`): no item
  => `E_NOTFOUND`; a folder => `E_NOTFOUND` (legacy: null). Then `GET /Items/<id>/PlaybackInfo`
  (the legacy `?parentId=<id>` is dropped: it is not a PlaybackInfo parameter); 404/405 => `POST` with `{}`.
  No `MediaSources` => `E_NOTSUPPORTED`. URL = `<base>/videos/<id>/stream?static=true&api_key=<token>`,
  the legacy form. No HEAD probe (v1 has no HEAD); the size is `MediaSources[0].Size`, which equals the
  HEAD `Content-Length` the legacy probe reads (51709 = 51709 measured). The legacy second probe of the same
  URL (`JF:100-107`) is a copy-paste duplicate and is not reproduced.
- **D10 Listing request.** `GET <base>/Items?[UserId=..&][ParentId=..&]Fields=ParentId,ProductionYear,Size,ProviderIds,Container&SortBy=SortName&SortOrder=Ascending&StartIndex=<n>&Limit=500&api_key=..`.
  One listing per folder (the legacy app fetches it twice). Pages until `StartIndex >= TotalRecordCount` or a
  short page; duplicate ids across pages are dropped (a library scan can shift pages).
- **D11 Names.** `name` = the server `Name` (legacy `Title`, `JF:201`), with `/` replaced by U+2215 and C0 /
  DEL bytes replaced by `_` (a #26 name is one path segment). Empty, `.`, `..`, invalid UTF-8 or longer than
  1,024 bytes: the name falls back to the id.
  `title` = the raw `Name`. Files keep the legacy extension-less name (`FileType` is empty for every Emby
  item, `JF:43`); the container is reported separately.
- **D12 `validate` (reconstructed: `TestJellyfinEmbyAsync` not shipped).** 1) base from D2; 2)
  `/System/Info/Public` (+ D6); `ProductName` containing "Jellyfin" => `E_CONFIG` (X5 makes the Emby dialect
  unusable there); 3) `APIKey` => `GET /System/Info?api_key=` (200 or `E_AUTH`), else `AuthenticateByName`.
  Output: `{"FullUrl":<base>}` plus `"ID":<server Id>` when the input `ID` is empty or absent. No token is
  ever written into the settings.
- **D13 Errors and secrets.** Messages never contain `Password`, `APIKey` or a token: URLs are redacted
  (`api_key=***`, `X-Emby-Token=***`, userinfo dropped); server bodies are cut to their first printable line
  (160 bytes) and scrubbed of every secret from the settings. Error out-buffer: `{"error":"..."}`.
- **D14 Output.** List: `{"items":[...]}`. Too small a buffer => `SPRCH_E_BUFFER` and nothing past `cap`.

## 5. Item JSON (#26 shape)

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

`path` = `id` = the Emby item id: pass it back as `folder_id` / in `entry_json`. `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 --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
                    --404 (folder)--> E_NOTFOUND   --other 4xx--> E_PROTOCOL   --bad JSON--> E_PROTOCOL
done --> ParentId check (D8) --> 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 (curl backend) | 32 MiB; past it a synthetic HTTP 413 "response too large" => `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, every `/Items` is 401, the tree is empty (the JELLYFIN handler shares this accessor) | `JF:210` | Emby dialect only; Jellyfin => `E_CONFIG` |
| L3 | a restricted Emby 4.8 user reads every library (no `UserId`) | `JF:238` | D7 |
| L4 | a vanished folder lists the root again on Emby (X12): a recursive walker loops | `JF:240-243` | D8 |
| L5 | `stream` on a missing id throws `ArgumentNullException` (`FirstOrDefault` on null) | `EH:39` | `E_NOTFOUND` |
| L6 | `PlaybackInfo?parentId=<id>`: not a parameter; its answer is only tested for non-empty | `JF:82-90` | dropped (D9) |
| 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, order differs between 4.8 and 4.10 (X20) | `JF:238` | D10 |
| L10 | `MediaYear` / `MediaFileSize` are always empty on Emby (X16): `Available` is always false, size 0 | `JF:23-35` | `Fields=` (D10) |
| L11 | one hard-coded `DeviceId="XXXXXX"` for every install: on Jellyfin each login revokes every other install's token (X19) | `JF:151` | kept for Emby (harmless there, measured); flagged for row 55 |
| L12 | an Emby name containing `/` would be a path separator downstream | `JF:201` | D11 |

## 9. Reconstructed or assumed

- `TestJellyfinEmbyAsync` (`EH:49`) was not shipped: D12 is a reconstruction (default port 8096 from the
  call site; `UseHttps`, `ServerUrl` / `HostName` / `ServerPort` handling ASSUMED from the fleet's other
  handlers).
- The bosxixi HTTP helpers were not shipped. `tools/csharp-legacy/Shim.cs` assumes: non-2xx => null (not an
  exception), transport failure => exception, `TestUrlSizeAsync` = HEAD + Content-Length, `AsArrayEX` = split on
  `,`/`;`. L1 depends on the first assumption.

## 10. What a later jellyfin engine (row 55) could vendor

`src/spemby_wire.c` is dialect-free: the `/Items` page parser, the item model and #26 writer, the
`AuthenticateByName` / `PlaybackInfo` / `System/Info/Public` parsers, the id validator and the status map.
The Emby dialect (query identity, `api_key`, `/emby` fallback, root-listing detection, `UserId` scope) is in
`src/spemby_dialect.c`. Jellyfin 12 needs request headers (X3, X5), so row 55 needs `scorpiox-http.h` or an
equivalent; the Jellyfin-specific facts are rows X5, X6, X19 and X22 above.
