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

The **Android backend** for the mobile playback **core** (`sppe_`, SCORPIO PLAYER 2027
row 23c). This repo is the thin layer between a pure C11 engine and Android; it has no
playback policy of its own.

## 1. Boundary

```
scorpiox-scorpioplayer-ffmpeg-ios-android-playback-engine      (C, vendored here, pinned)
    demux · master clock · A/V sync · track selection · seek · buffering
    subtitle decode + render (libass / PGS -> RGBA) · audio decode -> PCM · sw fallback
                     │  17-entry sppe_backend vtable, ABI 1
                     ▼
scorpiox-scorpioplayer-…-android-backend-kotlin                 (this repo)
    AMediaCodec -> ANativeWindow (Surface) · AAudio sink + clock
    sws_scale -> Surface for software frames · subtitle RGBA hand-off
                     │
                     ▼
Kotlin: SppeEngine (thread + Surface + passthroughs), SubtitleOverlayView (draws RGBA)
                     │
                     ▼
Compose / View shell — buttons only
```

The vtable is documented in the core's `SPEC.md` §3 and must not be redefined here.

## 2. What this repo may and may not do

**May** convert, upload and place: MediaCodec configuration (CSD, colour format), Surface
geometry and dataspace, output-buffer release-with-render, AAudio stream lifecycle and
buffer writes, `sws_scale` into a locked window, copying RGBA into a view.

**May not** decide: when a frame is due, which track plays, where a seek lands, how a
subtitle is timed, whether to fall back to software. Those arrive as calls with arguments
already decided. The test is mechanical — if a change needs `sppe_clock_now` or cue times,
it belongs in the core.

## 3. Threading

The core documents **one instance = one thread** (`sppe.h`). `SppeEngine` therefore owns one
single-thread executor: the pump timer runs there, and every public call hops onto it. Before
`startPumping()` the calls run inline (still one at a time). `onStats` / `onVideoSizeChanged`
fire on the pump thread and must hop before touching a View.

## 4. Hardware decode

`hw_probe` returns **0** when there is no decoder for the MIME, no Surface, or software was
forced. That is a normal outcome, not an error: the core selects its own decoder and records
a fallback. AV1 on an emulator or an older SoC lands here every time.

Probing is done by `AMediaCodec_createDecoderByType` — the NDK's public headers do not export
`AMediaCodecList`, so "ask the list" is not available to an app. Creating and deleting the
codec is the authoritative probe and costs one allocation per probed stream.

Pixel format is P010 for >8-bit content (`bit_depth > 8`), because asking MediaCodec for
8-bit silently truncates HDR to SDR with no error. **In Surface mode the colour format is not
set at all** — it is a byte-buffer-mode key and setting it makes some implementations
configure successfully and then never emit a frame (§11, P0-2).

### The sample form must match the CSD form (P0-1)

FFmpeg's MP4 demuxer produces an `avcC`/`hvcC` **configuration record** as extradata and
**length-prefixed** NAL units in packets. MediaCodec, once `csd-N` carries Annex-B, expects
Annex-B in every sample. Getting this mismatch wrong is invisible: `configure()` returns
`AMEDIA_OK`, every `queueInputBuffer` is accepted, and `dequeueOutputBuffer` returns
`TRY_AGAIN_LATER` until the end of the file. Measured 2026-11-20: 500 inputs, 0 outputs.

So `set_csd()` parses the record into one start-code-prefixed buffer per NAL, and
`hw_submit()` converts each sample from length-prefixed to Annex-B using `nal_len_size`,
which is read from the record (`avcC` byte 4, `hvcC` byte 21; `hvcC[22]` — not 21 — is
`numOfArrays`, a detail that cost a run). A byte-stream container (MPEG-TS) has Annex-B on both sides and
needs no conversion.

Also: **`KEY_PROFILE`/`KEY_LEVEL` must not be filled from FFmpeg's numbers.** MediaCodec uses
its own enums (`AVCProfileHigh` = 8, `AVCLevel41` = 0x1000); FFmpeg reports H.264's numeric
ids (100, 41). Writing those makes the decoder configure and emit nothing (P0-3).

`hw_flush` means **end of stream**: queue an empty input buffer with
`AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM`, then let `hw_receive` drain what the codec holds.
Using it as "discard" deletes the last frames of every file — a P0 the core already paid for
once.

## 5. Presentation

MediaCodec decodes **into** a Surface, so `AMediaCodec_releaseOutputBuffer(…, render=true)`
*is* the presentation. `video_present()` still runs afterwards, and here it is bookkeeping:
the core keeps its own frame/drift counters and they stay meaningful.

Software frames are real pixels in our address space, so `video_present()` on the software
path blits: `sws_scale` → RGBA → `ANativeWindow_lock/unlockAndPost`. This is what makes a
codec MediaCodec refuses (the AV1 row) still produce a picture, and it is the path the
forced-software test measures.

## 6. Subtitles — measured, not assumed

The core renders the overlay to straight-alpha RGBA in **video pixels**. Where those pixels
should be drawn is the one platform question that cannot be reasoned about:

* iOS: five layer arrangements were invisible and only alpha-blending into the presented
  frame worked. The Apple backend blends.
* **Android: a `SurfaceView`'s BufferQueue is composited by the system compositor BELOW the
  app window, with a hole punched in the window. Any view drawn in the window stack at that
  position composites on top of the decoded frames, including translucent pixels.**

`SubtitleOverlayView` draws there, positioned on the **picture rectangle** (aspect-fit maths),
not the view rect — the letterboxing trap the Apple backend hit. The instrumented test
`overlay_view_composites_over_the_video_surface` pushes a synthetic half-opaque / half-50 %
overlay, `PixelCopy`s the real window, and asserts green pixels are present in the composite.

**MEASURED on the `.25` emulator (API 36, arm64): green fraction 0.257 (3468 of 13500 sampled
pixels), overlay rect `Rect(0, 896 - 540, 1301)` inside a 1080×2400 window — i.e. the view
composites over decoded frames, translucent pixels included.** If a device ever disagrees, the
fallback is the Apple design (blend the RGBA into the frame); the backend already holds the
pixels and that test is what would catch it.

One platform fact the core cannot know: libass has no font provider here, so it takes the
first font file in its configured directory as the default. `/system/fonts` sorted
alphabetically starts with `AndroidClock.ttf` (digits only) — libass then renders zero pixels
while reporting success. `SppeFonts` supplies a private directory whose first entry is
Roboto; apps can override it through the core's `fonts_dir` config.

## 7. HDR / Dolby Vision

`video_set_hdr` converts the core's metadata to an **ADataSpace** and calls
`ANativeWindow_setBuffersDataSpace` (API 28). Without it the compositor treats PQ pixels as
SDR and the picture is washed out with no error anywhere. Colour transfer / standard / range
also go into the MediaCodec format for API 28+.

Dolby Vision travels in the bitstream's DOVI record and survives MediaCodec. There is no
public attachment to invent and fabricating one would silently disable DV. **Untested**: no
corpus file carries an RPU (the core's own note).

## 8. Audio

Always interleaved float32 (the core resamples; the backend never does). AAudio low-latency
shared mode, buffer capacity ≈ ¼ s, writes chunked at 1024 frames. Backpressure: wait up to
500 ms for room, then drop and count — a stalled route must not freeze the player.

The clock is `AAudioStream_getTimestamp(CLOCK_MONOTONIC)`'s framePosition converted to ticks
and offset by the first buffer's pts. If the timestamp is unavailable the fallback is frames
written: less accurate, never a lie about the direction of time.

## 9. Failures that are not failures

| condition | meaning |
|---|---|
| `hw_probe == 0` | software decode selected (no decoder, no surface, or forced) |
| `hw_open == NULL` | software decode selected, reason recorded |
| no subtitle stream selected | subtitles off |
| `sppe_render_subtitle` returns `SPPE_AGAIN` | nothing changed since the last push |
| `AMEDIACODEC_INFO_TRY_AGAIN_LATER` before EOS | the codec wants more input |
| audio drop counter increments | the sink was full for 500 ms |

## 10. Proof obligations

Every number in `README.md` is produced by `selftest/src/androidTest/` on the `.25` emulator
(`Medium_Phone_API_36.0`, arm64, Android 16, page size 4096) plus the native build's own
`nm`/`readelf` checks:

| suite | tests | what it pins down |
|---|---|---|
| `PlaybackCorpusTest` | 10 | h264 500/500 frames, forced-software 500 blitted, HEVC10 HDR dataspace, AV1, subtitles (4 overlays), seek 20.0→20.0 s, overlay compositing 25.7 %, JSON contract, truncated file, surface re-attach |
| `PlatformCodecSanityTest` | 3 | the same file decoded by plain Java MediaCodec (500 frames) and by the NDK alone — the control that separated "our format is wrong" from "the device cannot" while chasing P0 #1 |

Hardware decode is **not** claimed as proven on silicon: the emulator's MediaCodec is
`c2.goldfish.*`, a software implementation, so a "hw" row here proves the MediaCodec
plumbing, not a SoC's decoder. The 16 KB page rule is satisfied by our own `.so` and is
**not** satisfied by the published FFmpeg Android tree (4 KB `LOAD` alignment) — that
blocker belongs to `scorpiox-ffmpeg-libav` and is stated in `docs/FFMPEG-RUNTIME.md`.

## 11. The four P0s, with the measurement that found each

Every one is a "configure succeeded, no error, zero output" failure — the worst class in a
media stack, because every layer reports success.

| # | symptom | cause | fix |
|---|---|---|---|
| 1 | 500 packets in, 0 frames out, forever | Annex-B CSD with length-prefixed samples | parse `avcC`/`hvcC` into `csd-N`; convert samples (`nal_len_size`) |
| 2 | same, with `KEY_COLOR_FORMAT` set | byte-buffer-mode key in Surface mode | only set it when there is no Surface |
| 3 | same, with profile/level set | FFmpeg numeric ids vs MediaCodec enums | do not forward them |
| 4 | subtitles: cue exists, 0 overlay pushes | libass default font = `AndroidClock.ttf` | `SppeFonts` puts Roboto first |

Three smaller ones: `setSurface()` before `open()` was dropped (every file fell back to
software with no window), `setForceSoftware()` before `open()` was dropped (the toggle did
nothing), and `AMediaFormat_toString()`'s return is **format-owned memory** — freeing it
aborts inside Scudo.

SPDX-License-Identifier: MIT
