S027: MSE DOM to spec (attach/detach, events through tasks, buffered/seekable, removeSourceBuffer, abort, changeType, sequence mode, object URLs per global, weak event sink, pref switch); gst_mse remove, abort, reset and appendWindowStart fixes; spec smoke cases and leak check

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-12 15:15:12 -06:00
commit 23964ea43f
26 changed files with 1866 additions and 229 deletions

View file

@ -87,8 +87,58 @@ like Servo's player (appsink sinks, `download` flag, 500 MiB `buffer-size`). The
15 runs failed while a smoke loop ran, 0 of 30 on an idle machine), so the evidence is Nacre's
`tests/smoke/mse.txt` `?split` page: 10 of 10 played with the patch, against 6 stalls in 23 runs before it.
## 5. remove() is a stub (S027)
**What.** `gst_source_buffer_remove()` returned TRUE and removed nothing, so `buffered` never shrank and players that
trim old media (YouTube does, to stay under quota) kept growing the buffer until eviction.
**Fix.** It removes, synchronously, every coded frame group (key frame to key frame) that lies inside `[start, end)`
from every track buffer (`gst_media_source_track_buffer_remove_range`, the helper eviction already uses), then
recomputes the size. A group that only overlaps the range stays, so no kept frame loses its key frame; the spec removes
partial groups up to the next random access point, so Nacre keeps slightly more than a spec browser. Nacre's backend
still reports `update`/`updateend` itself (the library signals nothing for a removal). **Test:** `/mse/remove`.
## 6. abort() breaks the source buffer (S027)
**What.** `gst_source_buffer_abort()` sent end-of-stream into the append pipeline's appsrc. Every later append then
failed, so a page that aborted (on a seek, a quality switch, `changeType`) could never append again.
**Fix.** abort drops the pending data; if an append is inside the pipeline it waits for it (new `appending` /
`abort_requested` flags and `append_done_cond`; the append task discards that append's result and signals nothing)
and then runs the spec's "reset parser state" (`reset_parser_state_unlocked`, as the append error path does) and
clears `updating`. The next append must start with an initialization segment (the reset forgets the old one; the spec
keeps it). **Test:** `/mse/abort-then-append`.
## 7. Parser reset leaves the old appsinks in the append pipeline (S027)
**What.** `gst_append_pipeline_reset()` emptied its track list but left the tracks' appsinks in the bin. The next
initialization segment named its appsink `video-0` again, `gst_bin_add()` refused the duplicate and freed it, and
`add_track()` used the freed element: a crash on the first append after any reset (abort, changeType, append error).
**Fix.** The reset sets each old appsink to NULL and removes it from the bin first. **Test:** `/mse/abort-then-append`
(abort after the init segment was parsed, then append; crashed before).
## 8. Track feeds keyed by object, not by track id (S027)
**What.** After a reset, the new initialization segment brings new `GstMediaSourceTrack` objects with the same ids.
`track_buffers` is keyed by id and finds the existing buffer, but `track_feeds` used `g_direct_hash`, so the new
samples hit `get_track_feed_unlocked: assertion ... failed` (fatal in the tests).
**Fix.** `track_feeds` uses the same id hash and equality as `track_buffers`, so samples after a reset reach the
existing feeds and msesrc's streams. **Test:** `/mse/abort-then-append`.
## 9. appendWindowStart refuses every valid value (S027)
**What.** `gst_source_buffer_set_append_window_start()` failed when `start <= append_window_end`, the inverse of the
spec's check, so any start below the end (all valid ones) gave a TYPE error. `SourceBuffer.abort()` resets the window
to `0..+inf`, so it failed too.
**Fix.** The check is `start >= append_window_end` (an end of `GST_CLOCK_TIME_NONE` is +infinity in the unsigned
compare). **Test:** `/mse/remove` sets the window.
## Found, not fixed here
- `gst_source_buffer_remove()` is a stub in 1.28.9: it returns TRUE, removes nothing and signals nothing. Nacre's
backend (`vendor/servo-media-gstreamer/mse.rs`) reports the removal as finished itself so pages get `updateend`.
Coded frame removal belongs in the library (follow-up).
- `gst_source_buffer_change_content_type()` always fails (NotSupported). Nacre's backend accepts a change within the
same container (parser reset, the next init segment may bring other codecs) and refuses another container.
- `timestampOffset` is a `GstClockTime` in the API: negative offsets clamp to 0.
- Duration: `gst_media_source_end_of_stream()` doesn't apply the spec's duration change; Nacre's DOM does.

View file

@ -9,12 +9,19 @@
* urisourcebin activated its typefind hung in about one fresh process of
* eight (msesrc pad task, patch 4)
*
* /mse/remove remove() drops the coded frame groups inside the range (a stub in 1.28.9);
* set_append_window_start() takes a start below the end (refused all)
* /mse/abort-then-append abort() mid-append resets the parser; the next append works (1.28.9 sent
* end-of-stream into the append pipeline, so every later append failed);
* again after the init segment was parsed (the reset left the old appsinks
* in the pipeline and the next one crashed on a name clash)
*
* Built and run by `tools/gst-mse.sh test` against target/gst-mse (GST_PLUGIN_PATH, own registry).
* Clips in data/ (TESTS_DATA_DIR), made with ffmpeg:
* video-vp9.webm testsrc2 320x180 30 fps 5 s, libvpx-vp9, no audio
* audio-aac.mp4 sine 440 Hz 5 s, aac 64k, fragmented (frag_keyframe+empty_moov+default_base_moof, 1 s)
* Running the binary with LD_LIBRARY_PATH=/usr/lib and GST_PLUGIN_PATH unset tests the system copy instead
* (all three fail there).
* (all of them fail there).
*/
#include <stdlib.h>
@ -201,6 +208,113 @@ test_no_idle_updates (void)
counter_clear (&c);
}
/* Seconds buffered from the start of the first range to the end of the last one, 0 if none. */
static gdouble
buffered_span (GstSourceBuffer * buffer, guint * n_ranges)
{
GArray *ranges = gst_source_buffer_get_buffered (buffer, NULL);
gdouble span = 0;
*n_ranges = ranges ? ranges->len : 0;
if (*n_ranges > 0) {
GstMediaSourceRange *first = &g_array_index (ranges, GstMediaSourceRange, 0);
GstMediaSourceRange *last =
&g_array_index (ranges, GstMediaSourceRange, ranges->len - 1);
span = (gdouble) (last->end - first->start) / GST_SECOND;
}
g_clear_pointer (&ranges, g_array_unref);
return span;
}
static void
test_remove (void)
{
Lone lone;
Counter c;
counter_init (&c);
lone_setup (&lone, AUDIO_TYPE);
watch (lone.buffer, &c);
g_assert_true (gst_source_buffer_append_buffer (lone.buffer,
clip ("audio-aac.mp4"), NULL));
g_assert_true (wait_update_ends (&c, 1, 10));
guint n;
gdouble before = buffered_span (lone.buffer, &n);
g_assert_cmpfloat (before, >, 4.0);
GError *error = NULL;
g_assert_true (gst_source_buffer_remove (lone.buffer, 0, 3 * GST_SECOND,
&error));
g_assert_no_error (error);
gdouble after = buffered_span (lone.buffer, &n);
g_assert_cmpuint (n, >, 0);
g_assert_cmpfloat (after, <, before - 1.5);
/* The append window setters (start was refused for every value below the end). */
g_assert_true (gst_source_buffer_set_append_window_start (lone.buffer,
GST_SECOND, &error));
g_assert_no_error (error);
g_assert_true (gst_source_buffer_set_append_window_end (lone.buffer,
10 * GST_SECOND, &error));
g_assert_no_error (error);
g_assert_false (gst_source_buffer_set_append_window_start (lone.buffer,
20 * GST_SECOND, NULL));
g_assert_true (gst_source_buffer_set_append_window_start (lone.buffer, 0,
&error));
g_assert_no_error (error);
g_assert_true (gst_source_buffer_remove (lone.buffer, 0,
GST_CLOCK_TIME_NONE, &error));
g_assert_no_error (error);
buffered_span (lone.buffer, &n);
g_assert_cmpuint (n, ==, 0);
lone_teardown (&lone);
counter_clear (&c);
}
static void
test_abort_then_append (void)
{
Lone lone;
Counter c;
counter_init (&c);
lone_setup (&lone, VIDEO_TYPE);
watch (lone.buffer, &c);
/* Half the clip, then abort while that append may still be in the parser. */
GstBuffer *whole = clip ("video-vp9.webm");
gsize size = gst_buffer_get_size (whole);
g_assert_true (gst_source_buffer_append_buffer (lone.buffer,
gst_buffer_copy_region (whole, GST_BUFFER_COPY_ALL, 0, size / 2),
NULL));
GError *error = NULL;
g_assert_true (gst_source_buffer_abort (lone.buffer, &error));
g_assert_no_error (error);
g_assert_false (gst_source_buffer_get_updating (lone.buffer));
gint ends = c.update_ends;
g_assert_true (gst_source_buffer_append_buffer (lone.buffer,
gst_buffer_ref (whole), &error));
g_assert_no_error (error);
g_assert_true (wait_update_ends (&c, ends + 1, 10));
g_assert_cmpint (c.errors, ==, 0);
guint n;
g_assert_cmpfloat (buffered_span (lone.buffer, &n), >, 4.0);
/* Abort with the init segment parsed (tracks exist), then append again: the
* reset must drop the old appsinks (crashed before, name clash). */
g_assert_true (gst_source_buffer_abort (lone.buffer, &error));
g_assert_no_error (error);
ends = c.update_ends;
g_assert_true (gst_source_buffer_append_buffer (lone.buffer, whole, &error));
g_assert_no_error (error);
g_assert_true (wait_update_ends (&c, ends + 1, 10));
g_assert_cmpint (c.errors, ==, 0);
lone_teardown (&lone);
counter_clear (&c);
}
/* playbin3 on mse:// set up like Servo's player (vendor/servo-media-gstreamer/player.rs): appsink
* sinks, the download flag, a 500 MiB buffer-size. */
typedef struct
@ -359,6 +473,8 @@ main (int argc, char **argv)
gst_init (&argc, &argv);
g_test_add_func ("/mse/update-end-after-parse", test_update_end_after_parse);
g_test_add_func ("/mse/no-idle-updates", test_no_idle_updates);
g_test_add_func ("/mse/remove", test_remove);
g_test_add_func ("/mse/abort-then-append", test_abort_then_append);
g_test_add_func ("/mse/split-audio-video", test_split_audio_video);
return g_test_run ();
}

17
tests/smoke/mse-leak-check.sh Executable file
View file

@ -0,0 +1,17 @@
#!/usr/bin/env bash
# Leak check for tests/smoke/mse.txt (S027): in <outdir>/nacre.log, the leak case's MediaSource (the second-to-last
# "MSE: MediaSource <id> created") must be freed before the page's sentinel (the last one created) is created, i.e.
# collected during the run after the page dropped it, not at shutdown. Usage: tests/smoke/mse-leak-check.sh <outdir>
set -eu
log=$1/nacre.log
mapfile -t created < <(grep -n '^MSE: MediaSource [0-9]* created' "$log" | tail -2)
[ ${#created[@]} -eq 2 ] || { echo "mse-leak-check: fewer than two MediaSources created"; exit 1; }
leak=$(sed -E 's/^[0-9]+:MSE: MediaSource ([0-9]+) .*/\1/' <<<"${created[0]}")
sentinel_line=${created[1]%%:*}
freed_line=$(grep -n "^MSE: MediaSource $leak freed" "$log" | head -1 | cut -d: -f1)
if [ -n "$freed_line" ] && [ "$freed_line" -lt "$sentinel_line" ]; then
echo "mse-leak-check: ok, MediaSource $leak freed during the run ($(sed -n "${freed_line}p" "$log"))"
else
echo "mse-leak-check: FAILED, MediaSource $leak not freed before the sentinel was created"
exit 1
fi

9
tests/smoke/mse-off.txt Normal file
View file

@ -0,0 +1,9 @@
# dom_media_source_enabled off (S027): with NACRE_DOM_MEDIA_SOURCE_ENABLED=0 in the environment, MediaSource,
# SourceBuffer and SourceBufferList are absent. Offline. Run: NACRE_DOM_MEDIA_SOURCE_ENABLED=0 tools/smoke.sh tests/smoke/mse-off.txt
wait 3
open @PAGES@/mse-basic.html
waitload 30
assert typeof MediaSource === 'undefined' && typeof SourceBuffer === 'undefined' && typeof SourceBufferList === 'undefined'
assert window.mse.stage === 'no MediaSource'
status done
quit

View file

@ -1,6 +1,9 @@
# 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; ?split (S026) uses separate video and audio
# SourceBuffers. Passes when MediaSource exists, every chunk is appended, and currentTime advances. Offline. Run with tools/smoke.sh (needs a build with the MSE patch).
# Media Source Extensions (branch s022-mse-proto): mse-basic.html appends a clip to one SourceBuffer in 32 KiB
# chunks, ends the stream and plays; ?split (S026) uses separate video and audio SourceBuffers. Passes when
# MediaSource exists, every chunk is appended, and currentTime advances. Then mse-spec.html (S027) runs the spec
# cases one by one (see its header); each must report true. Afterwards run tests/smoke/mse-leak-check.sh <outdir>:
# the leak case's MediaSource must be freed during the run ("MSE: MediaSource <id> freed" in nacre.log). Offline. Run with tools/smoke.sh (needs a build with the
# MSE patches). mse-off.txt checks the dom_media_source_enabled switch.
wait 3
open @PAGES@/mse-basic.html
waitload 30
@ -27,5 +30,23 @@ assert window.mse.videoWidth > 0
shot mse-split
assert window.mse.errors.length === 0
js JSON.stringify(window.mse)
# S027: spec cases
open @PAGES@/mse-spec.html
waitload 30
waitfor 120 window.spec && window.spec.done
shot mse-spec
js JSON.stringify(window.spec.results)
assert window.spec.results.attach === true
assert window.spec.results.duration === true
assert window.spec.results.ranges === true
assert window.spec.results.remove === true
assert window.spec.results.removeSourceBuffer === true
assert window.spec.results.changeType === true
assert window.spec.results.abort === true
assert window.spec.results.reopen === true
assert window.spec.results.sequence === true
assert window.spec.results.detach === true
assert window.spec.results.leak === true
# then: tests/smoke/mse-leak-check.sh <outdir>
status done
quit

View file

@ -0,0 +1,302 @@
<!doctype html>
<html>
<!-- MSE spec cases (S027), run one after another on mse-clip-mp4.js (fMP4 H.264 + AAC, 5 s) and, for changeType,
mse-clip-webm.js. window.spec.results maps each case to true or to the reason it failed; window.spec.done
turns true at the end. Cases: attach (event order, revoke right after src), duration (setter, durationchange,
below-buffered throws), ranges (video.buffered/seekable from the MediaSource, activeSourceBuffers),
remove (remove + re-append), removeSourceBuffer (then a new buffer), changeType, abort mid-append, ended then
append reopens, sequence mode, detach (load() closes the source), leak (drops a MediaSource and churns the GC; the
collection itself is checked in the browser log by tests/smoke/mse-leak-check.sh). -->
<head><meta charset="utf-8"><title>MSE spec</title>
<style>
body { margin: 0; background: #1d2b3b; color: #fff; font: 18px sans-serif; }
video { display: block; margin: 12px auto; width: 480px; height: 270px; background: #000; }
#log { font: 14px monospace; white-space: pre; width: 900px; margin: 0 auto; }
</style></head>
<body>
<video id="v" muted></video>
<div id="log"></div>
<script>
const MP4 = 'video/mp4; codecs="avc1.4d401f, mp4a.40.2"';
const WEBM = 'video/webm; codecs="vp9, opus"';
const spec = window.spec = { results: {}, done: false, events: [] };
const log = (line) => { document.getElementById('log').textContent += line + '\n'; };
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function loadClip(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);
});
}
// Resolves with the event's name when `target` fires one of `names`, or 'timeout'.
function next(target, names, ms = 10000) {
return new Promise((resolve) => {
const done = (e) => { names.forEach((n) => target.removeEventListener(n, done)); clearTimeout(t); resolve(e.type); };
const t = setTimeout(() => { names.forEach((n) => target.removeEventListener(n, done)); resolve('timeout'); }, ms);
names.forEach((n) => target.addEventListener(n, done));
});
}
function check(cond, what) { if (!cond) throw new Error(what); }
function throwsName(fn) { try { fn(); return 'none'; } catch (e) { return e.name; } }
const end = (ranges) => (ranges.length ? ranges.end(ranges.length - 1) : 0);
const start = (ranges) => (ranges.length ? ranges.start(0) : -1);
// Records every event of these names on target into spec.events, as "<prefix>:<type>".
function record(target, prefix, names) {
names.forEach((n) => target.addEventListener(n, () => spec.events.push(prefix + ':' + n)));
}
async function append(sb, data) {
sb.appendBuffer(data);
const ev = await next(sb, ['updateend']);
check(ev === 'updateend', 'append: ' + ev);
}
// A fresh MediaSource attached to the page's video; resolves once open.
async function open(video, revoke) {
const ms = new MediaSource();
const opened = next(ms, ['sourceopen']);
video.src = URL.createObjectURL(ms);
if (revoke) URL.revokeObjectURL(video.src);
check(await opened === 'sourceopen', 'no sourceopen');
return ms;
}
function detach(video) {
video.removeAttribute('src');
video.load();
}
const cases = {
async attach(v, mp4) {
const ms = new MediaSource();
record(ms, 'ms', ['sourceopen', 'sourceended', 'sourceclose']);
check(ms.readyState === 'closed', 'initial ' + ms.readyState);
check(isNaN(ms.duration), 'closed duration ' + ms.duration);
const opened = next(ms, ['sourceopen']);
v.src = URL.createObjectURL(ms);
URL.revokeObjectURL(v.src); // as many players do; attaching must still work
check(ms.readyState === 'closed', 'open before attach');
check(await opened === 'sourceopen', 'no sourceopen');
check(ms.readyState === 'open', 'after sourceopen ' + ms.readyState);
check(throwsName(() => ms.addSourceBuffer('')) === 'TypeError', 'empty type');
check(throwsName(() => ms.addSourceBuffer('video/x-nothing')) === 'NotSupportedError', 'bad type');
const sb = ms.addSourceBuffer(MP4);
check(ms.sourceBuffers.length === 1 && ms.sourceBuffers[0] === sb, 'sourceBuffers');
const order = [];
['updatestart', 'update', 'updateend'].forEach((n) => sb.addEventListener(n, () => order.push(n)));
sb.appendBuffer(mp4);
check(sb.updating, 'not updating after appendBuffer');
check(throwsName(() => sb.appendBuffer(mp4)) === 'InvalidStateError', 'second append while updating');
await next(sb, ['updateend']);
check(order.join() === 'updatestart,update,updateend', 'order ' + order.join());
detach(v);
await sleep(100);
check(spec.events.join() === 'ms:sourceopen,ms:sourceclose', 'events ' + spec.events.join());
},
async duration(v, mp4) {
const ms = await open(v);
const sb = ms.addSourceBuffer(MP4);
await append(sb, mp4);
const buffered = end(sb.buffered);
check(buffered > 4, 'buffered ' + buffered);
const changed = next(v, ['durationchange']);
ms.duration = 100;
check(ms.duration === 100, 'ms.duration ' + ms.duration);
check(await changed === 'durationchange', 'no durationchange');
check(v.duration === 100, 'video.duration ' + v.duration);
check(throwsName(() => { ms.duration = 1; }) === 'InvalidStateError', 'below buffered');
check(throwsName(() => { ms.duration = -1; }) === 'TypeError', 'negative');
ms.endOfStream();
check(ms.readyState === 'ended', 'readyState ' + ms.readyState);
await next(ms, ['sourceended']);
await sleep(200);
check(Math.abs(ms.duration - buffered) < 0.1, 'duration after endOfStream ' + ms.duration + ' vs ' + buffered);
check(throwsName(() => { ms.duration = 50; }) === 'InvalidStateError', 'set while ended');
detach(v);
},
async ranges(v, mp4) {
const ms = await open(v);
const active = [];
ms.activeSourceBuffers.addEventListener('addsourcebuffer', () => active.push('add'));
const sb = ms.addSourceBuffer(MP4);
check(v.buffered.length === 0, 'buffered before append');
await append(sb, mp4);
await sleep(100);
check(ms.activeSourceBuffers.length === 1, 'activeSourceBuffers ' + ms.activeSourceBuffers.length);
check(active.join() === 'add', 'active events ' + active.join());
check(v.buffered.length >= 1, 'video.buffered empty');
check(Math.abs(end(v.buffered) - end(sb.buffered)) < 0.1, 'video.buffered ' + end(v.buffered));
check(end(v.seekable) === ms.duration, 'seekable ' + end(v.seekable) + ' duration ' + ms.duration);
ms.duration = Infinity;
check(Math.abs(end(v.seekable) - end(v.buffered)) < 0.01, 'live seekable ' + end(v.seekable));
ms.setLiveSeekableRange(0, 20);
check(end(v.seekable) === 20, 'live seekable range ' + end(v.seekable));
ms.clearLiveSeekableRange();
detach(v);
},
async remove(v, mp4) {
const ms = await open(v);
const sb = ms.addSourceBuffer(MP4);
await append(sb, mp4);
const before = end(sb.buffered);
check(throwsName(() => sb.remove(3, 2)) === 'TypeError', 'end before start');
sb.remove(0, 3);
check(sb.updating, 'not updating during remove');
check(await next(sb, ['updateend']) === 'updateend', 'remove updateend');
check(start(sb.buffered) >= 1, 'buffered start after remove ' + start(sb.buffered));
check(end(sb.buffered) === before, 'buffered end after remove ' + end(sb.buffered));
await append(sb, mp4);
check(start(sb.buffered) < 0.1 && end(sb.buffered) === before, 're-append ' + start(sb.buffered));
detach(v);
},
async removeSourceBuffer(v, mp4) {
const ms = await open(v);
const sb = ms.addSourceBuffer(MP4);
await append(sb, mp4);
const removed = next(ms.sourceBuffers, ['removesourcebuffer']);
ms.removeSourceBuffer(sb);
check(ms.sourceBuffers.length === 0, 'still listed');
check(await removed === 'removesourcebuffer', 'no removesourcebuffer');
check(throwsName(() => sb.appendBuffer(mp4)) === 'InvalidStateError', 'append to removed');
check(throwsName(() => ms.removeSourceBuffer(sb)) === 'NotFoundError', 'remove twice');
const sb2 = ms.addSourceBuffer(MP4);
await append(sb2, mp4);
check(end(sb2.buffered) > 4, 'new buffer ' + end(sb2.buffered));
detach(v);
},
async changeType(v, mp4) {
const ms = await open(v);
const sb = ms.addSourceBuffer(MP4);
await append(sb, mp4);
check(throwsName(() => sb.changeType('')) === 'TypeError', 'empty');
check(throwsName(() => sb.changeType('video/x-nothing')) === 'NotSupportedError', 'unsupported');
check(throwsName(() => sb.changeType(MP4)) === 'none', 'same type');
// gst_mse can't switch containers (documented limit).
check(throwsName(() => sb.changeType(WEBM)) === 'NotSupportedError', 'other container');
sb.remove(0, Infinity);
await next(sb, ['updateend']);
await append(sb, mp4);
check(end(sb.buffered) > 4, 'append after changeType ' + end(sb.buffered));
detach(v);
},
async abort(v, mp4) {
const ms = await open(v);
const sb = ms.addSourceBuffer(MP4);
const order = [];
['updatestart', 'update', 'updateend', 'abort'].forEach((n) => sb.addEventListener(n, () => order.push(n)));
sb.appendBuffer(mp4);
sb.abort();
check(!sb.updating, 'updating after abort');
check(sb.appendWindowEnd === Infinity, 'append window reset');
await sleep(500);
check(order.join() === 'updatestart,abort,updateend', 'order ' + order.join());
await append(sb, mp4);
check(end(sb.buffered) > 4, 'append after abort ' + end(sb.buffered));
detach(v);
},
async reopen(v, mp4) {
const ms = await open(v);
const sb = ms.addSourceBuffer(MP4);
await append(sb, mp4.slice(0, 60000));
ms.endOfStream();
check(ms.readyState === 'ended', 'not ended');
check(throwsName(() => ms.endOfStream()) === 'InvalidStateError', 'endOfStream twice');
await next(ms, ['sourceended']);
const reopened = next(ms, ['sourceopen']);
sb.appendBuffer(mp4);
check(ms.readyState === 'open', 'append did not reopen: ' + ms.readyState);
check(await reopened === 'sourceopen', 'no sourceopen');
await next(sb, ['updateend']);
check(end(sb.buffered) > 4, 'buffered ' + end(sb.buffered));
detach(v);
},
async sequence(v, mp4) {
const ms = await open(v);
const sb = ms.addSourceBuffer(MP4);
check(sb.mode === 'segments', 'mode ' + sb.mode);
sb.mode = 'sequence';
check(sb.mode === 'sequence', 'mode ' + sb.mode);
await append(sb, mp4);
check(end(sb.buffered) > 4, 'buffered ' + end(sb.buffered));
sb.timestampOffset = 10;
check(sb.timestampOffset === 10, 'timestampOffset ' + sb.timestampOffset);
detach(v);
},
async detach(v, mp4) {
const ms = await open(v);
const sb = ms.addSourceBuffer(MP4);
await append(sb, mp4);
const closed = next(ms, ['sourceclose']);
const removed = next(ms.sourceBuffers, ['removesourcebuffer']);
detach(v);
check(ms.readyState === 'closed', 'readyState ' + ms.readyState);
check(isNaN(ms.duration), 'duration ' + ms.duration);
check(ms.sourceBuffers.length === 0 && ms.activeSourceBuffers.length === 0, 'lists not empty');
check(await closed === 'sourceclose', 'no sourceclose');
check(await removed === 'removesourcebuffer', 'no removesourcebuffer');
check(throwsName(() => ms.addSourceBuffer(MP4)) === 'InvalidStateError', 'add while closed');
// A closed MediaSource can be attached again.
const opened = next(ms, ['sourceopen']);
v.src = URL.createObjectURL(ms);
check(await opened === 'sourceopen', 'no sourceopen on reattach');
detach(v);
},
// Drops an attached-then-detached MediaSource and churns the GC for 10 s. Servo runs neither
// FinalizationRegistry callbacks nor clears WeakRefs, so the page can't see the collection; the browser logs
// "MSE: MediaSource <id> created/freed" and tests/smoke/mse-leak-check.sh checks that this one (the
// second-to-last created) was freed before the sentinel (the last, kept alive) was created.
async leak(v, mp4) {
await (async () => {
const ms = await open(v, true);
const sb = ms.addSourceBuffer(MP4);
await append(sb, mp4);
detach(v);
})();
for (let i = 0; i < 40; i++) {
let junk = [];
for (let j = 0; j < 64; j++) junk.push(new ArrayBuffer(1 << 20));
junk = null;
await sleep(250);
}
window.sentinel = new MediaSource();
},
};
async function run() {
const v = document.getElementById('v');
if (!window.MediaSource) { spec.results.exists = 'no MediaSource'; spec.done = true; return; }
const mp4 = await loadClip('mse-clip-mp4.js');
for (const [name, fn] of Object.entries(cases)) {
try {
await fn(v, mp4);
spec.results[name] = true;
} catch (e) {
spec.results[name] = String(e && e.message || e);
}
log(name + ': ' + spec.results[name]);
await sleep(100);
}
spec.done = true;
log('done');
}
run().catch((e) => { spec.results.run = String(e); spec.done = true; });
</script>
</body>
</html>

50
tests/wpt-mse/driver.html Normal file
View file

@ -0,0 +1,50 @@
<!doctype html>
<html>
<!-- WPT media-source driver (tools/wpt-mse.sh): loads each test listed in tests.json in an iframe, waits for its
testharness completion (window.__wpt, from our testharnessreport.js) or TIMEOUT seconds, and keeps the results
in window.__all = { done, files: { <file>: { status, tests: [{name, status, message}] } } } and POSTs the files
map to /results (the server saves it). testharness test
status: 0 pass, 1 fail, 2 timeout, 3 not run, 4 precondition failed. -->
<head><meta charset="utf-8"><title>WPT MSE</title>
<style>body { font: 14px monospace; margin: 8px; } iframe { width: 640px; height: 360px; border: 1px solid #888; }</style>
</head>
<body>
<div id="head">WPT MSE</div>
<iframe id="f"></iframe>
<pre id="log"></pre>
<script>
const TIMEOUT = Number(new URLSearchParams(location.search).get('timeout') || 40);
const all = window.__all = { done: false, files: {} };
const log = (line) => { document.getElementById('log').textContent += line + '\n'; };
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function runOne(file) {
const frame = document.getElementById('f');
frame.src = '/media-source/' + file;
const deadline = Date.now() + TIMEOUT * 1000;
while (Date.now() < deadline) {
await sleep(250);
let result = null;
try { result = frame.contentWindow.__wpt; } catch (e) {}
if (result && result.done) return result;
}
return { done: false, status: 'driver-timeout', tests: [] };
}
async function run() {
const files = await (await fetch('tests.json')).json();
for (const file of files) {
const result = await runOne(file);
all.files[file] = result;
const pass = result.tests.filter((t) => t.status === 0).length;
log(file + ': ' + pass + '/' + result.tests.length + (result.done ? '' : ' (no completion)'));
document.getElementById('head').textContent = 'WPT MSE ' + Object.keys(all.files).length + '/' + files.length;
}
document.getElementById('f').src = 'about:blank';
await fetch('/results', { method: 'POST', body: JSON.stringify(all.files) });
all.done = true;
}
run().catch((e) => { all.error = String(e); all.done = true; });
</script>
</body>
</html>

42
tests/wpt-mse/server.py Executable file
View file

@ -0,0 +1,42 @@
#!/usr/bin/env python3
"""HTTP server for tools/wpt-mse.sh: serves a WPT checkout, with Nacre's testharnessreport.js, the driver page and
tests.json from tests/wpt-mse, and saves the driver's POST /results to the given file.
Usage: server.py <wpt dir> <tests.json> <results.json> <port>
"""
import http.server
import os
import sys
WPT, TESTS, RESULTS, PORT = sys.argv[1], sys.argv[2], sys.argv[3], int(sys.argv[4])
HERE = os.path.dirname(os.path.abspath(__file__))
OVERLAY = {
"/resources/testharnessreport.js": os.path.join(HERE, "testharnessreport.js"),
"/driver.html": os.path.join(HERE, "driver.html"),
"/tests.json": TESTS,
}
class Handler(http.server.SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=WPT, **kwargs)
def translate_path(self, path):
clean = path.split("?", 1)[0].split("#", 1)[0]
return OVERLAY.get(clean) or super().translate_path(path)
def do_POST(self):
if self.path != "/results":
self.send_error(404)
return
body = self.rfile.read(int(self.headers.get("Content-Length", 0)))
with open(RESULTS, "wb") as f:
f.write(body)
self.send_response(204)
self.end_headers()
def log_message(self, *args):
pass
http.server.ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever()

View file

@ -0,0 +1,11 @@
// Nacre's WPT report hook (tools/wpt-mse.sh): replaces resources/testharnessreport.js and keeps the results on
// window.__wpt for the driver page (tests/wpt-mse/driver.html), which runs each test in an iframe.
setup({ explicit_timeout: true });
add_completion_callback(function (tests, status) {
window.__wpt = {
done: true,
status: status.status,
message: status.message || '',
tests: tests.map(function (t) { return { name: t.name, status: t.status, message: t.message || '' }; }),
};
});

68
tools/wpt-mse.sh Executable file
View file

@ -0,0 +1,68 @@
#!/usr/bin/env bash
# Runs a subset of WPT media-source/ in Nacre and prints pass counts (S027). Offline after the first run.
# - fetches web-platform-tests at $WPT_REV (sparse: media-source, resources, common) into target/wpt once
# - serves it on 127.0.0.1:$WPT_PORT (tests/wpt-mse/server.py) with our testharnessreport.js
# - runs tests/wpt-mse/driver.html in a hidden smoke run (tools/smoke.sh): every test in an iframe, $WPT_TIMEOUT s each
# - writes <outdir>/wpt/results.json and prints per-file and total subtest pass counts
# Usage: tools/wpt-mse.sh [outdir] [file ...] (files default to the subset below)
# Not run: dedicated-worker/, managed/ (ManagedMediaSource), mse-for-webcodecs/, idlharness and *.window.js (need
# wptserve's generated wrappers), the reftest mediasource-video-is-visible, iamf, and the long config-change playbacks.
set -eu
root=$(cd "$(dirname "$0")/.." && pwd)
rev=${WPT_REV:-4e9e53b6fc1dad91c48a71593041b2a325d5401b}
port=${WPT_PORT:-8790}
wpt=$root/target/wpt
out=${1:-$root/target/smoke/wpt-mse-$(date +%H%M%S)}
shift || true
mkdir -p "$out/wpt"
if [ ! -d "$wpt/media-source" ]; then
git clone --filter=blob:none --no-checkout https://github.com/web-platform-tests/wpt.git "$wpt"
git -C "$wpt" sparse-checkout set media-source resources common
git -C "$wpt" fetch --depth 1 origin "$rev"
git -C "$wpt" checkout -q "$rev"
fi
if [ $# -gt 0 ]; then
files=("$@")
else
mapfile -t files < <(cd "$wpt/media-source" && ls -1 ./*.html | sed 's|^\./||' |
grep -v -e '^mediasource-config-change-' -e '^mediasource-video-is-visible' -e '^mediasource-iamf-')
fi
printf '%s\n' "${files[@]}" | python3 -c 'import json,sys; print(json.dumps([l.strip() for l in sys.stdin if l.strip()]))' >"$out/wpt/tests.json"
python3 -I "$root/tests/wpt-mse/server.py" "$wpt" "$out/wpt/tests.json" "$out/wpt/results.json" "$port" &
server=$!
trap 'kill $server 2>/dev/null' EXIT
rm -f "$out/wpt/results.json"
timeout_each=${WPT_TIMEOUT:-40}
cat >"$out/wpt/wpt.txt" <<SCRIPT
# Generated by tools/wpt-mse.sh
wait 2
open http://127.0.0.1:$port/driver.html?timeout=$timeout_each
waitload 30
waitfor $(( ${#files[@]} * (timeout_each + 5) )) window.__all && window.__all.done
shot wpt-driver
status done
quit
SCRIPT
SMOKE_TIMEOUT=$(( ${#files[@]} * (timeout_each + 5) + 120 )) "$root/tools/smoke.sh" "$out/wpt/wpt.txt" "$out" || true
python3 - "$out/wpt/results.json" <<'PY'
import json, sys
try:
files = json.load(open(sys.argv[1]))
except OSError:
sys.exit("wpt-mse: no results (the driver did not finish)")
total = passed = 0
for name, result in files.items():
tests = result.get("tests", [])
ok = sum(1 for t in tests if t["status"] == 0)
total += len(tests)
passed += ok
note = "" if result.get("done") else " (no completion: " + str(result.get("status")) + ")"
print(f"{ok:4}/{len(tests):<4} {name}{note}")
print(f"wpt-mse: {passed}/{total} subtests passed in {len(files)} files")
PY

View file

@ -938,6 +938,18 @@ gst_append_pipeline_reset (GstAppendPipeline * self)
background_task_stop (self->task);
/* Nacre patch: take the old tracks' appsinks out of the pipeline. Upstream
* left them in, so the next initialization segment's appsink ("video-0")
* clashed by name, gst_bin_add() dropped it and add_track() used it after
* it was freed (a crash on every append after abort() or changeType()). */
for (guint i = 0; i < self->tracks->len; i++) {
Track *track = &g_array_index (self->tracks, Track, i);
if (track->sink != NULL) {
gst_element_set_state (GST_ELEMENT (track->sink), GST_STATE_NULL);
gst_bin_remove (GST_BIN (self->pipeline), GST_ELEMENT (track->sink));
}
}
init_segment_finalize (&self->init_segment);
gst_clear_object (&self->streams);
g_array_free (self->tracks, TRUE);

View file

@ -155,6 +155,10 @@ struct _GstSourceBuffer
gsize size;
GstBuffer *pending_data;
GCond pending_data_cond;
/* Nacre patch: abort() during an append waits for it (see gst_source_buffer_abort). */
gboolean appending;
gboolean abort_requested;
GCond append_done_cond;
AppendToBufferTask *append_to_buffer_task;
GstAppendPipeline *append_pipeline;
GstMseEventQueue *event_queue;
@ -224,6 +228,8 @@ static void dispatch_event (SourceBufferEventItem * item, GstSourceBuffer *
static void schedule_event_unlocked (GstSourceBuffer * self,
SourceBufferEvent event);
static void append_to_buffer_task_func (AppendToBufferTask * task);
static gsize compute_total_size_unlocked (GstSourceBuffer * self);
static void reset_parser_state_unlocked (GstSourceBuffer * self);
static void append_to_buffer_task_start (AppendToBufferTask * task);
static void append_to_buffer_task_stop (AppendToBufferTask * task);
static AppendToBufferTask *append_to_buffer_task_new (GstSourceBuffer * parent);
@ -938,6 +944,7 @@ gst_source_buffer_init (GstSourceBuffer * self)
self->size = 0;
self->pending_data = NULL;
g_cond_init (&self->pending_data_cond);
g_cond_init (&self->append_done_cond);
self->processed_init_segment = FALSE;
self->event_queue =
gst_mse_event_queue_new ((GstMseEventQueueCallback) dispatch_event, self);
@ -947,8 +954,12 @@ gst_source_buffer_init (GstSourceBuffer * self)
(GEqualFunc) track_buffer_equal, NULL, gst_object_unref);
g_mutex_init (&self->tracks_lock);
self->track_feeds = g_hash_table_new_full (g_direct_hash, g_direct_equal,
NULL, (GDestroyNotify) clear_track_feed);
/* Nacre patch: keyed by track id like track_buffers. After a parser reset
* (abort, changeType) the next initialization segment brings new track
* objects with the same ids; their samples must reach the existing track
* buffers and feeds (and so msesrc's streams), not miss the lookup. */
self->track_feeds = g_hash_table_new_full ((GHashFunc) track_buffer_hash,
(GEqualFunc) track_buffer_equal, NULL, (GDestroyNotify) clear_track_feed);
self->seek_time = 0;
self->callbacks.callbacks.duration_changed = NULL;
self->callbacks.user_data = NULL;
@ -1178,7 +1189,9 @@ gst_source_buffer_set_append_window_start (GstSourceBuffer * self,
goto error;
}
if (!GST_CLOCK_TIME_IS_VALID (start) || start <= self->append_window_end) {
/* Nacre patch: upstream refused every start below the end (`<=`). An end of
* GST_CLOCK_TIME_NONE is +infinity, which the unsigned compare gets right. */
if (!GST_CLOCK_TIME_IS_VALID (start) || start >= self->append_window_end) {
g_set_error (error,
GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_TYPE,
"append window start must be between zero and append window end");
@ -1486,6 +1499,41 @@ gst_source_buffer_remove (GstSourceBuffer * self, GstClockTime start,
GstClockTime end, GError ** error)
{
g_return_val_if_fail (GST_IS_SOURCE_BUFFER (self), FALSE);
/* Nacre patch: upstream 1.28.9 returns here without removing anything.
* Remove every coded frame group (key frame to key frame) that lies inside
* [start, end); a group that only overlaps the range stays, so playback never
* loses the frames a kept frame depends on. Runs synchronously: the caller
* reports update and update-end. */
if (end == GST_CLOCK_TIME_NONE)
end = G_MAXUINT64;
GST_OBJECT_LOCK (self);
if (is_removed_unlocked (self) || is_updating (self)) {
g_set_error (error,
GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_INVALID_STATE,
"source buffer is removed or still updating");
GST_OBJECT_UNLOCK (self);
return FALSE;
}
if (start >= end) {
g_set_error (error,
GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_TYPE,
"remove range is empty");
GST_OBJECT_UNLOCK (self);
return FALSE;
}
GHashTableIter iter;
g_hash_table_iter_init (&iter, self->track_buffers);
for (gpointer value; g_hash_table_iter_next (&iter, NULL, &value);) {
gst_media_source_track_buffer_remove_range (value, start, end);
}
self->size = compute_total_size_unlocked (self);
GST_OBJECT_UNLOCK (self);
return TRUE;
}
@ -1772,10 +1820,20 @@ append_to_buffer_task_func (AppendToBufferTask * task)
* buffers, and the new-sample callback takes this object's lock, so drop it
* meanwhile. `updating` stays set, so no other append can start. */
GstAppendPipeline *pipeline = gst_object_ref (self->append_pipeline);
self->appending = TRUE;
GST_OBJECT_UNLOCK (self);
GstFlowReturn result = gst_append_pipeline_append (pipeline, pending_data);
gst_object_unref (pipeline);
GST_OBJECT_LOCK (self);
self->appending = FALSE;
/* Nacre patch: abort() came in while this append ran. It resets the parser
* and owns the events (abort and update-end come from the caller). */
if (self->abort_requested) {
self->abort_requested = FALSE;
g_cond_broadcast (&self->append_done_cond);
goto done;
}
if (is_removed_unlocked (self)) {
append_successful_unlocked (self, TRUE);
@ -2022,14 +2080,35 @@ gboolean
gst_source_buffer_abort (GstSourceBuffer * self, GError ** error)
{
g_return_val_if_fail (GST_IS_SOURCE_BUFFER (self), FALSE);
if (gst_append_pipeline_eos (self->append_pipeline) == GST_FLOW_OK) {
return TRUE;
} else {
/* Nacre patch: upstream sent end-of-stream into the append pipeline, which
* left it unable to take any later append. The spec's abort drops the pending
* data, stops a running append and resets the parser state, so the next
* append starts fresh (with an initialization segment). An append that is
* already inside the pipeline is waited for (it takes milliseconds) and its
* result discarded. */
GST_OBJECT_LOCK (self);
if (is_removed_unlocked (self)) {
g_set_error (error,
GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_INVALID_STATE,
"failed to abort source buffer");
"source buffer is removed");
GST_OBJECT_UNLOCK (self);
return FALSE;
}
clear_pending_data_unlocked (self);
if (self->appending) {
self->abort_requested = TRUE;
while (self->abort_requested) {
g_cond_wait (&self->append_done_cond, GST_OBJECT_GET_LOCK (self));
}
}
reset_parser_state_unlocked (self);
clear_updating (self);
GST_OBJECT_UNLOCK (self);
return TRUE;
}
gboolean

View file

@ -135,9 +135,124 @@ Base: https://sources.debian.org/src/gst-plugins-bad1.0/1.28.9-1/ . Apply with p
return GST_FLOW_OK;
}
@@ -875,6 +938,18 @@
background_task_stop (self->task);
+ /* Nacre patch: take the old tracks' appsinks out of the pipeline. Upstream
+ * left them in, so the next initialization segment's appsink ("video-0")
+ * clashed by name, gst_bin_add() dropped it and add_track() used it after
+ * it was freed (a crash on every append after abort() or changeType()). */
+ for (guint i = 0; i < self->tracks->len; i++) {
+ Track *track = &g_array_index (self->tracks, Track, i);
+ if (track->sink != NULL) {
+ gst_element_set_state (GST_ELEMENT (track->sink), GST_STATE_NULL);
+ gst_bin_remove (GST_BIN (self->pipeline), GST_ELEMENT (track->sink));
+ }
+ }
+
init_segment_finalize (&self->init_segment);
gst_clear_object (&self->streams);
g_array_free (self->tracks, TRUE);
--- a/gst-libs/gst/mse/gstsourcebuffer.c
+++ b/gst-libs/gst/mse/gstsourcebuffer.c
@@ -1761,13 +1761,26 @@
@@ -155,6 +155,10 @@
gsize size;
GstBuffer *pending_data;
GCond pending_data_cond;
+ /* Nacre patch: abort() during an append waits for it (see gst_source_buffer_abort). */
+ gboolean appending;
+ gboolean abort_requested;
+ GCond append_done_cond;
AppendToBufferTask *append_to_buffer_task;
GstAppendPipeline *append_pipeline;
GstMseEventQueue *event_queue;
@@ -224,6 +228,8 @@
static void schedule_event_unlocked (GstSourceBuffer * self,
SourceBufferEvent event);
static void append_to_buffer_task_func (AppendToBufferTask * task);
+static gsize compute_total_size_unlocked (GstSourceBuffer * self);
+static void reset_parser_state_unlocked (GstSourceBuffer * self);
static void append_to_buffer_task_start (AppendToBufferTask * task);
static void append_to_buffer_task_stop (AppendToBufferTask * task);
static AppendToBufferTask *append_to_buffer_task_new (GstSourceBuffer * parent);
@@ -938,6 +944,7 @@
self->size = 0;
self->pending_data = NULL;
g_cond_init (&self->pending_data_cond);
+ g_cond_init (&self->append_done_cond);
self->processed_init_segment = FALSE;
self->event_queue =
gst_mse_event_queue_new ((GstMseEventQueueCallback) dispatch_event, self);
@@ -947,8 +954,12 @@
(GEqualFunc) track_buffer_equal, NULL, gst_object_unref);
g_mutex_init (&self->tracks_lock);
- self->track_feeds = g_hash_table_new_full (g_direct_hash, g_direct_equal,
- NULL, (GDestroyNotify) clear_track_feed);
+ /* Nacre patch: keyed by track id like track_buffers. After a parser reset
+ * (abort, changeType) the next initialization segment brings new track
+ * objects with the same ids; their samples must reach the existing track
+ * buffers and feeds (and so msesrc's streams), not miss the lookup. */
+ self->track_feeds = g_hash_table_new_full ((GHashFunc) track_buffer_hash,
+ (GEqualFunc) track_buffer_equal, NULL, (GDestroyNotify) clear_track_feed);
self->seek_time = 0;
self->callbacks.callbacks.duration_changed = NULL;
self->callbacks.user_data = NULL;
@@ -1178,7 +1189,9 @@
goto error;
}
- if (!GST_CLOCK_TIME_IS_VALID (start) || start <= self->append_window_end) {
+ /* Nacre patch: upstream refused every start below the end (`<=`). An end of
+ * GST_CLOCK_TIME_NONE is +infinity, which the unsigned compare gets right. */
+ if (!GST_CLOCK_TIME_IS_VALID (start) || start >= self->append_window_end) {
g_set_error (error,
GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_TYPE,
"append window start must be between zero and append window end");
@@ -1486,6 +1499,41 @@
GstClockTime end, GError ** error)
{
g_return_val_if_fail (GST_IS_SOURCE_BUFFER (self), FALSE);
+
+ /* Nacre patch: upstream 1.28.9 returns here without removing anything.
+ * Remove every coded frame group (key frame to key frame) that lies inside
+ * [start, end); a group that only overlaps the range stays, so playback never
+ * loses the frames a kept frame depends on. Runs synchronously: the caller
+ * reports update and update-end. */
+ if (end == GST_CLOCK_TIME_NONE)
+ end = G_MAXUINT64;
+
+ GST_OBJECT_LOCK (self);
+
+ if (is_removed_unlocked (self) || is_updating (self)) {
+ g_set_error (error,
+ GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_INVALID_STATE,
+ "source buffer is removed or still updating");
+ GST_OBJECT_UNLOCK (self);
+ return FALSE;
+ }
+
+ if (start >= end) {
+ g_set_error (error,
+ GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_TYPE,
+ "remove range is empty");
+ GST_OBJECT_UNLOCK (self);
+ return FALSE;
+ }
+
+ GHashTableIter iter;
+ g_hash_table_iter_init (&iter, self->track_buffers);
+ for (gpointer value; g_hash_table_iter_next (&iter, NULL, &value);) {
+ gst_media_source_track_buffer_remove_range (value, start, end);
+ }
+ self->size = compute_total_size_unlocked (self);
+
+ GST_OBJECT_UNLOCK (self);
return TRUE;
}
@@ -1761,13 +1809,36 @@
}
if (!GST_IS_BUFFER (pending_data)) {
@ -155,10 +270,20 @@ Base: https://sources.debian.org/src/gst-plugins-bad1.0/1.28.9-1/ . Apply with p
+ * buffers, and the new-sample callback takes this object's lock, so drop it
+ * meanwhile. `updating` stays set, so no other append can start. */
+ GstAppendPipeline *pipeline = gst_object_ref (self->append_pipeline);
+ self->appending = TRUE;
+ GST_OBJECT_UNLOCK (self);
+ GstFlowReturn result = gst_append_pipeline_append (pipeline, pending_data);
+ gst_object_unref (pipeline);
+ GST_OBJECT_LOCK (self);
+ self->appending = FALSE;
+
+ /* Nacre patch: abort() came in while this append ran. It resets the parser
+ * and owns the events (abort and update-end come from the caller). */
+ if (self->abort_requested) {
+ self->abort_requested = FALSE;
+ g_cond_broadcast (&self->append_done_cond);
+ goto done;
+ }
+
+ if (is_removed_unlocked (self)) {
+ append_successful_unlocked (self, TRUE);
@ -167,6 +292,46 @@ Base: https://sources.debian.org/src/gst-plugins-bad1.0/1.28.9-1/ . Apply with p
if (result != GST_FLOW_OK) {
GST_ERROR_OBJECT (self, "failed to append: %s", gst_flow_get_name (result));
@@ -2009,14 +2080,35 @@
gst_source_buffer_abort (GstSourceBuffer * self, GError ** error)
{
g_return_val_if_fail (GST_IS_SOURCE_BUFFER (self), FALSE);
- if (gst_append_pipeline_eos (self->append_pipeline) == GST_FLOW_OK) {
- return TRUE;
- } else {
+
+ /* Nacre patch: upstream sent end-of-stream into the append pipeline, which
+ * left it unable to take any later append. The spec's abort drops the pending
+ * data, stops a running append and resets the parser state, so the next
+ * append starts fresh (with an initialization segment). An append that is
+ * already inside the pipeline is waited for (it takes milliseconds) and its
+ * result discarded. */
+ GST_OBJECT_LOCK (self);
+
+ if (is_removed_unlocked (self)) {
g_set_error (error,
GST_MEDIA_SOURCE_ERROR, GST_MEDIA_SOURCE_ERROR_INVALID_STATE,
- "failed to abort source buffer");
+ "source buffer is removed");
+ GST_OBJECT_UNLOCK (self);
return FALSE;
}
+
+ clear_pending_data_unlocked (self);
+ if (self->appending) {
+ self->abort_requested = TRUE;
+ while (self->abort_requested) {
+ g_cond_wait (&self->append_done_cond, GST_OBJECT_GET_LOCK (self));
+ }
+ }
+ reset_parser_state_unlocked (self);
+ clear_updating (self);
+
+ GST_OBJECT_UNLOCK (self);
+ return TRUE;
}
gboolean
--- a/gst-libs/gst/mse/gstmsesrc.c
+++ b/gst-libs/gst/mse/gstmsesrc.c
@@ -266,7 +266,7 @@

View file

@ -9,9 +9,9 @@
use std::any::Any;
use std::ops::Range;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use glib::object::ObjectType;
use glib::translate::ToGlibPtr;
use gstreamer as gst;
use gstreamer_mse as gst_mse;
@ -23,18 +23,31 @@ use servo_media_player::mse::{
pub struct GStreamerMediaSource {
pub(crate) source: gst_mse::MediaSource,
events: MseEventSink,
/// Live buffers by id, for `remove_source_buffer`.
buffers: Mutex<Vec<(usize, gst_mse::SourceBuffer)>>,
/// The page set an infinite duration; gst_mse stores it as "none", like an unknown one.
infinite: std::sync::atomic::AtomicBool,
}
impl GStreamerMediaSource {
pub fn new(events: MseEventSink) -> Self {
let source = gst_mse::MediaSource::new();
// The DOM drives ended and closed itself; only the end of attaching comes from here.
let sink = events.clone();
source.connect_on_source_open(move |_| sink(MseEvent::SourceOpen));
let sink = events.clone();
source.connect_on_source_ended(move |_| sink(MseEvent::SourceEnded));
source.connect_duration_notify(move |_| sink(MseEvent::DurationChange));
let active = source.active_source_buffers();
let sink = events.clone();
source.connect_on_source_close(move |_| sink(MseEvent::SourceClose));
Self { source, events }
active.connect_on_sourcebuffer_added(move |_| sink(MseEvent::ActiveChange));
let sink = events.clone();
active.connect_on_sourcebuffer_removed(move |_| sink(MseEvent::ActiveChange));
Self {
source,
events,
buffers: Mutex::new(vec![]),
infinite: Default::default(),
}
}
pub fn is_type_supported(mime: &str) -> bool {
@ -49,38 +62,57 @@ fn error(e: glib::Error) -> MseError {
MseError::InvalidState(e.to_string())
} else if e.matches(gst_mse::MediaSourceError::QuotaExceeded) {
MseError::QuotaExceeded(e.to_string())
} else if e.matches(gst_mse::MediaSourceError::Type) {
MseError::Type(e.to_string())
} else {
MseError::Backend(e.to_string())
}
}
/// GstClockTime is unsigned: negative times (a negative timestampOffset) clamp to 0.
fn clock(seconds: f64) -> gst::ClockTime {
gst::ClockTime::from_nseconds((seconds.max(0.0) * 1e9) as u64)
}
fn seconds(time: Option<gst::ClockTime>) -> f64 {
time.map_or(f64::NAN, |t| t.nseconds() as f64 / 1e9)
}
/// The container part of a MIME type ("video/webm" of `video/webm; codecs="vp9"`).
fn container(mime: &str) -> String {
mime.split(';').next().unwrap_or("").trim().to_ascii_lowercase()
}
static NEXT_BUFFER_ID: AtomicUsize = AtomicUsize::new(1);
impl MediaSourceBackend for GStreamerMediaSource {
fn add_source_buffer(
&self,
mime: &str,
) -> Result<(usize, Arc<dyn SourceBufferBackend>), MseError> {
fn add_source_buffer(&self, mime: &str) -> Result<Arc<dyn SourceBufferBackend>, MseError> {
let buffer = self.source.add_source_buffer(mime).map_err(error)?;
let index = self.source.source_buffers().length() as usize - 1;
let source_buffer = Arc::new(GStreamerSourceBuffer {
buffer,
index,
events: self.events.clone(),
});
let id = NEXT_BUFFER_ID.fetch_add(1, Ordering::Relaxed);
// Nacre's patched gst_mse (vendor/gst-mse) signals update-end once the appended samples
// are in the track buffers, and only for an append.
let sink = self.events.clone();
source_buffer
.buffer
.connect_on_update_end(move |_| sink(MseEvent::UpdateEnd { buffer: index }));
buffer.connect_on_update_end(move |_| sink(MseEvent::UpdateEnd { buffer: id }));
let sink = self.events.clone();
source_buffer
.buffer
.connect_on_error(move |_| sink(MseEvent::Error { buffer: index }));
Ok((index, source_buffer))
buffer.connect_on_error(move |_| sink(MseEvent::Error { buffer: id }));
self.buffers.lock().unwrap().push((id, buffer.clone()));
Ok(Arc::new(GStreamerSourceBuffer {
buffer,
source: self.source.clone(),
id,
content_type: Mutex::new(mime.to_owned()),
events: self.events.clone(),
}))
}
fn remove_source_buffer(&self, id: usize) -> Result<(), MseError> {
let mut buffers = self.buffers.lock().unwrap();
let Some(index) = buffers.iter().position(|(i, _)| *i == id) else {
return Err(MseError::InvalidState("no such source buffer".into()));
};
let (_, buffer) = buffers.remove(index);
drop(buffers);
self.source.remove_source_buffer(&buffer).map_err(error)
}
fn end_of_stream(&self, error_kind: EndOfStreamError) -> Result<(), MseError> {
@ -103,17 +135,33 @@ impl MediaSourceBackend for GStreamerMediaSource {
fn duration(&self) -> f64 {
match self.source.duration() {
Some(d) => d.nseconds() as f64 / 1e9,
None if self.infinite.load(Ordering::Relaxed) => f64::INFINITY,
None => f64::NAN,
}
}
fn set_duration(&self, duration: f64) -> Result<(), MseError> {
let value = if duration.is_infinite() {
None
} else {
Some(clock(duration))
};
self.source.set_duration(value).map_err(error)
let infinite = duration.is_infinite();
let value = (!infinite).then(|| clock(duration));
self.source.set_duration(value).map_err(error)?;
self.infinite.store(infinite, Ordering::Relaxed);
Ok(())
}
fn set_live_seekable_range(&self, range: Option<Range<f64>>) -> Result<(), MseError> {
match range {
Some(range) => self
.source
.set_live_seekable_range(clock(range.start), clock(range.end)),
None => self.source.clear_live_seekable_range(),
}
.map_err(error)
}
fn detach(&self) {
self.buffers.lock().unwrap().clear();
self.infinite.store(false, Ordering::Relaxed);
self.source.detach();
}
fn as_any(&self) -> &dyn Any {
@ -123,11 +171,17 @@ impl MediaSourceBackend for GStreamerMediaSource {
struct GStreamerSourceBuffer {
buffer: gst_mse::SourceBuffer,
index: usize,
source: gst_mse::MediaSource,
id: usize,
content_type: Mutex<String>,
events: MseEventSink,
}
impl SourceBufferBackend for GStreamerSourceBuffer {
fn id(&self) -> usize {
self.id
}
fn append_buffer(&self, data: Vec<u8>) -> Result<(), MseError> {
self.buffer
.append_buffer(gst::Buffer::from_mut_slice(data))
@ -141,9 +195,9 @@ impl SourceBufferBackend for GStreamerSourceBuffer {
fn remove(&self, start: f64, end: f64) -> Result<(), MseError> {
let end = if end.is_infinite() { None } else { Some(clock(end)) };
self.buffer.remove(Some(clock(start)), end).map_err(error)?;
// gst_mse 1.28.9's remove is a stub that removes nothing and signals nothing, so the
// removal ends here (the DOM gets updateend through its task queue, after Remove returns).
(self.events)(MseEvent::UpdateEnd { buffer: self.index });
// Nacre's gst_mse removes synchronously and signals nothing, so the removal ends here
// (the DOM gets updateend through its task queue, after Remove returns).
(self.events)(MseEvent::UpdateEnd { buffer: self.id });
Ok(())
}
@ -173,6 +227,20 @@ impl SourceBufferBackend for GStreamerSourceBuffer {
}
}
fn set_sequence_mode(&self, sequence: bool) -> Result<(), MseError> {
let mode = if sequence {
gst_mse::SourceBufferAppendMode::Sequence
} else {
gst_mse::SourceBufferAppendMode::Segments
};
self.buffer.set_append_mode(mode).map_err(error)
}
fn timestamp_offset(&self) -> f64 {
let offset = seconds(self.buffer.timestamp_offset());
if offset.is_nan() { 0.0 } else { offset }
}
fn set_timestamp_offset(&self, offset: f64) -> Result<(), MseError> {
self.buffer.set_timestamp_offset(Some(clock(offset))).map_err(error)
}
@ -183,7 +251,23 @@ impl SourceBufferBackend for GStreamerSourceBuffer {
self.buffer.set_append_window_end(end).map_err(error)
}
fn updating(&self) -> bool {
self.buffer.is_updating()
/// gst_mse 1.28 can't switch byte stream formats (`change_content_type` always fails). Within
/// the same container the parser is reset, so the next initialization segment may bring other
/// codecs; another container is NotSupported.
fn change_type(&self, mime: &str) -> Result<(), MseError> {
let mut content_type = self.content_type.lock().unwrap();
if container(mime) != container(&content_type) {
return Err(MseError::NotSupported(format!(
"changing {content_type} to {mime} is not supported"
)));
}
self.buffer.abort().map_err(error)?;
*content_type = mime.to_owned();
Ok(())
}
fn is_active(&self) -> bool {
let active = self.source.active_source_buffers();
(0..active.length()).any(|i| active.index(i).is_some_and(|b| b == self.buffer))
}
}

View file

@ -2,13 +2,27 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Media Source Extensions backend traits (Nacre S022 prototype).
//! Media Source Extensions backend traits (Nacre, D-015).
//! The backend owns the MSE algorithms (append, coded frame processing,
//! buffered ranges, removal); the DOM side only mirrors state and fires events.
//! buffered ranges, removal); the DOM side keeps the spec state (ready state,
//! updating, lists), checks the arguments and fires the events.
use std::any::Any;
use std::ops::Range;
use std::sync::Arc;
use std::sync::{Arc, OnceLock};
/// Whether `MediaSource` is exposed to pages (`dom_media_source_enabled`).
/// On unless the environment sets `NACRE_DOM_MEDIA_SOURCE_ENABLED` to `0` or
/// `false`. Read once, when the first page asks.
pub fn enabled() -> bool {
static ENABLED: OnceLock<bool> = OnceLock::new();
*ENABLED.get_or_init(|| {
!matches!(
std::env::var("NACRE_DOM_MEDIA_SOURCE_ENABLED").as_deref(),
Ok("0") | Ok("false")
)
})
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ReadyState {
@ -29,42 +43,168 @@ pub enum MseError {
NotSupported(String),
InvalidState(String),
QuotaExceeded(String),
Type(String),
Backend(String),
}
/// Events the backend reports from its own threads. `buffer` is the index
/// returned by `MediaSourceBackend::add_source_buffer`.
/// Events the backend reports from its own threads. `buffer` is the id of a
/// `SourceBufferBackend` (`SourceBufferBackend::id`).
#[derive(Clone, Debug)]
pub enum MseEvent {
/// The backend finished attaching to the player's source element.
SourceOpen,
SourceEnded,
SourceClose,
UpdateEnd { buffer: usize },
Error { buffer: usize },
/// The duration changed inside the backend (an initialization segment, or
/// coded frames past the old duration).
DurationChange,
/// A SourceBuffer joined or left the active list.
ActiveChange,
}
pub type MseEventSink = Arc<dyn Fn(MseEvent) + Send + Sync>;
pub trait SourceBufferBackend: Send + Sync {
/// Unique per process; events name the buffer by it.
fn id(&self) -> usize;
fn append_buffer(&self, data: Vec<u8>) -> Result<(), MseError>;
/// Stops a running append and resets the parser state: the next append must start with an
/// initialization segment.
fn abort(&self) -> Result<(), MseError>;
/// Removes the coded frames in `start..end` (`end` may be infinite). Synchronous; the backend
/// then reports `UpdateEnd` for this buffer.
fn remove(&self, start: f64, end: f64) -> Result<(), MseError>;
fn buffered(&self) -> Vec<Range<f64>>;
fn set_sequence_mode(&self, sequence: bool) -> Result<(), MseError>;
/// Seconds; in sequence mode appends move it.
fn timestamp_offset(&self) -> f64;
fn set_timestamp_offset(&self, offset: f64) -> Result<(), MseError>;
fn set_append_window(&self, start: f64, end: f64) -> Result<(), MseError>;
fn updating(&self) -> bool;
/// Switches the byte stream format; `NotSupported` when the backend can't.
fn change_type(&self, mime: &str) -> Result<(), MseError>;
/// In the backend's active list (it has a selected or enabled track).
fn is_active(&self) -> bool;
}
pub trait MediaSourceBackend: Send + Sync {
fn add_source_buffer(
&self,
mime: &str,
) -> Result<(usize, Arc<dyn SourceBufferBackend>), MseError>;
fn add_source_buffer(&self, mime: &str) -> Result<Arc<dyn SourceBufferBackend>, MseError>;
/// Removes the buffer with this id (aborting a running append).
fn remove_source_buffer(&self, buffer: usize) -> Result<(), MseError>;
fn end_of_stream(&self, error: EndOfStreamError) -> Result<(), MseError>;
fn ready_state(&self) -> ReadyState;
/// Seconds; `f64::NAN` while unknown, `f64::INFINITY` for live streams.
fn duration(&self) -> f64;
fn set_duration(&self, duration: f64) -> Result<(), MseError>;
fn set_live_seekable_range(&self, range: Option<Range<f64>>) -> Result<(), MseError>;
/// The media element dropped this source (its load algorithm ran again).
fn detach(&self);
/// Lets the player downcast to its own backend type when it attaches.
fn as_any(&self) -> &dyn Any;
}
/// Ranges that are in both `a` and `b` (each sorted and disjoint).
pub fn intersect_ranges(a: &[Range<f64>], b: &[Range<f64>]) -> Vec<Range<f64>> {
let mut out = vec![];
let (mut i, mut j) = (0, 0);
while i < a.len() && j < b.len() {
let start = a[i].start.max(b[j].start);
let end = a[i].end.min(b[j].end);
if start < end {
out.push(start..end);
}
if a[i].end < b[j].end {
i += 1;
} else {
j += 1;
}
}
out
}
/// <https://w3c.github.io/media-source/#htmlmediaelement-extensions-buffered>: the ranges every
/// active SourceBuffer has. Once the source has ended, each buffer's last range counts as reaching
/// the highest end time of them all.
pub fn media_source_buffered(active: &[Vec<Range<f64>>], ended: bool) -> Vec<Range<f64>> {
let highest_end = active
.iter()
.filter_map(|ranges| ranges.last().map(|r| r.end))
.fold(f64::NAN, f64::max);
if active.is_empty() || highest_end.is_nan() {
return vec![];
}
let mut intersection = vec![0.0..highest_end];
for ranges in active {
let mut ranges = ranges.clone();
if ended && let Some(last) = ranges.last_mut() {
last.end = highest_end;
}
intersection = intersect_ranges(&intersection, &ranges);
}
intersection
}
/// <https://w3c.github.io/media-source/#htmlmediaelement-extensions-seekable>
pub fn media_source_seekable(
duration: f64,
buffered: &[Range<f64>],
live: Option<Range<f64>>,
) -> Vec<Range<f64>> {
if duration.is_nan() {
return vec![];
}
if duration.is_finite() {
return vec![0.0..duration];
}
if let Some(live) = live {
let start = buffered.first().map_or(live.start, |b| b.start.min(live.start));
let end = buffered.last().map_or(live.end, |b| b.end.max(live.end));
return vec![start..end];
}
match buffered.last() {
Some(last) => vec![0.0..last.end],
None => vec![],
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn intersect() {
let a = [0.0..2.0, 3.0..6.0];
let b = [1.0..4.0, 5.0..9.0];
assert_eq!(intersect_ranges(&a, &b), vec![1.0..2.0, 3.0..4.0, 5.0..6.0]);
assert_eq!(intersect_ranges(&a, &[]), vec![]);
}
#[test]
fn buffered_of_split_audio_video() {
let video = vec![0.0..5.0];
let audio = vec![0.0..4.8];
assert_eq!(media_source_buffered(&[video.clone(), audio.clone()], false), vec![0.0..4.8]);
// Ended: the shorter buffer's last range reaches the highest end.
assert_eq!(media_source_buffered(&[video, audio], true), vec![0.0..5.0]);
assert_eq!(media_source_buffered(&[], false), vec![]);
assert_eq!(media_source_buffered(&[vec![]], false), vec![]);
}
#[test]
fn buffered_keeps_gaps() {
let a = vec![0.0..2.0, 4.0..6.0];
let b = vec![0.0..6.0];
assert_eq!(media_source_buffered(&[a, b], false), vec![0.0..2.0, 4.0..6.0]);
}
#[test]
fn seekable() {
assert_eq!(media_source_seekable(f64::NAN, &[0.0..3.0], None), vec![]);
assert_eq!(media_source_seekable(10.0, &[], None), vec![0.0..10.0]);
assert_eq!(media_source_seekable(f64::INFINITY, &[], None), vec![]);
assert_eq!(media_source_seekable(f64::INFINITY, &[2.0..3.0, 5.0..8.0], None), vec![0.0..8.0]);
assert_eq!(
media_source_seekable(f64::INFINITY, &[5.0..8.0], Some(1.0..6.0)),
vec![1.0..8.0]
);
}
}

View file

@ -906,7 +906,9 @@ DOMInterfaces = {
},
'MediaSource': {
'cx': ['AddSourceBuffer', 'SourceBuffers', 'ActiveSourceBuffers', 'RemoveSourceBuffer'],
'cx': ['AddSourceBuffer'],
'weakReferenceable': True,
'additionalTraits': ['crate::interfaces::MediaSourceHelpers'],
},
'MediaQueryList': {
@ -1271,7 +1273,7 @@ DOMInterfaces = {
},
'SourceBuffer': {
'cx': ['Buffered', 'AppendBuffer', 'Abort'],
'cx': ['Buffered', 'AppendBuffer'],
},
'URL': {

View file

@ -126,6 +126,11 @@ pub trait DocumentHelpers {
fn ensure_safe_to_run_script_or_layout(&self);
}
pub trait MediaSourceHelpers {
/// `dom_media_source_enabled` (Nacre MSE): exposes MediaSource, SourceBuffer, SourceBufferList.
fn enabled(cx: &mut JSContext, global: HandleObject) -> bool;
}
pub trait ServoInternalsHelpers {
fn is_servo_internal(cx: &mut JSContext, global: HandleObject) -> bool;
}

View file

@ -8,7 +8,7 @@ enum ReadyState { "closed", "open", "ended" };
enum EndOfStreamError { "network", "decode" };
[Exposed=Window]
[Exposed=Window, Func="MediaSource::enabled"]
interface MediaSource : EventTarget {
[Throws] constructor();
[SameObject] readonly attribute SourceBufferList sourceBuffers;

View file

@ -6,7 +6,7 @@
enum AppendMode { "segments", "sequence" };
[Exposed=Window]
[Exposed=Window, Func="MediaSource::enabled"]
interface SourceBuffer : EventTarget {
[SetterThrows] attribute AppendMode mode;
readonly attribute boolean updating;

View file

@ -4,7 +4,7 @@
// https://w3c.github.io/media-source/#sourcebufferlist
[Exposed=Window]
[Exposed=Window, Func="MediaSource::enabled"]
interface SourceBufferList : EventTarget {
readonly attribute unsigned long length;
attribute EventHandler onaddsourcebuffer;

Some files were not shown because too many files have changed in this diff Show more