# SPEC — scorpiox-scorpioplayer-ffmpeg-ios-android-playback-engine

Pure C11 playback core for **iOS / tvOS / macOS / Android**. Not a port of the
Windows/Xbox engine (row 23b) — a sibling with a different clock/present design.
Both are fed by the same FFmpeg build (`scorpiox-ffmpeg-libav` n9.0.2, LGPL, shared).

**User decision 2026-09-26 (#23c):** full control, our own engine. Not AVPlayer, not
VLCKit, not MPVKit. The C core owns demux, clock/A-V sync, track selection, seek,
buffering, subtitle decode + render, audio decode to PCM, and software fallback. The OS
does only hardware decode + presentation through **thin platform backends**.

```
Apple   : VideoToolbox VTDecompressionSession -> CVPixelBuffer
          -> AVSampleBufferDisplayLayer + AVSampleBufferAudioRenderer
          + AVSampleBufferRenderSynchronizer
Android : NDK AMediaCodec -> ANativeWindow (Surface) + AAudio
```

Those backends are separate repos (`…-apple-backend-swift`, `…-android-backend-kotlin`).
**This repo contains no Objective-C, no Swift, no Java, no JNI.**

---

## 1. Why a separate engine, not a port

| | Windows/Xbox (`sppb_`) | iOS/Android (`sppe_`) |
|---|---|---|
| Presentation model | caller **pulls** samples (`sppb_pull_frame`), the WinRT layer builds a `MediaStreamSource` | engine **pushes** to platform sinks on a clock (`video_sink.present`) |
| Clock owner | the Media Foundation pipeline | **this engine** (audio clock by default) |
| Sync | implicit (MF) | explicit drop/repeat against the master clock |
| Hardware decode | D3D11VA texture handed back as `AV_PIX_FMT_D3D11` | opaque `frame_handle` the backend understands (CVPixelBuffer / AHardwareBuffer) |
| Subtitles | cues delivered to the app | cues **and** rendered RGBA overlays (libass / PGS) |
| Transport | `sppb_io` callbacks | same shape, `sppe_io` |

Consequence: **nothing is copy-pasted from `sppb_`.** Where a module is genuinely the
same shape (the subtitle *cue model*: text bytes vs bitmap+palette) the SPEC says so and
the module is scheduled for a later shared repo — it is not vendored today.

---

## 2. Boundary

```c
/* include/sppe.h — the whole public surface */
sppe_t *sppe_open_path(const char *utf8_path_or_url, const char *config_json);
sppe_t *sppe_open_io(const sppe_io *io, const char *name_hint, const char *config_json);
void    sppe_close(sppe_t *);

const char *sppe_info_json(sppe_t *);   /* streams, HDR/DV metadata, chapters, attachments */
int  sppe_select(sppe_t *, int video, int audio, int sub_primary, int sub_secondary);

int  sppe_play(sppe_t *);  int sppe_pause(sppe_t *);  int sppe_is_playing(const sppe_t *);
int  sppe_set_rate(sppe_t *, double rate);
int  sppe_seek(sppe_t *, int64_t ticks, int mode);      /* mode 0=accurate 1=fast */
int  sppe_set_audio_delay(sppe_t *, int64_t ticks);
int  sppe_pump(sppe_t *, int64_t max_wait_ms);          /* one step of the engine loop */

int  sppe_install_backend(sppe_t *, const sppe_backend *);
const char *sppe_status_json(sppe_t *);
const char *sppe_last_error(const sppe_t *);
const char *sppe_version(void);
```

Units: **100 ns ticks** (`int64_t`), the same unit `sppb_` and `TimeSpan` use. iOS has no
libcurl, so transport is always the caller's callbacks.

### 2.1 The io seam (identical shape to `sppb_io`, deliberately)

```c
typedef struct sppe_io {
    void   *ctx;
    int     (*read) (void *ctx, uint8_t *buf, int n);         /* >0 bytes, 0 EOF, <0 err */
    int64_t (*seek) (void *ctx, int64_t off, int whence);     /* + AVSEEK_SIZE (0x10000) */
    int64_t (*size) (void *ctx);                              /* total bytes or -1 */
    int     (*interrupt)(void *ctx);                          /* non-zero aborts */
    void   *reserved[4];
} sppe_io;
```

`config_json` is lenient about unknown keys and clamps out-of-range values, but a
malformed document is a typed error (`SPPE_ERR_ARG`) rather than a silent fallback to
defaults — an app's typo should be visible.

`bytes_read` is counted **inside the AVIOContext read shim**, so probe reads, demux reads
and seek reads are all counted. (Same P0 the Windows engine fixed: the legacy per-packet
counter missed FFmpeg's probe traffic.)

---

## 3. The backend vtable — exactly as the Apple/Android tasks implement it

```c
typedef struct sppe_codec_par {          /* transport-free view of AVCodecParameters */
    const char *codec_name;              /* "h264","hevc","av1","vp9","mpeg2video",...  */
    const uint8_t *extradata;  int extradata_size;
    int width, height;                   /* video */
    int profile, level;
    int pix_fmt;                         /* AVPixelFormat value, -1 for audio */
    int bit_depth;                       /* 8 / 10 / 12 */
    int sample_rate, channels;           /* audio */
    int color_primaries, color_trc, color_space, color_range;
    void *av_codecpar;                   /* escape hatch: const AVCodecParameters*      */
} sppe_codec_par;

/* A hardware frame the engine never inspects: only the backend knows what it is. */
typedef struct sppe_hw_frame {
    void *handle;                        /* CVPixelBufferRef / AHardwareBuffer*         */
    int   width, height;
    int   pix_fmt;                       /* backend's own code for the surface format   */
    int64_t pts_ticks;
    void *opaque;                        /* backend-private (e.g. the CMSampleBuffer)   */
} sppe_hw_frame;

typedef struct sppe_hdr_meta {
    int present;                         /* 0 = no HDR metadata on this stream          */
    int transfer;                        /* 0 SDR, 1 PQ (SMPTE2084), 2 HLG (ARIB-B67)   */
    int primaries;                       /* 1 BT.709, 9 BT.2020                         */
    int matrix;
    int full_range;
    int has_mastering;                   /* mastering display + light levels follow     */
    int prim_x[3], prim_y[3], wp_x, wp_y;      /* in 0.00002 units as FFmpeg gives them */
    int64_t min_lum, max_lum;                  /* 0.0001 nit units                      */
    int has_cll;
    int max_cll, max_fall;                     /* nits                                  */
    int has_dovi;
    int dv_profile, dv_level, dv_bl_signal_compatibility_id, dv_rpu_present;
} sppe_hdr_meta;

typedef struct sppe_sw_frame {           /* software fallback, planar, engine-owned     */
    int width, height, pix_fmt;
    const uint8_t *data[4];
    int linesize[4];
} sppe_sw_frame;

typedef struct sppe_backend {
    int abi;                             /* SPPE_BACKEND_ABI == 1                       */
    const char *name;
    void *ctx;

    /* ---- hardware decoder ------------------------------------------------ */
    /* probe: 1 = this backend can hardware-decode this codec par, 0 = cannot.
     * Never fails the open; a 0 simply selects the software path.             */
    int   (*hw_probe)(void *ctx, const sppe_codec_par *par);
    void *(*hw_open) (void *ctx, const sppe_codec_par *par);
    int   (*hw_submit)(void *ctx, void *dec, const void *pkt_data, int pkt_size,
                       int64_t pts, int64_t dts, int key);
    /* receive: 0 = frame in *out, 1 = need more input, 2 = EOF, <0 = ERROR
     * (an error here triggers the documented software fallback).             */
    int   (*hw_receive)(void *ctx, void *dec, sppe_hw_frame *out);
    int   (*hw_flush)(void *ctx, void *dec);
    void  (*hw_close)(void *ctx, void *dec);
    /* release a frame the engine has finished presenting */
    void  (*hw_frame_free)(void *ctx, sppe_hw_frame *f);

    /* ---- sinks ----------------------------------------------------------- */
    int   (*video_present)(void *ctx, const sppe_hw_frame *hw, const sppe_sw_frame *sw,
                           int64_t pts_ticks, int64_t duration_ticks);
    int   (*video_set_hdr)(void *ctx, const sppe_hdr_meta *meta);
    int   (*audio_configure)(void *ctx, int sample_rate, int channels, int sample_fmt,
                             const char *layout_name);
    int   (*audio_write)(void *ctx, const uint8_t *const *planes, const int *linesize,
                         int nb_samples, int64_t pts_ticks);
    /* the master clock: playback position in ticks. NULL = engine uses its own
     * monotonic clock (that is what makes the fake backend headless).         */
    int64_t (*audio_clock_now)(void *ctx);
    int   (*audio_flush)(void *ctx);

    int   (*subtitle_overlay)(void *ctx, const uint8_t *rgba, int width, int height,
                              int stride, int x, int y, int64_t pts_ticks,
                              int64_t duration_ticks);
    int   (*subtitle_clear)(void *ctx);
} sppe_backend;

#define SPPE_BACKEND_ABI 1   /* v1.0.0 shape; v1.1.0 header defines 2 with ABI_MIN 1 — see "v1.1.0" section below */
```

Notes the Apple/Android task must honour:

1. `hw_probe` returning 0 is **not** an error — it selects software decode.
2. Any `hw_receive` < 0 **at runtime** also falls back to software for that stream, is
   counted (`sppe_status_json` → `fallbacks[]`), and the error text is kept.
3. The engine never dereferences `hw_frame.handle`. It is the backend's object; the
   engine only passes it back to `hw_frame_free` after `video_present`.
4. `audio_clock_now` is polled once per pump; if the backend returns a negative value the
   engine treats the audio clock as unstarted and uses the monotonic clock until the sink
   reports a real position.
5. All sinks are optional. A backend that only implements `video_present` still works —
   the engine's fake backend does exactly that plus recorders.

### 3.1 Fake backend (`src/sppe_backend_fake.c`)

Implements the whole vtable with **recorders**: every `video_present` records
`(pts, sw or hw, drop_or_show)`, every `audio_write` records `(pts, nb_samples)`,
`subtitle_overlay` records `(pts, w, h, crc32)`, `hw_probe` answers from a configurable
codec list, and `audio_clock_now` is driven by a settable `fake_clock`. That is what makes
the entire pipeline run headless on Linux, and what the A-V sync metrics are measured on.

`--fake-hw h264,hevc` enables hardware for those codecs. `--fake-hw-fail h264@frame120`
makes `hw_receive` fail at a chosen frame so the fallback path is *exercised*, not just
existent.

---

## 4. Clock and A/V sync

* **Master clock = audio**, unless `audio_clock_now` is absent/unstarted, in which case the
  engine's own `now_ticks()` (monotonic) is used and seeded at the first presented video
  frame. `config_json` may force `{"clock":"system"}`.
* `clock = audio_position - audio_delay`, where `audio_position` is what the sink reports.
* A video frame is **presented** when `frame_pts <= clock + 1 frame`. It is **dropped**
  when `frame_pts < clock - drop_threshold` (default 120 ms, `{"drop_ms":N}`).
  It is **held** (presented again) when the clock outruns the frame by more than one
  frame interval (`repeat`), which is what a starved decoder looks like.
* `status_json` exports cumulative `presented`, `dropped`, `repeated`, `max_drift_ms`,
  `mean_abs_drift_ms`. These are the numbers the report quotes.

## 5. Seek

`mode 0` = accurate: `av_seek_frame(..., AVSEEK_FLAG_BACKWARD)` to the keyframe before the
target, then decode forward discarding until `pts >= target`. `mode 1` = fast: land on the
keyframe and present from there. Both flush every decoder, flush the sinks, and reset the
clock to the landing pts. The landing pts is returned via `status_json.last_seek_landed_ticks`
so the oracle can compare it with `ffprobe -read_intervals` keyframes.

## 6. Subtitles

Two paths, both in the core (the sink only gets pixels):

* **Text** (`subrip`, `ass`, `mov_text`, `webvtt`, `text`): the cue's raw packet bytes are
  exposed as `sppe_sub_text()` and, for `ass`/`ssa`, handed to **libass** which renders an
  RGBA overlay pushed to `subtitle_overlay` at the video's display size.
* **Bitmap** (`hdmv_pgs_subtitle`, `dvb_subtitle`, `xsub`): the decoded rect (w×h, 8-bit
  index) + palette (`nb_colors*4`, BGRA) are expanded in the core to RGBA and pushed as an
  overlay at `(x,y)` from the rect.

`sub_primary` + `sub_secondary` are both rendered — the legacy fork's P0 was that the
second track never reached the app. Forced-only tracks honour
`AV_DISPOSITION_FORCED`.

Remote sources, inline ingest, font caps and live cue overrides: **§16 (v1.2.0)**.

Fonts: `config_json {"fonts_dir": "..."}` → `ass_set_fonts_dir`. Without it libass uses
the system fontconfig. **Embedded MKV font attachments are installed into a private temp
dir** and that dir is set as the fonts dir — the legacy player never did this, which is why
fansubbed signs rendered in the wrong font.

## 7. HDR / Dolby Vision passthrough

`info_json` carries, per video stream, a `hdr` object with exactly the fields the Apple
task needs to build the CMSampleBuffer attachments:

| field | source |
|---|---|
| `transfer` | `AVCOL_TRC_SMPTE2084` → `"pq"`, `ARIB_STD_B67` → `"hlg"`, else `"sdr"` |
| `primaries`, `matrix`, `range` | `AVCodecParameters` colour fields |
| `mastering.{prim_x,prim_y,wp_x,wp_y,min_lum,max_lum}` | `AV_PKT_DATA_MASTERING_DISPLAY_METADATA` side data |
| `cll.{max_cll,max_fall}` | `AV_PKT_DATA_CONTENT_LIGHT_LEVEL` side data |
| `dovi.{profile,level,bl_compatibility_id,rpu_present}` | `AV_PKT_DATA_DOVI_CONF` side data / `AVDOVIDecoderConfigurationRecord` |

The same struct is passed to `video_set_hdr` before the first presented frame, so the sink
can configure the display layer once and never flip.

**Not carried:** HDR10+ dynamic metadata. FFmpeg gives it per-packet; no Apple/Android
display layer accepts it. Recorded in `info_json` as `hdr10plus_present` only.

## 8. Software fallback

| codec | software path |
|---|---|
| H.264 / HEVC / VP9 / MPEG-2 | FFmpeg's own decoders (always built in) |
| AV1 | FFmpeg's `libdav1d` decoder (our build has dav1d 1.5.4) |

Triggers, all counted and logged: `hw_probe == 0`; `hw_open == NULL`;
`hw_receive < 0` at runtime after at least one good frame; `config {"force_sw":true}`.
Reopen is one-way per stream for the session (no ping-pong); `status_json.fallbacks[]`
lists `{stream, reason, at_ticks}`.

## 9. Threading and ownership

* **One instance = one thread.** No internal threads, no locks. The mobile shell owns a
  worker thread and calls `sppe_pump()` from it. This is what makes ASAN and the fuzzer
  meaningful.
* Frames are engine-owned for the duration of one `sppe_pump` call; `hw_frame_free` is
  called with the exact `handle` the backend produced, inside the same call.
* Strings returned (`info_json`, `status_json`, `last_error`) are valid until the next call
  that regenerates them.

## 10. What TPlayer / IOSLegacy did, and what we keep or drop

| Behaviour | Legacy location | Verdict |
|---|---|---|
| Primary + secondary subtitle, both rendered | fork `AvSubtitleTrack` (`+825` in `master-sp`) | **keep** — the mobile app never had it, we do |
| Bitmap subs delivered with palette, not pre-blended | fork `AvSubtitleEventArgs` | **keep** — needed for PGS at arbitrary display sizes |
| Subtitle delay applied after cue creation, negative clamped & remembered | `SubtitleProvider.h:100-160` | **keep** |
| `PreventModifiedSubtitleDurationOverlap` cue clipping | `SubtitleProvider.h` | **keep** |
| Soft subtitles rendered by the app on a Win2D canvas | `Features/SubtitleFeature.cs` (2,127) | **drop** — libass + an overlay layer does it, in the core |
| Playback via AVPlayer | `Platform/IOSLegacy` | **drop** — the whole point of #23c |
| Per-frame `readCallback` byte counter | `FFmpegReader.cpp:553` | **drop** — count in the AVIO shim (P0) |
| Background audio / Now Playing / PiP | IOSLegacy `AppDelegate` | **backend** (Apple), not the core |
| `catch { return null }` around every media open | IOSLegacy `Player` | **drop** — the engine returns typed errors |
| Embedded fonts in MKV attachments | *never done* | **add** |
| Forced-subtitle disposition | *partial* | **keep + use** |

## 11. Oracles

| oracle | what it proves |
|---|---|
| `ffprobe -of json` (same n9.0.2 build) | info, streams, chapters, attachments |
| `ffmpeg -f framemd5` (software decode) | the software path is byte-exact, per frame |
| `libass` reference render (`ass_render` → PNG) | overlay pixels match libass exactly |
| `ffmpeg -f srt` | text cue times |
| `ffprobe -read_intervals` keyframe list | seek landing, fast and accurate |
| fake-backend presented-pts log | max drift, drops, repeats over the corpus |

## 12. Out of scope (stated, not silently skipped)

* iOS/tvOS cross-compile is **link-checked only if the Apple xcframeworks exist on dist**.
  They were 404 when this task was written and went **live during it (2026-11-19)**, so the
  iOS arm64 link check WAS performed on .25 (Xcode 27.2, iPhoneOS27.2 SDK, minos 15.0):
  `apple-ios-arm64/lib*.dylib`, Mach-O arm64, 43/43 exports, no undefined symbols.
  tvOS is **not** link-checked — the tvOS slice of each framework is on dist, but nothing in
  this core is tvOS-specific, so it is the Apple backend task's job. No device run.
* No device run anywhere. No playback of a real DRM stream. No AirPlay.
* Dolby Vision **decoding** is not ours: DV profile 5/8 base layer is HEVC and decodes
  normally; the DV metadata is carried for the display layer to consume. RPU parsing is
  FFmpeg's.

## 13. This core is THE core (ADR-0001) — and the open defects it must close

[`docs/ADR-0001-one-core-per-platform.md`](docs/ADR-0001-one-core-per-platform.md) decides
that **this engine is the playback core for every self-presenting platform** — Linux
(x86_64 + aarch64/Pi5), Android, Android TV, iOS/iPadOS, macOS, tvOS — and that Windows/Xbox
stay on `sppb_` + the WinRT component until four checkable conditions hold (ADR §5).

The repo name still says `ios-android` because the `sppe_` prefix is the shipped ABI; the
scope is the ADR, and the ADR is authoritative over this SPEC where prose differs.

The same document records **three measured defects in this core** that Phase B must close
before any backend is built on it:

| | Defect | Evidence |
|---|---|---|
| §3.1 | frame pts are **not** normalised by the container's `start_time` — last frame of `corpus/mpeg2.ts` presents at 16.40 s of a 15.01 s file | `sppe` 1.44 s first pts vs `sppb` 0.0 s |
| §3.2 | accurate seek compares a **shifted** `av_seek_frame` target against **unshifted** frame pts — request 10.0 s lands at 11.52 s | same file; both engines agree to the tick on a `start_time = 0` file |
| §3.3 | `sppe_seek(e, t, 1)` reports the **request** as the landing, always | 0.0/5.0/10.0 for 0.0/5.0/10.0; `sppb_seek_fast` really lands (10.5 s → 12.0 s) |

and **ABI 2** (ADR §7): an additive tail on `sppe_backend` for vsync pacing,
per-frame HDR switch, SPDIF passthrough transport, discontinuity, one shared hw device,
dmabuf export, and an `AVPacket` submit that removes the per-backend bitstream parser.
**ABI 1 backends keep working unchanged** — the core must accept `abi` 1 *and* 2 and append
only.

Reproduce every number with `bash docs/measure-cores.sh`.

## 14. HDMI bitstream passthrough — ABI 2 (v1.1.0, 2026-11-21)

**Contract** — ADR-0001 §7.2, now real in `include/sppe.h`:

- `SPPE_BACKEND_ABI` = 2, the core accepts **1..2** (`SPPE_BACKEND_ABI_MIN`). The v2 tail is
  appended after `subtitle_clear`; the core reads **no** v2 field unless `abi >= 2`
  (`SPPE_BE_V2`). An ABI-1 backend (shipped Apple v1.0.0, Android v1.0.1, Linux v1.0.0) installs
  unchanged and gets exactly the v1.0.0 behaviour.
- Of the tail the core **calls** only `audio_configure_ex` and `audio_discontinuity` (after every
  seek). `video_present2`, `video_set_hdr2`, `video_vsync_period_ns`, `hw_device_*`,
  `hw_frame_export`, `hw_submit_packet` are declared, not called yet.
- Config `"passthrough":"ac3,eac3,dts,truehd"` (or `"all"`) = the shell's wish list. Default `""`
  = always decode. The sink has the final word.

**Path** (`src/sppe_pt.c`): once per selected audio stream, if the codec is AC-3 / E-AC-3 / DTS /
TrueHD, wanted, and the backend is ABI 2 with `audio_configure_ex`, the core calls it with
`sample_fmt = AV_SAMPLE_FMT_S16` and the **IEC 61937 transport** rate/channels:

| codec | transport rate | channels |
|---|---|---|
| ac3, dts | codec rate (48 kHz) | 2 |
| eac3 | 4 × codec rate (192 kHz) | 2 |
| truehd | 4 × codec rate (192 kHz) | 8 (HBR) |

0 = accepted: the decoder is never opened; every compressed packet goes through FFmpeg's own
`spdif` muxer (`libavformat/spdifenc.c` in our n9.0.2 — E-AC-3 6-frame aggregation, TrueHD MAT
packing, DTS type selection are its job, not re-implemented) into a memory AVIO, and the bursts
reach `audio_write` with `planes[0]` = S16LE bytes, `linesize[0]` = byte count, `nb_samples` =
transport frames. The burst pts = the pts of the first packet aggregated into it, so a sink's
`first_pts + frames/transport_rate` is the same clock as PCM. Non-zero = refused → the PCM path,
unchanged. A muxer failure mid-stream records a fallback (`SPPE_HW_RUNTIME_ERROR`) and calls
`audio_configure` so the sink switches back before the first decoded frame. A seek rebuilds the
muxer (aggregation state is not trusted across a discontinuity).

`sppe_status_json` gains `"audio_out":"pcm"|"bitstream:<fmt>"`, `"audio_transport":{rate,
channels,bursts,bytes}` and `"backend_abi"`.

**Tests**: `tests/c_fixtures.c` §5 drives the fake backend as an HDMI sink (`"spdif":"…"` =
what it accepts, `"abi":1` = pretend to be an old backend): ac3/eac3/dts/truehd accepted with the
right transport rate/channels, **every** write starting with Pa/Pb `0xF872 0x4E1F`, zero PCM
configures, the sink clock reaching ≥ 7 s of the 8 s corpus files; sink-refused / shell-unwanted /
non-bitstream codec → PCM; an ABI-1 backend installs on this core and never sees
`audio_configure_ex`; seek during E-AC-3 → `audio_discontinuity` + bursts resume with intact
preambles. CLI: `sppe play <file> --passthrough eac3 --spdif eac3`.

**Not proven here (hardware):** that a real receiver locks. That is the Linux backend's job on the
Pi5 → BRAVIA → HT-A7000 (`…-linux-backend-c-egl-pipewire` v1.1.0, PipeWire iec958).

## 15. The three ADR-0001 §3 defects — fixed in v1.1.0 (2026-11-21, UNBUILT)

- **§3.1 timeline is zero-based.** `sppe_pts()` / `sppe_pts_ticks()` (`src/sppe_util.c`) subtract
  `start_time_ticks` (never a negative start). Every pts that leaves the core goes through it:
  video frames (software path and the hw path — the backend scales the RAW packet pts it was given,
  the core shifts the result), PCM audio writes, IEC 61937 burst pts, subtitle cues, chapters, the
  accurate-seek comparison. `sppe_tools.c` (framemd5) is untouched on purpose: it mirrors
  `ffmpeg -f framemd5`, which prints stream-timebase pts.
- **§3.2 accurate seek** now compares the zero-based frame pts with the zero-based request (the
  `av_seek_frame` target was already shifted by `start_time_av`). Oracle row
  `oracle_seek_start_time` on `corpus/mpeg2.ts` (start 1.429978 s): 0/5/10 s land within a frame,
  first presented pts ≈ 0, last inside the duration.
- **§3.3 fast seek** decodes to the first frame after `av_seek_frame` and reports **that** pts as
  `last_seek_landed_ticks`; the oracle now asserts landed == the keyframe at/before the target
  (v1.0.0's oracle asserted landed == target, i.e. it enshrined the defect). The FFmpegInteropX
  20 % overshoot heuristic is not ported.
- `oracle_sync` subtracts the container start_time from ffprobe's `pts_time` (tolerance 2 ticks).

## 16. v1.2.0 — remote-safe subtitles + live cue overrides (2026-11-27)

**Additive only.** 65 → **68 exports**; `SPPE_BACKEND_ABI` stays **2** (accepts 1..2); no
existing export changed signature or meaning, no vtable field added.

### 16.1 Upstreamed from the Apple backend's vendored core (v1.1.2 `f7b86d1`/`9689303`, v1.1.3 `6719215`)

The Apple backend shipped these first under `Sources/CScorpioPlayerEngine/`; they are now the
canonical core, so `scripts/sync-core.sh` in the Swift repo is lossless again.

| Fix | Where | What |
|---|---|---|
| remote flag | `sppe_api.c`, `sppe_internal.h` | `e->is_remote` = 1 for `http(s)/rtsp/rtmp/mms` URLs and **every `sppe_open_io`** (an io source is a stream the shell feeds). New config key `"remote": true|false` overrides it (e.g. an Android content-fd of a local file can ask for the full scan back). `status_json` reports `remote` and `subs_scanned`. |
| inline subtitle ingest | `sppe_core.c demux_one`, `sppe_subs.c sppe_subs_ingest_packet` | On a remote source the **selected** subtitle streams are decoded as the demuxer reaches their packets (deduplicated over the last 64 cues, so a seek back does not double them). The one-pass rewind-and-scan cost 14–18 s of HTTPS range reads on a multi-GB MKV. Local sources keep the scan (and are NOT ingested inline — that would duplicate the scan's cues). Proof: `c_fixtures` "inline-ingested cues == scanned cues". |
| zero-spin subtitle pump | `sppe_subs.c render_one / sppe_render_subtitle` | An unchanged cue returns `SPPE_AGAIN` with *active* set (so it is not cleared), per §6 / `sppe.h` ("SPPE_AGAIN = nothing changed"). Before, it returned OK and `sppe_pump` spun at 100 % CPU for the whole cue. |
| pump nap | `sppe_core.c sppe_pump` | idle nap is min(5 ms, time left) instead of a flat 2 ms. |
| font cap | `sppe_subs.c sppe_ass_init` | ≤ 16 MiB and ≤ 24 faces from `fonts_dir` + MKV attachments; a single file ≤ 16 MiB. On `__APPLE__` ONE system sans-serif (HelveticaNeue.ttc …) instead of walking `/System/Library/Fonts` (378–564 MB into heap on the first cue → iOS Jetsam). Elsewhere `/usr/share/fonts` is walked only when nothing else supplied a default face. Plain POSIX paths; the core still has no platform headers. |
| HTTP | `sppe_api.c sppe_open_path` | `reconnect`/`reconnect_streamed`/`reconnect_delay_max=5`; config `"http_headers"` (alias `"headers"`, CRLF-separated) forwarded to avformat; with no `ca_file`, the first readable of `/etc/ssl/certs/ca-certificates.crt`, `/etc/ssl/cert.pem`, `/etc/pki/tls/certs/ca-bundle.crt` is used for https. `get_config` reports `http_headers_set` (never the header values — they may be credentials). |

### 16.2 Remote stall guard in the cue getters

`sppe_sub_count`, `sppe_sub_json`, `sppe_sub_text`, `sppe_next_subtitle` and
`sppe_render_subtitle` call `sppe_subs_ensure()`, which **does not scan** when the source is
remote or the stream is external: they serve the cues already in the table. Proof
(`c_fixtures` §7): through `sppe_open_io`, all five getters plus `sppe_sub_peek_window` leave
`subs_scanned == 0` and read **zero bytes** past the probe (max read offset and backward-seek
count unchanged).

### 16.3 Live cue overrides — the three new exports

```c
int sppe_sub_peek_window(sppe_t*, int stream_index, int64_t from_ticks, int64_t to_ticks,
                         char *out_json, int cap);           /* >=0 cue count | <0 */
int sppe_sub_set_cue_override(sppe_t*, int stream_index, int cue_ordinal,
                              const char *utf8_text);        /* NULL clears */
int sppe_sub_clear_overrides(sppe_t*, int stream_index);     /* <0 = all; >=0 count cleared */
```

* **Ordinals are per stream** (0-based index into that stream's cue table) and stable — cues
  are only appended. They are *not* the cross-stream ordinals of `sppe_sub_json`.
* `peek_window` never scans, seeks or reads; it lists TEXT cues overlapping the window
  (delay applied), in start order, as
  `{"stream","ordinal","start_ms","end_ms","start_ticks","end_ticks","text","ass"[,"override"]}`.
  `text` is plain (ASS `{tags}` stripped, `\N` → newline) — what a translator wants; `ass` is
  the ASS Text field. Bitmap cues are never listed. Cap too small → `SPPE_ERR_ARG`, `out_json=""`.
* `set_cue_override` stores the display text **beside** the immutable `text`/`ass`
  (`sppe_cue.override`); `\n`/`\r\n` → `\N`. It replaces only the Dialogue **Text field**, so
  the cue's style, margins and position are kept — `"Original\nTranslated"` renders as a
  two-line cue in place, as ONE overlay (no dual-layer collision in the Apple backend's single
  overlay layer). The libass track of every layer showing the stream is rebuilt and the overlay
  cache invalidated, so the next `sppe_render_subtitle`/`sppe_pump` pushes the new pixels.
  Max 8192 bytes; bitmap cue → `SPPE_ERR_UNSUPPORTED`.
* `clear_overrides` frees them and invalidates the same way; clearing restores the **exact**
  original RGBA (FNV-1a CRC equal — `c_fixtures` §6).
* Threading is unchanged (§9): one instance, one thread. A shell that translates on a
  background queue must call `set_cue_override` on the engine's thread (the same queue that
  calls `sppe_pump`). Overrides are freed with the cue table (`sppe_close`, stream teardown).
