# SPEC — scorpiox-scorpioplayer-iptv-m3u-source-client (RuntimeType `IPTV`)

Status: v1.0.0. This file was written before any C code. Every decision is numbered and
cites the C# reference as `file:line` (files are in
`reference/scorpiox-scorpioplayer-iptv-m3u-source-client/csharp-reference/`). "Oracle"
means the real C# parser `M3UParser` 1.0.0.1 (NuGet, Mark Saunders). It is the assembly that
`IPTVFolderFileAccesssor.cs:44` calls as `M3UParser.M3UParser.parse(string[])`. The package
API is identical: `List<M3UFileInfo{Title,Location,Duration}> parse(string[])`. The oracle
runs from `scorpiox-scorpioplayer-iptv-m3u-source-client.console --oracle`.

## 1. Scope and wire subset

| Implemented | Not implemented |
|---|---|
| HTTP(S) GET of one playlist URL through `scorpiox_io.http_get` | `http_post`, auth, tokens (IPTV has none) |
| `#EXTM3U` playlists (any encoding the vendored parser decodes) | HLS media/master manifests (refused, D14) |
| `#EXTINF` attributes `tvg-id`, `tvg-name`, `tvg-logo`, `group-title`, `http-user-agent`, `http-referrer` | `#EXTHTTP`, `#KODIPROP`, `url-tvg` / EPG |
| `#EXTVLCOPT:http-user-agent=` / `http-referrer=` (also `http-referer`) | every other `#EXTVLCOPT` key |
| `#EXTGRP:` (through the vendored parser) | catch-up / timeshift attributes |

The parser is **vendored** (`vendor/spplp`, `scorpiox-scorpioplayer-playlist-file-parse`
at the pinned promoted commit `aad25ee`, the reference copy plus one local overflow patch; see
`vendor/spplp/VENDOR.md`). This repo contains no second M3U parser. The one addition is a
`#EXTVLCOPT` side-scan (D12). It exists because the vendored parser drops that tag
(`spplp_engine.c:304`).

## 2. Decisions

| # | Decision | Source |
|---|---|---|
| D1 | `runtime_type = "IPTV"`, exact and case-sensitive. | `IPTVRuntimeConfigHandler.cs:11` |
| D2 | `caps = SPRCH_CAP_LIST \| SPRCH_CAP_STREAM \| SPRCH_CAP_VALIDATE` = `0x23`. The reference SKILL.md said `0x3`, but that predates sprch v1, which adds `CAP_VALIDATE` for handlers with a `Test<X>Connection`. IPTV has `TestIPTVConnection`. | `IPTVRuntimeConfigHandler.cs:36`, sprch.h v1 |
| D3 | Settings are the legacy `RuntimeSettings` dictionary. Keys read: `URL`, `ID`. Keys written by `validate`: `RuntimeType`, `URL` (only when defaulted), `ID` (only when empty). Every other key is copied through unchanged, including its JSON type. | `IPTVRuntimeConfigHandler.cs:15,43,44,49,56,60` |
| D4 | `validate` output is the **full** input object with those keys applied, so the round-trip preserves unknown keys even without the registry merge. | sprch.h ("full, or only the keys changed") |
| D5 | Empty or missing `URL`: use `https://iptv-org.github.io/iptv/index.category.m3u`. **Divergence:** C# does this only under `Debugger.IsAttached`. The reference SKILL.md specifies the default unconditionally. | `IPTVRuntimeConfigHandler.cs:46-50` |
| D6 | `URL` must be absolute `http://` or `https://` with a non-empty host; anything else is `E_CONFIG`. C# `HttpClient` also rejects other schemes, but its catch-all turns that into "Failed". | `IPTVFolderFileAccesssor.cs:29,55-59` |
| D7 | `validate` = fetch + parse + require >= 1 usable entry (D10). That is `TestFileServerAsync` returning `files.IsNotEmptyItems()`. `validate` always goes to the network (it is a connection test), bypassing the max-age of D17; an unchanged body still skips the re-parse (D18). | `IPTVRuntimeConfigHandler.cs:71-81` |
| D8 | `ID` empty or missing: a new random RFC 4122 v4 GUID in the lowercase `8-4-4-4-12` format of `Guid.NewGuid().ToString()`. An existing `ID` is never replaced. | `IPTVRuntimeConfigHandler.cs:58-61` |
| D9 | Status handling: 2xx is OK. See section 4 for the full map (C# `EnsureSuccessStatusCode` treats all non-2xx the same). | `IPTVFolderFileAccesssor.cs:30` |
| D10 | A playlist entry is **usable** iff its location is non-empty and an absolute URI (D11), and its display name is non-empty. Display name = the `#EXTINF` title, else `tvg-name`. **Divergence:** C# requires the title and has no `tvg-name` fallback. On the default playlist every entry has a title, so the oracle diff is empty (report). | `IPTVFolderFileAccesssor.cs:47` |
| D11 | Absolute URI = `scheme ":" rest`, where scheme is `ALPHA *(ALPHA/DIGIT/"+"/"-"/".")`, rest is non-empty, and there is no ASCII control char. When rest starts with `//`, the authority must be non-empty and contain no space. This matches the oracle (`Uri.TryCreate(..., Absolute)`) for `http`, `https`, `rtmp`, `mmsh`, `srt`, `urn:`, `C:\x`, a space in the path (accepted) and a space in the host (rejected). **Divergence:** a bare `/a/b` path is rejected; .NET on Unix accepts it as a `file://` URI that cannot be played remotely. | oracle probe, `tests/oracle/` |
| D12 | `#EXTVLCOPT:http-user-agent=` and `http-referrer=` (or `http-referer=`) are collected by a side-scan over the parser's decoded UTF-8 text (`g_sp.utf8`). Options accumulate until the next location line; that line's item ordinal is exactly the one the vendored parser assigns (every non-empty, non-`#` line after the header is one item). The last occurrence wins. | task "Behaviour", `spplp_engine.c:273-336` |
| D13 | `stream_url` headers: `#EXTVLCOPT` first, then `#EXTINF` attributes `http-user-agent` / `http-referrer` (the iptv-org lists carry both). Emitted as `"User-Agent"` and `"Referer"`. `"headers"` is always present (possibly `{}`). | task "Behaviour", SKILL.md |
| D14 | Content gate: the body must parse as M3U (`#EXTM3U` header, vendored parser `SPPLP_FMT_AUTO` resolving to `SPPLP_FMT_M3U`). HLS manifests, CUE sheets, headerless URL lists and unknown bodies are `E_PROTOCOL`. **Divergence:** C# gates on a `Content-*` header containing `.m3u` or the URL ending in `.m3u`. `scorpiox_io` v1 exposes no response headers, so we sniff the body instead. The oracle also requires the header (`InvalidDataException: Missing header`). | `IPTVFolderFileAccesssor.cs:32-34` |
| D15 | Tolerance where the oracle throws: C# throws on the first `#EXTINF` without a comma, on a lowercase `#extm3u`, and on leading blank lines. The throw loses the **whole** playlist to the catch-all. The vendored parser keeps the rest of the list. **Divergence**, deliberate (strictly more entries). | oracle probe |
| D16 | `list` layout. Root (`""`, `"/"`, `"root"` or NULL) = one folder per distinct `group-title`, in order of first appearance. An empty or missing group goes to `"Other"`. If **no** usable entry has a group, the root lists the channels directly (flat). A folder (`"/<group-title>"`, verbatim; the bare SKILL.md form `"<group-title>"` is accepted too) = its channels in playlist order. Lookup is exact and case-sensitive. **Divergence:** C# is always flat (`GetMediaFolderItemsAsync` returns null). The task specifies grouping. | `IPTVFolderFileAccesssor.cs:62-65`, task "Behaviour" |
| D17 | Cache: the parsed playlist is cached per URL (up to 4 URLs, LRU) for a **max age of 6 h**. `list` and `stream_url` inside the max age touch no network. | task "Behaviour" |
| D18 | Revalidation: after max age (or on every `validate`), the playlist is re-fetched. If the body's 64-bit FNV-1a hash and length equal the cached ones, the cache is refreshed without re-parsing. | task "Behaviour" |
| D19 | ETag / Last-Modified live in the **transport**: `scorpiox_io` v1 has no request or response headers. The bundled libcurl backend keeps `ETag` / `Last-Modified` plus the body per URL (8 URLs). It sends `If-None-Match` / `If-Modified-Since`, and on `304` hands the stored body back as `200`. The iOS `URLSession` backend gets the same behaviour from `URLCache`. The hit is counted and exported (`spiptv_stats_json`). | `scorpiox-io.h` |
| D20 | Stable item id = 16 lowercase hex digits of FNV-1a 64 over `stream URL + "\x1f" + tvg-id`. Identical (id) entries within one folder are de-duplicated, keeping the first; C# resolves duplicates by `FirstOrDefault` too. The same channel in two groups keeps the same id in both. | `IPTVPlaylistFolder.cs:40`, task "Behaviour" |
| D21 | Item JSON (the #26 shape plus the SKILL.md keys). Channel: `{"id","name","path":"/<group>/<id>","folder":false,"is_folder":false,"size":-1,"group","tvg_id","tvg_name","tvg_logo","stream_url"}`. Folder: `{"id":"/<group>","name","path":"/<group>","folder":true,"is_folder":true,"size":-1,"count":N}`. Both `folder` (sprch.h) and `is_folder` (SKILL.md) are emitted because the two drafts disagree. In `name`, `/` becomes U+2215 (spffa: one path segment; `Sport 24/7` stays readable) and ASCII control chars become spaces; `path` keeps the group verbatim. `size` is `-1` = unknown (C# wrote `0`, `IPTVFolderFileAccesssor.cs:47`, but spffa forbids 0 for unknown). | `spffa.h` |
| D22 | `stream_url(entry_json)`: entry must be a JSON object. If it has `"id"`, the id is resolved against the (cached) playlist of `settings.URL`; an unknown id is `E_NOTFOUND`. If it has no `"id"` but an absolute `"stream_url"` / `"url"`, that URL is returned with no headers and no network. Output: `{"url":"...","headers":{...}}`. C# returned null here and played the `HttpNamedStream` URL directly. | `IPTVRuntimeConfigHandler.cs:25-28`, `IPTVFolderFileAccesssor.cs:49` |
| D23 | `download` returns `SPRCH_E_NOTSUPPORTED` unconditionally. The handler is read-only: no `CAP_WRITES` and no `_allow_writes` export. | `IPTVRuntimeConfigHandler.cs:20-23` |
| D24 | Output that does not fit `cap` returns `SPRCH_E_BUFFER`, and nothing but a NUL (when `cap >= 1`) is written. The full JSON stays readable through `spiptv_result_json()` until the next call. | sprch.h v1 |
| D25 | On an error the out buffer receives `{"error":"<message>"}` when it fits. Messages never contain URL userinfo, query or fragment: URLs are redacted to `scheme://host[:port]/path` + `?<redacted>`. Xtream-style `?username=&password=` lists are common. | sprch.h, task "Rules" |
| D26 | Body limit 64 MiB (`E_PROTOCOL` above). `scorpiox_io` v1 bodies are NUL-terminated with no length, so a body is read up to its first NUL. UTF-16 playlists are therefore unreadable over `scorpiox_io` v1 (open question Q2). | `scorpiox-io.h` |
| D27 | Concurrency: one process-wide mutex serializes every entry point, because the vendored parser and the cache are global. `spiptv_last_error()` / `spiptv_result_json()` point into process-wide buffers: copy them before the next call. | fleet style (`spffa.h` "Threading") |
| D28 | `M3UService.cs:67` (`Title.Replace(",", " ")`) belongs to the local-file path (`GetM3UFolderAsync`), not to IPTV. It is not applied. | `M3UService.cs:50-88` |
| D29 | Title with commas: the vendored parser splits `#EXTINF` at the **last unquoted** comma, so the title `Chan, A` becomes `A`. The oracle splits at the **first** comma, whether or not it is quoted, and produces garbage when an attribute value contains a comma. Neither is right. We keep the vendored behaviour (defect V1 in section 7): 0 default-playlist lines have two unquoted commas. The oracle's quote-blind split corrupts **539 of 11,596** default-playlist titles, because their `http-user-agent` value contains `KHTML, like Gecko` (C2). | oracle diff, `spplp_engine.c:212-219` |
| D30 | Every emitted string is strictly valid UTF-8 (RFC 3629). The vendored parser's UTF-8 check is lenient (it accepts surrogates, overlongs and code points above U+10FFFF), so invalid sequences become U+FFFD when stored. The id (D20) hashes the emitted URL + tvg-id, so `list` output always round-trips into `stream_url` through a strict JSON reader. Error messages replace invalid bytes with `?`. | found by fuzzing, section 7 H1 |

## 3. State machine (per URL cache entry)

```
            fetch ok + parse ok                  age < 6h (list/stream_url)
  EMPTY ---------------------------> FRESH <--------------------------------+
    ^                                  |  age >= 6h, or any validate        |
    |  evicted (LRU, >4 URLs)          v                                    |
    +-------------------------- REVALIDATE -- same hash (304 or 200) -------+  (no re-parse)
                                       |------ new hash --> parse --> FRESH (replaced)
                                       |------ transport/HTTP/parse error --> error returned;
                                                the cache entry is dropped (never served stale)
```

A failed revalidation drops the entry and returns the error. A stale list is never served,
because "a network failure is never an empty list" and a silent stale list would hide it.

## 4. Error taxonomy

| Condition | Code |
|---|---|
| `settings_json` NULL, not JSON, not an object; `URL` not a string or not `http(s)://host` | `SPRCH_E_CONFIG` (-8) |
| `io` NULL or `io->http_get` NULL | `SPRCH_E_CONFIG` (-8) |
| `entry_json` not an object, or with neither `id` nor an absolute `stream_url`/`url` | `SPRCH_E_CONFIG` (-8) |
| transport failure (`http_get` returned -1) | `SPRCH_E_NETWORK` (-4) |
| HTTP 401, 403 | `SPRCH_E_AUTH` (-1) |
| HTTP 404, 410 | `SPRCH_E_NOTFOUND` (-2) |
| HTTP 429 | `SPRCH_E_RATE` (-3) |
| HTTP 408, 5xx, or 0 | `SPRCH_E_NETWORK` (-4) |
| any other non-2xx (1xx, 3xx not followed, 4xx) | `SPRCH_E_PROTOCOL` (-5) |
| body > 64 MiB, empty, not M3U, HLS, out of memory while parsing | `SPRCH_E_PROTOCOL` (-5) |
| `validate`: 0 usable entries | `SPRCH_E_PROTOCOL` (-5) |
| `list`: folder not found; `stream_url`: id not found | `SPRCH_E_NOTFOUND` (-2) |
| `download` | `SPRCH_E_NOTSUPPORTED` (-6) |
| out NULL, `cap <= 0`, or output does not fit | `SPRCH_E_BUFFER` (-9) |

`list` of a valid playlist with 0 usable entries returns `SPRCH_OK` with `[]`. That is the
server's real answer, not a network failure.

## 5. Auth and limits

- Auth: none. Credentials embedded in the URL (userinfo, query) are forwarded to the
  transport untouched and are redacted from every message (D25).
- Limits: body <= 64 MiB (D26); cache <= 4 playlists (D17); the libcurl backend stores
  <= 8 validators; redirects are followed (<= 10); connect timeout 15 s, total 120 s.
- Performance budget (task): the 2.6 MB default list must parse in < 300 ms and < 32 MB.
  Measured with `spiptv bench`; the numbers are in the README and the report.

## 6. Exports (flat P/Invoke, prefix `spiptv_`)

`sprch_get`, `spiptv_validate`, `spiptv_list`, `spiptv_stream_url`, `spiptv_download`,
`spiptv_last_error`, `spiptv_result_json`, `spiptv_version`, `spiptv_runtime_type`,
`spiptv_caps`, `spiptv_set_io`, `spiptv_use_curl`, `spiptv_use_fake`, `spiptv_fake_reset`,
`spiptv_fake_set`, `spiptv_fake_fail`, `spiptv_fake_calls`, `spiptv_cache_clear`,
`spiptv_cache_set_max_age`, `spiptv_stats_json`. `exports.json` is checked against
`nm -D --defined-only` by `make exports-check`. The flat calls use the installed backend:
libcurl by default, or the fake after `spiptv_use_fake()`.

## 7. Defects found (reference: reported; this engine: fixed)

- **V1 (vendored parser, P2):** the `#EXTINF` title is cut at the last unquoted comma (D29).
- **V2 (vendored parser, P2):** `spplp_item` embeds `attrs[64]`, about 1 KB per item. The
  11,596-entry default list costs about 17 MB of item array. That is inside budget (section 5),
  but it is the dominant cost.
- **V3 (vendored parser, P3):** `#EXTVLCOPT` is dropped (the reason for D12). Upstreaming it
  would delete the side-scan.
- **C1 (C#, P1):** one malformed `#EXTINF` (no comma) throws inside `M3UParser.parse` and the
  catch-all at `IPTVFolderFileAccesssor.cs:55` returns null. The whole source shows as
  empty or "Failed" (D15).
- **C2 (C#, P1):** the title split takes the first comma even inside a quoted attribute (D29).
  On the **default URL** that corrupts 539 of 11,596 channel names in the shipped app
  (`tests/oracle/index.category.expected.diff`).
- **C3 (C#, P1):** `M3UParser` rejects a header with attributes (`#EXTM3U url-tvg="..."`,
  the norm for Xtream / EPG-enabled lists) with `Missing header`, so the whole source is lost
  (`tests/oracle/basic.expected.diff`).
- **V4 (vendored parser, P0 for any strict-C99 build):** `strdup` without a feature-test
  macro. Under `-std=c99` it is implicitly declared `int` and pointers are truncated, which
  crashes on the first parse. We build the vendored code with `-D_POSIX_C_SOURCE=200809L
  -Werror=implicit-function-declaration`.
- **V5 (vendored parser, P1):** signed integer overflow (undefined behaviour) in every digit
  accumulator (`#EXTINF` duration, CUE `mm:ss:ff` / `TRACK` / `INDEX`). Found by libFuzzer
  + UBSAN. Fixed by local patch `vendor/spplp/patches/0001-saturate-digit-accumulators.patch`,
  which should be upstreamed.
- **V6 (vendored parser, P1 for Windows):** `spplp_internal.h` includes POSIX `<iconv.h>`,
  which neither MSVC nor mingw-w64 ships, so the parser does not build for Windows as vendored.
  A mingw-w64 cross-link of this engine with a UTF-8-only iconv stub works and exports exactly
  the 20 symbols of `exports.json`. The shipping fix belongs upstream (win-iconv, or
  `MultiByteToWideChar` on `_WIN32`).
- **H1 (this engine, found by the fuzzer before shipping, fixed):** invalid UTF-8 from the
  parser was emitted as-is, so a listed channel could fail `stream_url` behind a strict JSON
  reader. Fixed by D30. Regression input: `tests/fuzz/corpus/playlist/regress-invalid-utf8-roundtrip.m3u`.
- **H2 (this engine, found by the unit tests, fixed):** a transport error that echoed only the
  query string (`username=..&password=..`) leaked it into `last_error`. Every query value
  and the userinfo are now redacted individually (D25).
- **H3 (this engine, P0, found by the fuzzer before shipping, fixed):** `spiptv_redact_url`
  looped forever once its output buffer filled before the `?<redacted>` suffix, because the
  `PUT` macro skipped evaluating `*r++`. Any configured URL longer than about 500 bytes with a
  query string (typical for Xtream lists) would have hung every call while holding the handler
  lock. Unit test + `tests/fuzz/corpus/inputs/regress-h3-redact-long-url-hang`; libFuzzer now
  runs with `-timeout=10` so hangs are reported.

## 8. Open questions (written down, not guessed)

- **Q1** The canonical `sprch_conformance.h` / `sprch_conformance.c` (registry repo, row 54)
  is not reachable from the cloud session. `make test` gates on a local conformance suite
  (`tests/sprch_conformance_local.c`) that checks the same published contract. Swap in the
  canonical files verbatim when promoting.
- **Q2** `scorpiox_io` v1 has no body length and no headers. That blocks UTF-16 bodies (D26)
  and in-handler conditional GET (D19). Propose `scorpiox_io` v2: `http_get_ex` with a
  request-header list, response headers and a body length.
- **Q3** No `SPRCH_E_*` code fits out-of-memory; it is mapped to `E_PROTOCOL`.
- **Q4** Should `group-title="A;B"` (iptv-org multi-category syntax used by some lists)
  place the channel in both folders? Today it is kept verbatim as one folder `A;B`. The
  default list uses one category per line.
- **Q6** `#EXTVLCOPT` keys other than user-agent / referrer (e.g. `http-origin`) are dropped.
  Should `stream_url` forward them as headers?
- **Q5** Should an expired or unreachable playlist fall back to the stale cache for
  `stream_url` only? Today it does not (section 3).
