diff --git a/docs/engine/gst-mse-patches.md b/docs/engine/gst-mse-patches.md index c6b35fa..d2f03bb 100644 --- a/docs/engine/gst-mse-patches.md +++ b/docs/engine/gst-mse-patches.md @@ -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. diff --git a/tests/gst-mse/mse-fixes.c b/tests/gst-mse/mse-fixes.c index 67ea9b7..c6b03f7 100644 --- a/tests/gst-mse/mse-fixes.c +++ b/tests/gst-mse/mse-fixes.c @@ -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 @@ -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 (); } diff --git a/tests/smoke/mse-leak-check.sh b/tests/smoke/mse-leak-check.sh new file mode 100755 index 0000000..d715742 --- /dev/null +++ b/tests/smoke/mse-leak-check.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# Leak check for tests/smoke/mse.txt (S027): in /nacre.log, the leak case's MediaSource (the second-to-last +# "MSE: MediaSource 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 +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 diff --git a/tests/smoke/mse-off.txt b/tests/smoke/mse-off.txt new file mode 100644 index 0000000..8a2cd1c --- /dev/null +++ b/tests/smoke/mse-off.txt @@ -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 diff --git a/tests/smoke/mse.txt b/tests/smoke/mse.txt index 27b071b..0eb8cb5 100644 --- a/tests/smoke/mse.txt +++ b/tests/smoke/mse.txt @@ -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 : +# the leak case's MediaSource must be freed during the run ("MSE: MediaSource 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 status done quit diff --git a/tests/smoke/pages/mse-spec.html b/tests/smoke/pages/mse-spec.html new file mode 100644 index 0000000..cec86aa --- /dev/null +++ b/tests/smoke/pages/mse-spec.html @@ -0,0 +1,302 @@ + + + +MSE spec + + + +
+ + + diff --git a/tests/wpt-mse/driver.html b/tests/wpt-mse/driver.html new file mode 100644 index 0000000..eaa503e --- /dev/null +++ b/tests/wpt-mse/driver.html @@ -0,0 +1,50 @@ + + + +WPT MSE + + + + + +

+
+
+
diff --git a/tests/wpt-mse/server.py b/tests/wpt-mse/server.py
new file mode 100755
index 0000000..9eaa3b3
--- /dev/null
+++ b/tests/wpt-mse/server.py
@@ -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    
+"""
+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()
diff --git a/tests/wpt-mse/testharnessreport.js b/tests/wpt-mse/testharnessreport.js
new file mode 100644
index 0000000..9d90740
--- /dev/null
+++ b/tests/wpt-mse/testharnessreport.js
@@ -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 || '' }; }),
+  };
+});
diff --git a/tools/wpt-mse.sh b/tools/wpt-mse.sh
new file mode 100755
index 0000000..29c63ba
--- /dev/null
+++ b/tools/wpt-mse.sh
@@ -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 /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" <