# SPEC — scorpiox-scorpioplayer-media-library-home-rows-model

**Home/library policy for SCORPIO PLAYER 2027.** What goes on the home screen, in what
order, what each tile means, where resume comes from, what plays next. Pure policy over
JSON the shell already fetched from shipped engines (`spcat_`, `spfiles_`, `spfsc_`,
`spmcat_`, `spis_`, `spplfm_`). No sockets, no auth, no engine links. One input contract,
one output contract, every shell (WinUI3, GTK4, SwiftUI, Compose) renders the same rows.

Prefix: **`sphrm_`** (SCORPIO Player Home Rows Model). ABI 1. Frozen error taxonomy.
Strings are library-owned, valid until the next mutating call — copy them.

---

## 1. Scope decision

Tracker rule: *"Shells are native and hold no logic — anything that needs logic becomes a
C engine export."* The home screen is logic: which server sections become rows, in which
order, which ids are movies vs shows, which item is "continue watching", which episode is
next, whether the Play button says *Resume* or *Start*. Three legacy shells each carried
their own copy of that logic (TPlayer UWP, IOSLegacy Uno/Droid, and every 2025 backend
adapter). This repo is the single place it lives.

**In scope**
1. Load/validate the five input blocks (server home JSON, item records, watch state,
   library entries, local store snapshot) — §2.
2. Row building: server sections → rows, plus derived rows (Continue Watching, Recently
   Added, Movies, TV Shows → seasons → episodes, Favourites, Genre, Collections,
   Unmatched) — §3–§5.
3. Ordering rules, per row, with the legacy citation for each — §6.
4. Item detail: sources (playable, ranked), resume decision, next episode, autoplay
   timeline — §7–§9.
5. Stable ids following `spplfm_` v2 rules — §10.
6. `sphrm_result_json()` — the render-ready document every shell consumes — §11.

**Out of scope**
- Transport (the shell calls `spcat_get_homepage` etc. and hands the JSON over).
- Poster/image fetching, layout, focus graph (`sptpl_`), remote keys (`sprc_`).
- Writing anything. This engine is read-only by construction; there is no write export.

## 2. Input contract

`int sphrm_load_inputs(const char *json)` takes one object with five blocks. Every block
is optional; a missing block is *absent*, not empty (the distinction is observable: an
absent watch block means "no resume data anywhere", an empty one means "nothing watched").

| block | shape | produced by |
|---|---|---|
| `server_home` | object — the spimdb homepage exactly as `spcat_home_json()` returns it (`List`, `Continues`, `Level30s`, `Spotlights`, `ExtentList`, `UserInfo`, `Peoples`, `CollectionPlaylists`, `Basics`) | `scorpiox-scorpioplayer-spimdb-catalogue-client` |
| `items` | array of item records (§2.1) | `spfiles_get_by_imdb` (`spfiles_file_json(i)`), `spmcat_result_json()`, `spfsc_item_json(i)`, `spplfm_result_json()` items |
| `watch` | array of watch-state records (§2.2) | `spfiles_get_progress` rows, `spfiles_get_playback_sessions`, `spis` settings/bookmarks, `spcat` Continues |
| `library` | array of library entries (§2.3) | the shell's folder walk (`spfsc_`/`spffa_` listings through `spplfm_`) |
| `store` | object — `{"favourites":[…],"playlists":[…]}` | `scorpiox-scorpioplayer-item-store` (`spis_fav_*`, `spis_playlist_*`) |

Validation (all failures = `SPHRM_ERR_BAD_INPUT`, state cleared):
root not an object · a block present but of the wrong top-level type · an item record
without a usable `id` (§10) · more than 200,000 items · more than 2,000 rows ·
a string field longer than 8,192 bytes is **truncated, not rejected** (the server has
been seen to emit 4 KB titles; a row must not vanish because of a poster URL).

Unknown keys are kept, never fatal (fleet convention, `spis` D- pattern).

### 2.1 Item record (the unit the whole model walks on)

```
{ "id": <required>, "kind": "movie"|"tv"|"episode"|"file"|"folder"|"other",
  "title": str, "year": int|null, "imdb_id": "tt…"|null,
  "poster_url": str|null, "backdrop_url": str|null, "plot": str|null,
  "genres": [str], "runtime_min": int|null, "rating": float|null,
  "season": int|null, "episode": int|null, "air_date": str|null,
  "size": int|null (-1/absent = unknown), "duration_s": float|null,
  "mtime_ms": int|null, "added_ms": int|null,
  "sources": [ { "key","uri","url","quality","codec","hdr","hevc","dolby",
                 "audio_channels","width","height","extension","active",
                 "content_source","subtitle_count","subtitle_languages" } ],
  "path": str|null, "folder": str|null, "backend_id": str|null,
  "library": "scorpio_plus"|"media_empire"|"debrid"|"local"|"other"|null,
  "matched": bool|null, "extra": object|null }
```

`id` is required and must be non-empty; everything else is optional. The shipped
engines name the same identity differently — `spfiles_file_json(i)` and
`spmcat_result_json()` call it `key`, `spplfm_result_json()` and `spfsc_item_json(i)`
call it `id` — so `key` is accepted as a fallback when `id` is absent (the engine
never mints an id it was not given). `sources` may be
absent, null or empty — an item with no sources is *known but not playable*, which is a
different product state from *unknown* (see §7 and `spfiles` §0.3: the C# collapsed both
into `null`; we keep them apart).

`added_ms` is the "Recently Added" clock. Absent → fall back to `mtime_ms`, then to
`null` (the item sorts last in Recently Added, never dropped).

### 2.2 Watch-state record

```
{ "item_id": str|null, "imdb_id": "tt…"|null, "season": int|null,
  "episode": int|null, "position_s": float|null, "duration_s": float|null,
  "fraction": float|null (0..1), "finished": bool|null, "size": int|null,
  "updated_ms": int|null, "source": "server_progress"|"server_session"|
            "local_store"|"server_continue", "key": str|null }
```

At least one of `position_s` / `fraction` / `finished` must be present, else the record
is rejected (`SPHRM_ERR_BAD_INPUT`). `fraction` wins over `position_s/duration_s` when
both are present (the server stores the fraction — `spfiles` SPEC §1.3, measured:
`SMF_Position_*` `value` is already position/duration).

### 2.3 Library entry

A folder/file the shell walked but which produced **no** item record (the unmatched
case). Same fields as §2.1 minus `sources`/`imdb_id` (those come from a matcher).

## 3. Server sections → rows (the legacy order, measured)

TPlayer `HomePageViewModel.cs:127-171` builds `take2` from `detail.List`; IOSLegacy
`NewHomePageViewModel.cs:262-398` does the same with two extra removals. The engine
reproduces the observable order and makes the two dialects one rule:

1. every `List` entry with a non-empty `Value` becomes a row, **in server order**;
2. `MyWatched` and `HighSpeedServer` are **never** rows (TPlayer filters them at
   `:129`; IOSLegacy removes them at `:372`/`:379` — same outcome, one rule here);
3. `MovieNowPlaying` is pulled out of the list and re-inserted at index 2
   (`:134-136`, `:171`);
4. `Continues` (the `Continues` block, not a `List` id) is inserted at index 2
   (`:146-148`, IOSLegacy `:389-392`);
5. `Genre_*` entries from `ExtentList` collapse into one row inserted at index 0
   (`:150-156`);
6. `Spotlights` become a row inserted at index 0 (`:159`);
7. `MyWatchlist` and `BrowseHistory` are **kept as rows** and also stashed for the
   nav pane (`:138-141`) — the engine emits them as rows *and* exposes them via
   `sphrm_watchlist_json()` / `sphrm_browse_history_json()`;
8. `CachePlaylist_*` / `FeatureFlags_*` / `TitleTranslations` /
   `LanguageMapperTranslations` from `ExtentList` are **not** rows (they are config;
   `:152` only selects ids starting with `Genre`);
9. `CollectionPlaylists` → a "Collections" row; `Level30s` → the "Recently Added"
   seed (§4.2); `Basics` → the poster/metadata feed (§4.1).

Row order after steps 1-8 is therefore:
`Spotlight, Genre, <list rows…>, [MovieNowPlaying at 2], [Continues at 2] …`
— exactly the legacy stack: the later insert at 2 lands *before* the earlier one.
The engine keeps the two inserts in the legacy order (MovieNowPlaying first, then
Continues) so the visible result is `…, Continues, MovieNowPlaying, …` as shipped.

`HighSpeedServer` and `NewToSCORPIO` are still surfaced, not discarded:
`sphrm_server_flags_json()` returns
`{"high_speed_ids":[…],"scorpio_plus_ids":[…],"chromecast_ids":[…],"level30_ids":[…],"feature_flags":{…}}`
because `ITheFileItemService.Assign(highSpeedIds, scorpioPlustIds, chromecastsIds)`
(`Core/Toolkit14/Interfaces/ISPIMDbService.cs:732-738`) consumed exactly those three
strings and the detail page's "Find Resources" affordance depends on membership
(`MoviePageViewModel.cs:88-94`).

## 4. Derived rows

### 4.1 Row kinds (frozen values)

| value | name | meaning |
|---|---|---|
| 0 | `SPHRM_ROW_CONTINUE_WATCHING` | resume candidates, ranked (§4.2) |
| 1 | `SPHRM_ROW_RECENTLY_ADDED` | newest first (§4.3) |
| 2 | `SPHRM_ROW_MOVIES` | |
| 3 | `SPHRM_ROW_TV_SHOWS` | |
| 4 | `SPHRM_ROW_FOLDERS` | library folders to descend |
| 5 | `SPHRM_ROW_FAVOURITES` | |
| 6 | `SPHRM_ROW_GENRES` | |
| 7 | `SPHRM_ROW_COLLECTIONS` | server collections/playlists |
| 8 | `SPHRM_ROW_UNMATCHED` | walked but never matched (§5.3) |
| 9 | `SPHRM_ROW_SERVER_SECTION` | a raw `List` row (`My TV Series`, `What to watch ▶️`, …) |
| 10 | `SPHRM_ROW_SPOTLIGHT` | |
| 11 | `SPHRM_ROW_NOW_PLAYING` | |
| 12 | `SPHRM_ROW_EPISODES` | one show's season episodes |
| 13 | `SPHRM_ROW_SEASONS` | one show's seasons |
| 14 | `SPHRM_ROW_AUDIO` | |
| 15 | `SPHRM_ROW_PICTURE` | |

### 4.2 Continue Watching

Union of: the server `Continues` block, every `watch` record, and every item that has
both a source and a resume-eligible position. Dedup key =
`(imdb_id, season, episode)` when an imdb id exists, else `item_id`.

Ranking (newest first): `updated_ms` desc, then fraction desc, then position desc.
A record is **excluded** when the resume decision (§8) resolves to `START` — i.e. the
legacy thresholds say "this is effectively unwatched". That is the whole reason this
row is engine-side: the legacy home row showed entries the player would then restart
from 0 (`Events.cs:1608-1625`), so "Continue Watching" lied.

Per cell: `resume_action` (§8), `resume_position_s`, `progress_fraction`,
`next_episode` (§9), `poster_url`, `title`, `year`, `season`, `episode`,
`playable` (1/0), `source_count`.

**Server-first merge.** When both a server record and a local record exist for the same
key, the server wins (it is shared across devices); the local one is reported in
`local_only` so a shell can show "on this device".

### 4.3 Recently Added

Two sources, merged, deduped by id:
- `Level30s` (`{IMDbID, Size, FileName}` — the server's "new in the last 30 days" list,
  `spcat` SPEC §3) → items resolved through `items[]` by `imdb_id`; unresolved ids
  still produce a cell (title = `FileName`, poster = `null`) so the row never silently
  shrinks;
- `library`/`items` entries with `added_ms` (or `mtime_ms`) — the media-empire walk.

Order: `added_ms` desc; unknown-date entries last, in input order. Cap: `sphrm_set_row_cap(n)`
(default 200, max 2000) — the legacy home page pulled 5 items per section and
`LoadMoreItemsAsync(3)` on scroll (`HomePage.xaml.cs:76-84`); the engine returns the
whole ranked row and lets the shell page it.

### 4.4 Movies / TV Shows

Classification of an item: `kind` if present, else `IsTVShow` from the server `Basics`
block (key-cased agnostic — `spcat` D15), else the presence of `season`/`episode`,
else `runtime_min` vs `episode` heuristics **not** used (no guessing: unknown → `other`,
which appears in no genre row). Movies row = movie items sorted by `year` desc then
title asc; TV row = tv items sorted by `year` desc then title asc. Both rows dedupe
against Continue Watching (a show in Continue Watching is not repeated in TV Shows).

### 4.5 Favourites

From `store.favourites` (`spis_fav_token/metadata/display_name` — opaque capability
tokens, `spis` D17/D18). Order = insertion order as given. A favourite whose token
matches an `items[].id` gets the full cell (poster, resume); one that does not is still
a cell with `resolved: 0` — the shell must be able to say "this favourite is dead"
rather than dropping it silently (the legacy `FavoritesService` dropped them).

## 5. TV shows → seasons → episodes

`items[]` carrying `imdb_id` + `season` + `episode` are grouped per show.

- **Seasons row** (`SPHRM_ROW_SEASONS`): one cell per distinct season, `season` asc,
  `episode_count`, `poster_url` = the season's first episode poster when present.
- **Episodes row** (`SPHRM_ROW_EPISODES`): `season` asc, then `episode` asc, then
  `air_date` asc, then title asc. Cells carry `watch` state and `resume_action`.
- Shows with **no** episode items produce no season/episode rows (they stay in TV Shows).
- `season`/`episode` of 0 or absent = movie, never a season-0 row (the server uses
  `s=-1&e=-1`-style absence for movies — `spfiles` §1.1).

## 6. Ordering rules, and where each came from

| rule | citation |
|---|---|
| server `List` rows keep server order | `HomePageViewModel.cs:127-131` (no sort) |
| `MyWatched`/`HighSpeedServer` excluded | `HomePageViewModel.cs:129`; IOSLegacy `:372,:379` |
| `MovieNowPlaying` insert at 2 | `HomePageViewModel.cs:134-136,171` |
| `Continues` insert at 2 | `HomePageViewModel.cs:146-148`; IOSLegacy `:389-392` |
| Genre row insert at 0 | `HomePageViewModel.cs:150-156` |
| Spotlight row insert at 0 | `HomePageViewModel.cs:159` |
| Continue Watching newest-first | `MyWatchHistoryPageViewModel.cs:63-77` (server order = recency) + `spfiles` §1.3 `recordUpdated` |
| Recently Added = `Level30s` order | `HomePageViewModel.cs:143-145` (`NewToSCORPIO` + `Level30s` feed `ITheFileItemService`) |
| natural sort for folder-name rows | `spplfm_` SPEC §7 (the shipped natural comparator) |
| episode order season→episode→airdate | `MoviePage.xaml:81,171,178` (Season, then episode list, then AirDate) |

## 7. Item detail & sources

`sphrm_select_item(item_id)` (or `sphrm_select_imdb(imdb_id)` /
`sphrm_select_source(source_key)`) sets the current item; the getters read it.

**Source ranking** (best first), all ties broken by input order:
1. `active` sources only (`AccessEntry.isActive` — an inactive entry is listed but never
   offered; `spfiles` §1.1)
2. `content_source` 3 (Http, measured) before others
3. higher `width*height`, then `hdr`, then `dolby`, then `hevc`
4. larger `size`

`subtitle_languages` is passed through verbatim (comma-joined, as the wire gives it).
`uri` and `url` are **both** kept verbatim and never normalised — the measured wire has
rows where `url` is percent-encoded and `uri` is not (`spfiles` SPEC §1.1, Avengers
Endgame). A shell that "fixes" one of them breaks the other.

`playable` = `source_count > 0` — the product question `spfiles_is_playable` answers
(`spfiles` SPEC 0.1 rule 3: GetFiles is the source of truth, not the DB, not the disk).

## 8. Resume decision — the thresholds, verbatim from the shipped player

`TPlayer/Views/Events.cs:1576-1631` (`LoadPlaybackProgressAsync`), measured line by
line. Inputs: stored `position`, `base_time` (= `NaturalDuration`, falling back to the
session's duration), the server progress fraction, and the two switches.

```
if (!remember_last_position)            → START, 0            (:1578)
if (is_audio_only && !remember_audio)   → START, 0            (:1580-1582)
if (is_cue_track)                       → START, 0            (:1584-1586)
position = stored position (default 0)                        (:1588)
if (server fraction f present) and base_time > 30 s:
        position = base_time * f                              (:1600-1604)
if (base_time - position) < 5 s         → FINISHED, 0         (:1608-1613)
else if position > 5 s                  → RESUME, position    (:1616-1619)
else                                    → START, 0            (:1620-1623)
```

`is_audio_only` and `is_cue_track` are **inputs**, not guesses: the shell knows them
from the playback engine it is about to open. Defaults: `remember_last_position = 1`
(`CONSTANTS.RememberLastPosition` default `true`, `Events.cs:1578`),
`remember_audio = 0` (`DefaultValue.RememberAudioProgress`, `Properties.cs:780-787`).

Edge cases the engine must not fumble:
- `base_time` unknown (0) → the 5-second tail test is undecidable → `RESUME` if
  `position > 5 s` else `START`; `finished` is never asserted without a duration.
- `position > base_time` (a stale record after a re-encode) → clamp to
  `base_time - 1 s` and report `clamped: 1`.
- fraction outside [0,1] → clamp, `fraction_clamped: 1`.
- `base_time` exactly 30 s → the server fraction is **ignored** (`> 30`, strict).

Actions (`SPHRM_RESUME_*`): 0 `START`, 1 `RESUME`, 2 `FINISHED`.

## 9. Next episode

`bosxixi.ScorpioPlayer.Core/Toolkit14/RuntimeConfigHandlers/DebridDownloadConfig.cs:108-127`
(`GetNextEpisodeAsync`), reproduced exactly:

```
s = current.season, e = current.episode
if (s > 0 && e > 0):
    pick = the file in the same imdb whose (season==s && episode==e+1)
           AND whose first entry url == the current file's first entry url
    if none: pick = the first file with (season==s && episode==e+1)
    if pick && pick.imdb == current.imdb → next = pick
else: no next
```

The "same first-entry url" preference is the legacy way of staying on the same quality
/ language track across episodes; it is kept because it is observable. No season
rollover (`s,e+1` only) — the legacy never advanced seasons, and inventing that here
would change behaviour without a product decision.

**Autoplay timeline** (`DebridDownloadConfig.cs:152-211`), given the settings:
```
position = 0
if use_fixed_present_before && duration > present_before_duration:
    position = duration - present_before_duration
if use_percentage_present_before && 0 < pct < 1:
    position = duration * pct                      (percentage WINS — it overwrites)
if 0 < position < duration:
    prepare_position = position - 15 s   → "PrepareProposal"
    emit "Proposal" at position          (auto_dismiss = true)
countdown_position = enable_countdown ? duration - countdown_duration : duration
if 0 < countdown_position < duration:
    prepare_position = countdown_position - 15 s → "PrepareEnding"
    emit "Ending" at countdown_position  (auto_play = automatic_play_next)
```
The 15 s prepare lead is `TimeSpan.FromSeconds(15)` at `:170` and `:196`.
Defaults are **not** invented here: the engine takes the settings block from the shell
(`sphrm_set_autoplay_settings(json)`) and, when absent, emits no timeline and reports
`autoplay_configured: 0`.

## 10. Stable ids — `spplfm_` v2 rules, no new invention

`spplfm_` SPEC §9: v2 primary id = decimal string of
`GetStableHashCode(backend_id + "\u0001" + folder_path + "\u0001" + name)`; legacy id =
`GetStableHashCode(name)` alone (the collision defect D1). The hash is the djb2-UTF-16
`Math.Abs` fold, byte-exact, already shipped in `spcat`/`spfiles`/`spmcat`/`spis`.

This engine **does not mint ids for items** — ids come in from the callers (§2.1). It
does expose the same hash so a shell can build a key from a path without linking
another engine:
- `sphrm_stable_hash(utf8, out, n)` → decimal, byte-exact vs the C# (INT32_MIN → 0);
- `sphrm_resume_key(backend_id, folder_path, name, out, n)` →
  `Base64(UTF-8(backend_id + "\u0001" + folder_path + "\u0001" + name))` — the v2 key
  `spis_` stores positions under;
- `sphrm_legacy_resume_key(folder_name, out, n)` → `Base64(UTF-8(folder_name))`
  (byte-exact legacy, `LoadFolderAsync.cs:241-242`).

Dedup inside this engine uses the incoming `id` verbatim; when two items share an id
the **first** wins and the second is counted in `rejected` (mirrors `spfsc` §D7).

## 11. Output contract

`sphrm_result_json()` → one document:

```
{ "version": 1, "status": 0,
  "row_count": n,
  "rows": [ { "index": 0, "kind": 10, "key": "Spotlight", "title": "Spotlight",
              "cell_count": 9, "truncated": 0,
              "cells": [ { "item_id","imdb_id","title","year","kind","poster_url",
                           "backdrop_url","season","episode","playable","source_count",
                           "resume_action","resume_position_s","progress_fraction",
                           "finished","added_ms","next_item_id","resolved","library",
                           "server_key" } ] } ],
  "item": { …detail…, "sources":[…], "resume":{…}, "next":{…}, "autoplay":[…] },
  "server_flags": { … }, "watchlist": "…", "browse_history": "…",
  "stats": { "items":n,"watch":n,"library":n,"rows":n,"cells":n,"rejected":n,
             "continue_candidates":n,"unmatched":n } }
```

Cells are **render-ready**: a shell maps `kind` → a widget and never computes an order,
a threshold, or a season grouping itself. `truncated: 1` means the row had more cells
than the cap and `cell_count` is the real count.

## 12. Error taxonomy (frozen)

| code | name |
|---|---|
| 0 | `SPHRM_OK` |
| 1 | `SPHRM_ERR_BAD_INPUT` (JSON invalid / wrong shape — state cleared) |
| 2 | `SPHRM_ERR_INVALID_ARG` |
| 3 | `SPHRM_ERR_OOM` |
| 4 | `SPHRM_ERR_TOO_LARGE` (cap exceeded, or output buffer too small) |
| 5 | `SPHRM_ERR_NO_STATE` (no inputs loaded / no item selected) |

## 13. Conventions (fleet)

- Pure C99, vendored `yyjson` 0.12.0, no other dependency, no sockets, no threads.
- `exports.json` == `nm -D --defined-only` == the `.map` version script.
- Global state, single-threaded (fleet style); `sphrm_shutdown()` frees everything.
- No secrets anywhere; no store publishes; nothing writes.
- `.console` harness: one PASS/FAIL per export, Linux `.so` + Windows `.dll`.

## 14. Test corpora (real fixture JSON, read-only)

| fixture | origin |
|---|---|
| `tests/corpus/homepage.auth-profile0.json` | the shipped `spcat` zlib capture, inflated (real server home, 11 sections, 100 Continues, 6,572 Level30s, 710 Basics) |
| `tests/corpus/getfiles.movie-multi.json` | `spfiles` corpus, `GET /api/finder/getfiles?id=tt4154796` (3 qualities, space-containing filename) |
| `tests/corpus/getfiles.tv-all.json` | `spfiles` corpus, `id=tt0944947&s=&e=` — 114 files, whole series |
| `tests/corpus/getfiles.movie-single.json` | `spfiles` corpus, `tt0111161` |
| `tests/corpus/position.rows.json` | `spfiles` corpus, `SMF_Position_` rows (fraction 0..1, p5/p6/p7) |
| `tests/corpus/basics.sample.json` | `spmovie` corpus basics array (title/year/duration/IsTVShow/genres/ratings) |
| `tests/corpus/spfsc_hosted_root.json` | `spfsc` fixture listing (`tests/fixtures/media.json`) |
| `tests/corpus/spis_local_snapshot.json` | `spis` fixture (`tests/fixtures/local__ok__typical.json`) |
| `tests/corpus/spplfm_result.json` | `spplfm` CLI `result-json` output on a real listing |
| `tests/corpus/empire_*.json` | **live, read-only** GETs against `http://192.168.1.90:3323/Hosted/` through the shipped `spfsc` CLI (no writes) |

Every threshold in §8/§9 is asserted against a fixture, not against prose.
