S022: MSE spike findings, sized plan, mse smoke page

Prototype on branch s022-mse-proto (gst_mse backend, vendored script).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-12 10:56:24 -06:00
commit c44bcbd8ee
7 changed files with 271 additions and 7 deletions

View file

@ -72,6 +72,7 @@ Never modify: `~/Documents/Apps/Nacre` (the original Python Nacre, reference onl
| `tools/smoke.sh tests/smoke/settings.txt` (+ `SMOKE_SIZE=1280x1100`) | every settings section and sub-page dark and light, search results (`nacre://settings/?search=…`), narrow width; `settings-write.txt` (hidden, `SMOKE_SIZE=1280x1100`, fresh outdir) taps controls with selftest `tap x y`, then check `home/.config/nacre-servo/Default/settings.json` (expected values in its header) | now (S019) |
| `SMOKE_SIZE=1280x1600 tools/smoke.sh tests/smoke/sliders.txt` | controls hold still (R1-21): Interface size drag (value label while held, applied on release), Contrast live, Style chip pick; `SMOKE_VISIBLE=1 tools/smoke.sh tests/smoke/sliders-visible.txt` the same plus scrolling for the user's window (~772 px). Selftest `press`/`drag`/`release`, `scroll x y dy`; read the PNGs | now (R1-21) |
| `python3 tests/smoke/net/server.py &` + `tools/smoke.sh tests/smoke/net-{privacy,adblock,downloads}.txt` | network pass, offline: secure DNS through a local DoH stub (`*.nacre.test` → 127.0.0.1), HTTPS-only + certificate warning, tracking params, ad blocker with a local list, downloads + download manager stubs; the server's `/log` has requests, DNS names, Range headers, manager calls. `cache-restart.txt` with `SMOKE_HOME=<cache.txt outdir>/home`: disk cache. `net-real.txt` needs internet. `@HOME@` in scripts = the throwaway home | now (S007) |
| `tools/smoke.sh tests/smoke/mse.txt` | MSE: MediaSource + one SourceBuffer plays chunk-appended fMP4 and WebM (offline); passes only on a build with the MSE patches (branch `s022-mse-proto`, see docs/engine/mse-spike.md) | S022 prototype |
| `python tools/icons.py` | rebuilds the icon font subset and `src/ui/icons.rs` from `tools/icons.txt` (needs fontTools and Arch's ttf-material-symbols-variable) | now (S015) |
| appimagetool, wine + Inno Setup, VM "Windows 10" | packaging and Windows checks | see the user's global CLAUDE.md "Building" |

View file

@ -12,13 +12,13 @@ YouTube's player needs Media Source Extensions; Servo 0.7 has none, so videos sh
- References (read, port ideas, don't copy code): WebKitGTK's GStreamer MSE backend (`Source/WebCore/platform/graphics/gstreamer/mse/`), Firefox `dom/media/mediasource/` (MPL-2.0, same licence as Servo), Chromium only for the spec behaviour
## Steps
- [ ] Upstream check: does current Servo (git main, issues, PRs, servo-media) have MSE work? Note links, state, and whether it can be backported to 0.7
- [ ] Map the work for Servo 0.7: WebIDL + DOM (`MediaSource`, `SourceBuffer`, `SourceBufferList`, `URL.createObjectURL(MediaSource)`), byte-stream parsing (fMP4 init/media segments, WebM), feeding GStreamer (appsrc per track, buffered ranges, seeking, `endOfStream`), `isTypeSupported` codecs (VP9, AV1, H.264, Opus, AAC through the installed GStreamer plugins)
- [ ] Decide how Nacre would carry the change: vendored `script` / `servo-media` crates via `[patch.crates-io]` like servo-net (D-012), and measure the rebuild cost of a vendored `script` crate
- [ ] Prototype the smallest path: `MediaSource` + one `SourceBuffer` that plays a local fMP4 or WebM clip appended in chunks (`tests/smoke/pages/mse-basic.html`, clip generated with ffmpeg); a smoke shot shows the clip playing (currentTime advances)
- [ ] Try YouTube with the prototype (heavy-web.txt YouTube steps): record exactly how far it gets and what breaks next
- [ ] Windows: what GStreamer the Windows build needs (bundled runtime size, plugins) for MSE playback
- [ ] Write `docs/engine/mse-spike.md`: findings, sized task list (sessions per part), risks, recommendation; then 🧑 ask the user (through the orchestrator) go / no-go
- [x] Upstream check: does current Servo (git main, issues, PRs, servo-media) have MSE work? Note links, state, and whether it can be backported to 0.7
- [x] Map the work for Servo 0.7: WebIDL + DOM (`MediaSource`, `SourceBuffer`, `SourceBufferList`, `URL.createObjectURL(MediaSource)`), byte-stream parsing (fMP4 init/media segments, WebM), feeding GStreamer (appsrc per track, buffered ranges, seeking, `endOfStream`), `isTypeSupported` codecs (VP9, AV1, H.264, Opus, AAC through the installed GStreamer plugins)
- [x] Decide how Nacre would carry the change: vendored `script` / `servo-media` crates via `[patch.crates-io]` like servo-net (D-012), and measure the rebuild cost of a vendored `script` crate
- [x] Prototype the smallest path: `MediaSource` + one `SourceBuffer` that plays a local fMP4 or WebM clip appended in chunks (`tests/smoke/pages/mse-basic.html`, clip generated with ffmpeg); a smoke shot shows the clip playing (currentTime advances)
- [x] Try YouTube with the prototype (heavy-web.txt YouTube steps): record exactly how far it gets and what breaks next
- [x] Windows: what GStreamer the Windows build needs (bundled runtime size, plugins) for MSE playback
- [x] Write `docs/engine/mse-spike.md`: findings, sized task list (sessions per part), risks, recommendation; then 🧑 ask the user (through the orchestrator) go / no-go
- [ ] PROGRESS entry, DECISIONS (go/no-go), INDEX line, commit `S022: …` and push
## End criteria

156
docs/engine/mse-spike.md Normal file
View file

@ -0,0 +1,156 @@
# MSE spike (S022)
Can Nacre get Media Source Extensions into Servo 0.7, so YouTube (and Reddit's HLS player) play in the page?
Date: 2026-11-12. Prototype: branch `s022-mse-proto` on origin, worktree `~/Projects/Nacre-s022`.
## Answer
Yes. GStreamer ships its own MSE library, **gst_mse** (`libgstmse-1.0`, plugin `mse` with the `msesrc` element, since
1.24, Rust bindings `gstreamer-mse` 0.25 matching Servo 0.7's gstreamer-rs 0.25). It runs the MSE algorithms in C:
byte-stream parsing (fMP4, WebM, MPEG-TS), coded frame processing, track buffers, buffered ranges, eviction,
`remove`, `abort`, `timestampOffset`, append windows, duration and ready states. So Servo only needs a thin DOM and
a player source, not its own demuxer. The prototype is ~900 lines on top of vendored crates and:
- plays a chunk-appended local clip, fMP4 (H.264 + AAC) and WebM (VP9 + Opus): `tests/smoke/mse.txt` passes, and
the shots show frames with the clock running (1.68 s, 2.04 s);
- takes YouTube from "Your browser can't play this video" to its own player, with controls, captions, the
quality menu button and a `blob:` MediaSource src. In one run (AV1 + Opus picked) `currentTime` ran 0→12 s of
the 19 s video, with captions following, but showed no picture (no AV1 decoder installed). With VP9 + AAC (after
the decoder fix) it stays at readyState 0. That is gst_mse bug 3 below.
Three gst_mse 1.28.9 defects block YouTube. All three are in C code we can fix (see "Sized plan").
## Upstream state (step 1)
| Item | State | Notes |
|---|---|---|
| [servo#22416](https://github.com/servo/servo/issues/22416) | open since 2018, E-very-complex | Members (2025) prefer "Servo holds an opaque gst_mse handle and calls methods on it". |
| [servo#44403](https://github.com/servo/servo/issues/44403) | open, B-roadmap, assigned calvaris (2026-04) | Roadmap item "Implementing the Media Source API"; no code linked. |
| [servo#40423](https://github.com/servo/servo/pull/40423) | open draft (2025-11) | WebIDL + stubs (`todo!()`), gst_mse via a servo-media fork; isTypeSupported hard-coded. |
| [servo/media#458](https://github.com/servo/media/pull/458) | open, locked, conflicted; repo archived | MSE traits over gst_mse, ~450 lines. Media now lives in the servo monorepo. |
| [servo#47269](https://github.com/servo/servo/pull/47269) | closed unmerged 2026-08 (LLM-written, Servo's AI policy) | Own ISO BMFF/WebM parser feeding `servosrc`; one SourceBuffer, no coded frame processing. Ideas only. |
| Servo v0.8.0 (2026-11-09) | released | No MSE. |
Nothing can be backported. Nacre carries its own implementation (same direction as upstream), and drops it when
Servo ships MSE.
## How Nacre carries it (step 3)
`[patch.crates-io]` like servo-net (D-012): `vendor/servo-script`, `servo-script-bindings` (the WebIDL codegen lives
there), `servo-media` (Backend trait), `servo-media-player` (Player trait plus the `mse` traits),
`servo-media-gstreamer` (gst_mse backend and player), plus the new dependency `gstreamer-mse = 0.25`.
The prototype lives in a worktree with its own `target/` (a btrfs reflink copy of the main target, which takes 1 s).
Measured rebuilds (`nice cargo build --release -j 2`, warm target):
| Change | Rebuild |
|---|---|
| First build after vendoring the 5 crates | 593 s (24 crates: script and everything downstream) |
| Edit in `servo-script` / WebIDL | 566 s |
| Edit in `servo-media-gstreamer` only | 106 s (3 crates) |
Vendored `script` costs about 10 minutes per DOM edit. That is fine, but keep DOM edits batched.
## Prototype (step 4)
| File (branch `s022-mse-proto`) | What |
|---|---|
| `vendor/servo-media-player/mse.rs` | `MediaSourceBackend` / `SourceBufferBackend` traits, `MseEvent`, `StreamType::MediaSource`, `Player::set_media_source` (default: unsupported) |
| `vendor/servo-media/lib.rs` | `Backend::create_media_source`, `is_media_source_type_supported` (defaults: none) |
| `vendor/servo-media-gstreamer/mse.rs` | gst_mse wrapper: events from signals, `buffered` via FFI (no binding in 0.25), settle work-around |
| `vendor/servo-media-gstreamer/player.rs` | `mse://` uri, `source-setup` attaches the `GstMediaSource` to `msesrc`; seek and rate allowed |
| `vendor/servo-script-bindings/webidls/{MediaSource,SourceBuffer,SourceBufferList}.webidl`, `URL.webidl` | spec IDL (minus ManagedMediaSource, workers); `createObjectURL(Blob or MediaSource)` |
| `vendor/servo-script/dom/media/{mediasource,sourcebuffer,sourcebufferlist}.rs` | DOM mirror of the backend state, events through the media element task source |
| `htmlmediaelement.rs` | `blob:` URL of a MediaSource → MSE player, no fetch |
| `tests/smoke/mse.txt`, `pages/mse-basic.html`, `pages/mse-clip-{mp4,webm}.js` | offline smoke (clips are base64 scripts: Servo refuses `fetch`/XHR of `file://`) |
Spike shortcuts, which the real plans must replace: object URLs are never freed (pages revoke right after setting
`src`), every SourceBuffer counts as active, `mode = "sequence"` and `changeType` are stored only,
`removeSourceBuffer` only drops it from the list, `HTMLMediaElement.buffered` still comes from playbin (empty under
MSE, so YouTube's "buffer health" reads 0 s), there is no pref switch, and a `Trusted` in the event sink keeps each
MediaSource alive.
## YouTube with the prototype (step 5)
`watch?v=jNQXAC9IVRw`, hidden smoke run, direct connection:
1. Before the decoder fix: YouTube picks **AV1 + Opus** because `gst_media_source_is_type_supported` only checks
that it can parse the type. Arch has no AV1 decoder (no dav1d plugin). Audio runs, so `currentTime` goes 0→12 s
and the captions follow, but the video area stays empty and `videoWidth` is 0. Fixed in the prototype:
isTypeSupported also requires Servo's `can_play_type` (decoder present). Opus in WebM then reads unsupported
(Servo's registry scanner), so YouTube takes AAC.
2. After the fix: **VP9 (242) + AAC (140)**, two SourceBuffers. Both init segments are parsed, but msesrc creates
a stream for the video track only (the video init came 2 s before the audio's), so playbin waits at
readyState 0 with the spinner. gst_mse **bug 3**.
3. Across runs it is flaky (some runs stall at 2 s, one at 0). Also seen once: a later `js` probe never returned,
so the script thread may block. `GStreamerPlayer::setup` blocks the script thread until `source-setup` fires.
This needs a look in the real plan.
gst_mse 1.28.9 defects (read from its source, gst-plugins-bad `gst-libs/gst/mse/`, LGPL. Ideas only, no code copied):
1. **Early `update-end`**: `append_to_buffer_task_func` signals success once the bytes are pushed into the append
pipeline (`gst_append_pipeline_append`), before the end-of-append marker has been processed. `buffered` is
stale at every `updateend`, which is exactly when players read it. Prototype work-around: wait (≤ 250 ms) for
`buffered` to move. Proper fix: signal after the end-of-append message is handled (`consume_all_samples`).
2. **Idle ticks**: the same task emits `update` / `update-end` about every second with no pending data.
The prototype ignores them when no append is outstanding.
3. **Split A/V SourceBuffers**: msesrc exposes streams as soon as one SourceBuffer has its init segment. The spec
says HAVE_METADATA only after every SourceBuffer has received one, and WebKit waits for all of them. This blocks
YouTube, which always uses separate audio and video buffers.
What YouTube still lacks after MSE works: DRM videos (no EME, DESIGN.md), AV1 needs the dav1d plugin, and
PiP reloads the page in its own web view (D-008), so the MediaSource re-buffers there. Expected to work but
unverified: seeking, quality switches, live (`setLiveSeekableRange` is a no-op now).
## Windows (step 6)
- GStreamer packages the mse **library** in its binary installers since 1.24.2 ("Package new analytics and mse
libraries in binary packages") and the mse **plugin** (`msesrc`) since **1.26.11** (cerbero "gst-plugins-bad:
Ship the mse plugin"). The Windows build therefore needs the MSVC runtime ≥ 1.26.11, or 1.28.x.
- Official installers: 1.28.8 MSVC x86_64 is an exe of 517 MB (1.28 dropped merge modules), and 1.26.11 is an
84 MB msi. Nacre ships a subset next to `nacre.exe`: core, base, good (isomp4, matroska, vpx), bad (mse,
dav1d, codecparsers), libav, opus and the audio sinks. Estimate 80–150 MB unpacked. **Not measured or tried in the
VM yet.**
- Arch (1.28.9) already has everything except an AV1 decoder (`gst-plugin-dav1d`, or `gst-plugins-rs` dav1ddec).
An AppImage must bundle GStreamer ≥ 1.26.11 with the mse plugin, because older distros lack it.
## Sized plan (if go)
Each line is one session unless noted. Option A keeps gst_mse and fixes it, so the expensive parsing stays in
GStreamer.
1. **gst_mse fixes** (2 sessions): bugs 1–3 as a patch on gst-plugins-bad 1.28.9 `gst-libs/gst/mse` (C, LGPL).
Build our own `libgstmse-1.0.so` and `libgstmse.so` (the plugin), loaded from Nacre's lib dir ahead of the
system copy. Offer the patches upstream (an MR to GStreamer). A C unit test per bug, like the Python probes in
the spike.
2. **MSE DOM to spec** (2 sessions): ready-state and event ordering, duration change, `removeSourceBuffer`,
`activeSourceBuffers`, `changeType`, sequence mode, `abort`, `HTMLMediaElement.buffered`/`seekable` from the
MediaSource, object URL lifetime (Blob URL store entry, #40749), no `Trusted` leak, a `dom_media_source_enabled`
pref, and the WPT `media-source` subset as smoke.
3. **Player integration** (1 session): seeking through msesrc, playback rate, error paths. The script thread must
not block in `GStreamerPlayer::setup` (async attach). `isTypeSupported` codec table: Opus in WebM, AV1 with
dav1d.
4. **YouTube + Reddit pass** (1 session): heavy-web YouTube steps green (play, seek, quality menu, captions, PiP,
ad blocking), plus Reddit's HLS video (hls.js over MSE) and site-doctor's video sites.
5. **Packaging** (1–2 sessions): AppImage bundles GStreamer ≥ 1.26.11 with the mse plugin, our patched libgstmse and
dav1d. The Windows installer bundles the MSVC runtime subset; check playback in the VM (software rendering).
Total **7–8 sessions**. Option B (own MSE core in Rust: fMP4/WebM byte-stream parsers, coded frame processing and
track buffers feeding one `appsrc` per track, like WebKit's own GStreamer MSE) is the fallback if bug 3 can't be
fixed inside msesrc. It would add 5–6 sessions.
## Risks
- Patched gst_mse must ship as our own copy on every platform until upstream releases the fixes (version skew
with the system GStreamer on Linux; bundling avoids it).
- `script` rebuilds take about 10 minutes per DOM edit; a Servo upgrade means re-applying the vendored patches (as D-012).
- YouTube's SABR streaming and A/B tests change often; the flakiness seen in the spike may have more causes than
bug 3.
- No EME: DRM content stays unavailable.
- Windows GStreamer bundle size and software-GL video in the VM are unmeasured.
## Recommendation
**Go, option A.** The DOM plus backend are small (the prototype took one session), the hard part (coded frame
processing) already exists in gst_mse, and the three blockers are concrete and local. Start with plan 1 (gst_mse
fixes), because it decides whether option B is needed. Plans 2–3 can then run while YouTube is re-checked.

21
tests/smoke/mse.txt Normal file
View file

@ -0,0 +1,21 @@
# Media Source Extensions (S022 prototype, branch s022-mse-proto): mse-basic.html appends a clip to one
# SourceBuffer in 32 KiB chunks, ends the stream and plays. Passes when MediaSource exists, every chunk is
# appended, and currentTime advances. Offline. Run with tools/smoke.sh (needs a build with the MSE patch).
wait 3
open @PAGES@/mse-basic.html
waitload 30
assert typeof MediaSource === 'function'
waitfor 20 window.mse && window.mse.stage === 'ended'
waitfor 20 window.mse.time > 1.5
shot mse-mp4
assert window.mse.errors.length === 0
js JSON.stringify(window.mse)
open @PAGES@/mse-basic.html?webm
waitload 30
waitfor 20 window.mse && window.mse.stage === 'ended'
waitfor 20 window.mse.time > 1.5
shot mse-webm
assert window.mse.errors.length === 0
js JSON.stringify(window.mse)
status done
quit

View file

@ -0,0 +1,82 @@
<!doctype html>
<html>
<!-- MSE test (S022): a MediaSource with one SourceBuffer, fed mse-clip-mp4.js (fMP4, H.264 + AAC) or, with
?webm, mse-clip-webm.js (VP9 + Opus) in 32 KiB appendBuffer chunks. The clips are base64 scripts because
Servo refuses fetch() and XHR of file:// URLs. window.mse holds the state for
smoke asserts: stage, chunks appended, buffered end, currentTime, errors. -->
<head><meta charset="utf-8"><title>MSE basic</title>
<style>
body { margin: 0; background: #1d3b2a; color: #fff; font: 20px sans-serif; text-align: center; }
video { display: block; margin: 20px auto; width: 640px; height: 360px; background: #000; }
#log { font: 16px monospace; white-space: pre; text-align: left; width: 640px; margin: 0 auto; }
</style></head>
<body>
<div id="head">MSE BASIC</div>
<video id="v" muted></video>
<div id="log"></div>
<script>
const webm = location.search.includes('webm');
const file = webm ? 'mse-clip-webm.js' : 'mse-clip-mp4.js';
const mime = webm ? 'video/webm; codecs="vp9, opus"' : 'video/mp4; codecs="avc1.4d401f, mp4a.40.2"';
const mse = window.mse = { stage: 'start', chunks: 0, buffered: 0, time: 0, errors: [] };
const log = (line) => { document.getElementById('log').textContent += line + '\n'; };
const fail = (what) => { mse.errors.push(String(what)); log('ERROR ' + what); };
function load(url) {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = url;
script.onload = () => resolve(Uint8Array.from(atob(window.MSE_CLIP), (c) => c.charCodeAt(0)).buffer);
script.onerror = () => reject('load ' + url);
document.head.appendChild(script);
});
}
function update() {
const v = document.getElementById('v');
mse.time = v.currentTime;
mse.readyState = v.readyState;
document.getElementById('head').textContent =
'MSE ' + mse.stage + ' chunks ' + mse.chunks + ' buffered ' + mse.buffered.toFixed(2) +
' time ' + mse.time.toFixed(2);
}
async function run() {
if (!window.MediaSource) { mse.stage = 'no MediaSource'; return; }
mse.supported = MediaSource.isTypeSupported(mime);
log('isTypeSupported ' + mse.supported + ' ' + mime);
const data = await load(file);
const v = document.getElementById('v');
const ms = new MediaSource();
ms.addEventListener('sourceopen', () => {
mse.stage = 'open';
log('sourceopen readyState ' + ms.readyState);
let sb;
try { sb = ms.addSourceBuffer(mime); } catch (e) { fail(e); return; }
let offset = 0;
const next = () => {
if (sb.buffered.length) mse.buffered = sb.buffered.end(sb.buffered.length - 1);
if (offset >= data.byteLength) {
ms.endOfStream();
mse.stage = 'ended';
log('endOfStream buffered ' + mse.buffered + ' duration ' + ms.duration);
v.play().then(() => log('playing'), fail);
return;
}
sb.appendBuffer(data.slice(offset, offset + 32768));
offset += 32768;
mse.chunks++;
};
sb.addEventListener('updateend', next);
sb.addEventListener('error', () => fail('SourceBuffer error'));
next();
});
ms.addEventListener('sourceended', () => log('sourceended'));
v.addEventListener('error', () => fail('video error ' + (v.error && v.error.message)));
v.src = URL.createObjectURL(ms);
setInterval(update, 250);
}
run().catch(fail);
</script>
</body>
</html>

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long