# 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
```

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`.

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.
