S026: msesrc waits for an active peer before pushing; split audio/video smoke case; patch write-up

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-12 11:58:53 -06:00
commit 45f2cfc72a
9 changed files with 499 additions and 35 deletions

View file

@ -0,0 +1,94 @@
# gst_mse patches (S026)
Nacre carries its own build of GStreamer's MSE library (`libgstmse-1.0`) and plugin (`mse`, element `msesrc`) from
gst-plugins-bad **1.28.9** (`vendor/gst-mse/`, LGPL-2.1, `COPYING` kept). Every change is marked `Nacre patch` in the
source; `vendor/gst-mse/nacre.patch` is the whole diff against the Debian 1.28.9-1 sources. This page is the write-up
for upstream. **No merge request has been opened** (that needs the user's OK).
Build and test: `tools/gst-mse.sh` (library and plugin into `target/gst-mse/`), `tools/gst-mse.sh test` (C tests in
`tests/gst-mse/mse-fixes.c`). Every test passes on the patched build; the tests for 1–3 fail on the system 1.28.9
(`LD_LIBRARY_PATH=/usr/lib`, no `GST_PLUGIN_PATH`).
## 1. update-end fires before the append is parsed
**What.** `append_to_buffer_task_func` (gstsourcebuffer.c) calls `gst_append_pipeline_append()` and signals
`on-update` / `on-update-end` right after. `gst_append_pipeline_append()` only queues the buffer and an
`end-of-append` event in appsrc. The samples reach the track buffers later, when the append pipeline's background
task handles the `end-of-append` bus message (`consume_all_samples`).
**Why it matters.** Players read `SourceBuffer.buffered` at `updateend` to decide what to fetch next. With 1.28.9 it
is still empty (or one append behind), so a player either fetches the same range again or stalls. Spec: the
"segment parser loop" runs the coded frame processing before "the buffer append" algorithm fires `update` and
`updateend`.
**Fix.** `GstAppendPipeline` counts appends sent and appends done (`appends_sent`, `appends_done`, a mutex and a
cond). `gst_append_pipeline_append()` takes a ticket and waits until the background task has handled that append's
`end-of-append` (after `consume_all_samples`), or the pipeline shut down, aborted or failed (`finish_appends(all)`),
or 10 s passed (a warning; a stuck parser must not leave the buffer updating forever). The append task drops the
source buffer's object lock while it waits, because the new-sample callback takes that lock; `updating` stays set, so
no second append can start, and the task re-checks `is_removed` after re-locking.
**Test.** `/mse/update-end-after-parse`: append a whole WebM clip (init + media) in one call; at the first
update-end, `gst_source_buffer_get_buffered()` must be non-empty. System 1.28.9: 0 ranges.
## 2. update / update-end every second while idle
**What.** The append task waits for pending data with a 1 s timeout. On timeout it took the "no pending data" branch
and called `append_successful_unlocked()`, which schedules `on-update` and `on-update-end`.
**Why it matters.** A page sees `update`/`updateend` without having appended anything, every second. Players that
chain the next append on `updateend` append twice, or hit `InvalidStateError` because they think the buffer is free.
**Fix.** The "no pending data" branch returns without signalling.
**Test.** `/mse/no-idle-updates`: no signals during 3 s idle; one append gives exactly one `update` and one
`update-end`; 3 s more idle add none. System 1.28.9: 3 updates in the first 3 s.
## 3. msesrc exposes streams before every SourceBuffer has an init segment
**What.** `gst_mse_src_emit_streams()` (gstmsesrc.c) runs on every SourceBuffer's first init segment and exposes the
tracks it knows right away. `update_ready_state_for_init_segment()` checks whether every buffer has an init segment,
but only to set HAVE_METADATA, and its "not yet" path returned with `media_source_lock` still held.
**Why it matters.** Sites with separate audio and video SourceBuffers (YouTube always) append one init segment before
the other. msesrc exposed the first buffer's track alone, playbin prerolled on it and never took the second, so the
element stayed at HAVE_NOTHING. The leaked mutex then deadlocked the ready-state task and every later caller of
`MEDIA_SOURCE_LOCK` (attach, detach, seek). Spec: "init segment received" step 5 moves to HAVE_METADATA only once
every SourceBuffer in `activeSourceBuffers` has received one; WebKit's GStreamer MSE also waits for all of them.
**Fix.** `update_ready_state_for_init_segment()` returns whether every buffer has its init segment (TRUE once past
HAVE_NOTHING, or when detached), always unlocks, and releases the buffer list it was leaking. `emit_streams()`
returns early, exposing nothing, until it is TRUE. Each call passes all tracks of all buffers, so the last init
segment exposes every stream at once with one stream collection.
**Test.** `/mse/split-audio-video`: playbin3 on `mse://`, a video-only WebM (VP9) SourceBuffer and an audio-only
fMP4 (AAC) SourceBuffer; the video clip is appended, then 2 s later the audio. During those 2 s msesrc has
`n-video = n-audio = 0` and `ready-state = HAVE_NOTHING`; after the audio append both are 1, and playback passes
1 s. System 1.28.9: `n-video = 1` after the video append alone.
## 4. msesrc pad task gives up when its peer is not active yet
**What.** `pad_task` (gstmsesrc.c) waits until its pad is linked, pops a sample from the track and pushes it. Under
playbin3, urisourcebin links each new msesrc pad to a fresh typefind element and only then activates that element,
and linking resumes the pad task. A push in that gap returns `GST_FLOW_FLUSHING`; the task treated it as a flush,
paused for good, and the popped sample was lost. That stream never started, playbin3 waited for it, and the element
stayed at HAVE_NOTHING. Which stream lost depends on the order of the streams hash table and on timing: about one
start in four in Nacre's split smoke page, one in eight of the C test under CPU load, none when idle.
**Why it matters.** It hits every multi-stream MediaSource, but split audio/video (patch 3, YouTube) makes it common,
because both pads appear at once.
**Fix.** Before taking data from the track, the task checks whether the peer pad is still flushing (not activated);
if so it sleeps 10 ms and returns, so the task loops until the peer is ready. Sticky events pushed meanwhile stay
on the pad and go out with the first buffer.
**Test.** `/mse/split-audio-video` runs its scenario in `SPLIT_ROUNDS` fresh processes (default 4) with playbin3 set up
like Servo's player (appsink sinks, `download` flag, 500 MiB `buffer-size`). The race needs load to show there (2 of
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.
## 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).

View file

@ -3,7 +3,11 @@
* /mse/update-end-after-parse bug 1: `buffered` is current at the first update-end of an append
* /mse/no-idle-updates bug 2: no update / update-end while nothing is appended
* /mse/split-audio-video bug 3: separate audio and video SourceBuffers, video appended 2 s
* before audio, expose no stream until both have an init segment, then play
* before audio, expose no stream until both have an init segment, then play;
* SPLIT_ROUNDS times (default 4), each in a fresh process, with playbin3 set
* up like Servo's player: the stream whose pad task started before
* urisourcebin activated its typefind hung in about one fresh process of
* eight (msesrc pad task, patch 4)
*
* 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:
@ -13,6 +17,7 @@
* (all three fail there).
*/
#include <stdlib.h>
#include <gst/gst.h>
#include <gst/mse/mse.h>
@ -196,7 +201,8 @@ test_no_idle_updates (void)
counter_clear (&c);
}
/* playbin on mse://, both sinks fakesink (no audio device in test runs). */
/* 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
{
GstElement *playbin;
@ -234,22 +240,29 @@ position (GstElement * playbin)
return pos;
}
static GstElement *
new_appsink (void)
{
GstElement *sink = gst_element_factory_make ("appsink", NULL);
g_object_set (sink, "sync", TRUE, "drop", TRUE, "max-buffers", 2, NULL);
return sink;
}
static void
test_split_audio_video (void)
split_audio_video_round (void)
{
Player p = { 0 };
g_mutex_init (&p.lock);
g_cond_init (&p.cond);
p.source = gst_media_source_new ();
g_signal_connect (p.source, "on-source-open", G_CALLBACK (on_source_open), &p);
p.playbin = gst_element_factory_make ("playbin", NULL);
p.playbin = gst_element_factory_make ("playbin3", NULL);
g_assert_nonnull (p.playbin);
GstElement *vsink = gst_element_factory_make ("fakesink", NULL);
GstElement *asink = gst_element_factory_make ("fakesink", NULL);
g_object_set (vsink, "sync", TRUE, NULL);
g_object_set (asink, "sync", TRUE, NULL);
g_object_set (p.playbin, "uri", "mse://test", "video-sink", vsink,
"audio-sink", asink, NULL);
guint flags;
g_object_get (p.playbin, "flags", &flags, NULL);
g_object_set (p.playbin, "uri", "mse://test", "video-sink", new_appsink (),
"audio-sink", new_appsink (), "buffer-size", 500 * 1024 * 1024,
"flags", flags | 0x80 /* download */ , NULL);
g_signal_connect (p.playbin, "source-setup", G_CALLBACK (on_source_setup), &p);
gst_element_set_state (p.playbin, GST_STATE_PAUSED);
@ -321,6 +334,24 @@ test_split_audio_video (void)
g_cond_clear (&p.cond);
}
static void
test_split_audio_video (void)
{
if (g_test_subprocess ()) {
split_audio_video_round ();
return;
}
const gchar *env = g_getenv ("SPLIT_ROUNDS");
gint rounds = env ? atoi (env) : 4;
for (gint i = 0; i < rounds; i++) {
g_test_trap_subprocess (NULL, 30 * G_USEC_PER_SEC,
G_TEST_SUBPROCESS_INHERIT_STDERR);
g_test_message ("round %d: %s", i + 1,
g_test_trap_has_passed ()? "played" : "failed");
g_test_trap_assert_passed ();
}
}
int
main (int argc, char **argv)
{

View file

@ -1,6 +1,6 @@
# 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).
# 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).
wait 3
open @PAGES@/mse-basic.html
waitload 30
@ -17,5 +17,15 @@ waitfor 20 window.mse.time > 1.5
shot mse-webm
assert window.mse.errors.length === 0
js JSON.stringify(window.mse)
# S026: separate video and audio SourceBuffers (video appended 2 s before audio), as YouTube does
open @PAGES@/mse-basic.html?split
waitload 30
assert window.mse.supported === true
waitfor 30 window.mse && window.mse.stage === 'ended'
waitfor 20 window.mse.time > 1.5
assert window.mse.videoWidth > 0
shot mse-split
assert window.mse.errors.length === 0
js JSON.stringify(window.mse)
status done
quit

View file

@ -1,9 +1,11 @@
<!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. -->
?webm, mse-clip-webm.js (VP9 + Opus) in 32 KiB appendBuffer chunks. With ?split (S026) it uses two
SourceBuffers like YouTube: mse-clip-video.js (VP9 WebM, video only) is appended first, then after 2 s
mse-clip-audio.js (AAC fMP4, audio only). 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
(the smallest over the buffers), currentTime, readyState, videoWidth, 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; }
@ -16,8 +18,12 @@
<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 split = location.search.includes('split');
const tracks = split
? [{ file: 'mse-clip-video.js', mime: 'video/webm; codecs="vp9"' },
{ file: 'mse-clip-audio.js', mime: 'audio/mp4; codecs="mp4a.40.2"', delay: 2000 }]
: [{ file: webm ? 'mse-clip-webm.js' : 'mse-clip-mp4.js',
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); };
@ -36,31 +42,20 @@ function update() {
const v = document.getElementById('v');
mse.time = v.currentTime;
mse.readyState = v.readyState;
mse.videoWidth = v.videoWidth;
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; }
// Appends data to sb in 32 KiB chunks, one per updateend; resolves when all of it is in.
function append(sb, data) {
return new Promise((resolve) => {
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);
sb.removeEventListener('updateend', next);
resolve();
return;
}
sb.appendBuffer(data.slice(offset, offset + 32768));
@ -68,9 +63,42 @@ async function run() {
mse.chunks++;
};
sb.addEventListener('updateend', next);
sb.addEventListener('error', () => fail('SourceBuffer error'));
next();
});
}
const bufferedEnd = (sb) => (sb.buffered.length ? sb.buffered.end(sb.buffered.length - 1) : 0);
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function run() {
if (!window.MediaSource) { mse.stage = 'no MediaSource'; return; }
mse.supported = tracks.every((t) => MediaSource.isTypeSupported(t.mime));
for (const t of tracks) log('isTypeSupported ' + MediaSource.isTypeSupported(t.mime) + ' ' + t.mime);
for (const t of tracks) t.data = await load(t.file);
const v = document.getElementById('v');
const ms = new MediaSource();
ms.addEventListener('sourceopen', async () => {
mse.stage = 'open';
log('sourceopen readyState ' + ms.readyState);
try {
for (const t of tracks) {
t.sb = ms.addSourceBuffer(t.mime);
t.sb.addEventListener('error', () => fail('SourceBuffer error ' + t.mime));
}
} catch (e) { fail(e); return; }
for (const t of tracks) {
if (t.delay) {
await sleep(t.delay);
log('before ' + t.mime + ': readyState ' + v.readyState);
}
await append(t.sb, t.data);
}
mse.buffered = Math.min(...tracks.map((t) => bufferedEnd(t.sb)));
ms.endOfStream();
mse.stage = 'ended';
log('endOfStream buffered ' + mse.buffered + ' duration ' + ms.duration);
v.play().then(() => log('playing'), fail);
});
ms.addEventListener('sourceended', () => log('sourceended'));
v.addEventListener('error', () => fail('video error ' + (v.error && v.error.message)));
v.src = URL.createObjectURL(ms);

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,20 @@
# YouTube over MSE (S026): the watch page of heavy-web.txt, then the player's state at 5, 15 and 30 s after play:
# codecs (the player's stats for nerds), readyState, currentTime, videoWidth, buffered. Needs internet,
# SMOKE_TIMEOUT=300. Read yt-mse-*.png for the picture. A probe, not a pass/fail test: it asserts only that the
# watch page loads.
wait 3
open https://www.youtube.com/watch?v=jNQXAC9IVRw
waitfor 120 location.pathname === "/watch" && !!document.querySelector("video")
wait 5
js (() => { const v = document.querySelector("video"); v.muted = true; v.play().catch(() => {}); return "play"; })()
wait 5
js (() => { const v = document.querySelector("video"), p = document.getElementById("movie_player"), s = p && p.getStatsForNerds ? p.getStatsForNerds() : {}; const b = v.buffered; return JSON.stringify({ t: 5, codecs: s.codecs, resolution: s.resolution, readyState: v.readyState, currentTime: v.currentTime, videoWidth: v.videoWidth, buffered: b.length ? b.end(b.length - 1) : 0, paused: v.paused, src: v.currentSrc.slice(0, 40), error: v.error && v.error.message, ytError: document.querySelector("#movie_player .ytp-error") ? document.querySelector("#movie_player .ytp-error").innerText.slice(0, 80) : null }); })()
shot yt-mse-5s
wait 10
js (() => { const v = document.querySelector("video"), p = document.getElementById("movie_player"), s = p && p.getStatsForNerds ? p.getStatsForNerds() : {}; return JSON.stringify({ t: 15, codecs: s.codecs, readyState: v.readyState, currentTime: v.currentTime, videoWidth: v.videoWidth, paused: v.paused }); })()
shot yt-mse-15s
wait 15
js (() => { const v = document.querySelector("video"), p = document.getElementById("movie_player"), s = p && p.getStatsForNerds ? p.getStatsForNerds() : {}; return JSON.stringify({ t: 30, codecs: s.codecs, readyState: v.readyState, currentTime: v.currentTime, videoWidth: v.videoWidth, paused: v.paused, ended: v.ended }); })()
shot yt-mse-30s
status done
quit

View file

@ -973,6 +973,21 @@ pad_task (GstMseSrcPad * pad)
goto pause;
}
/* Nacre patch: urisourcebin links a new pad to a typefind element before it
* activates that element, and linking resumes this task. Pushing then gets
* FLUSHING, which paused the task for good and dropped the sample it had
* popped, so that stream never started (the pad order is the streams hash
* table's, so either stream of a split audio/video source could hang). Wait
* for the peer to become active before taking data from the track. */
GstPad *peer = gst_pad_get_peer (GST_PAD (pad));
gboolean peer_inactive = peer != NULL && GST_PAD_IS_FLUSHING (peer);
gst_clear_object (&peer);
if (peer_inactive) {
GST_TRACE_OBJECT (pad, "peer is not active yet");
g_usleep (10 * 1000);
return;
}
self = GST_MSE_SRC (gst_pad_get_parent_element (GST_PAD (pad)));
GstMediaSourceTrack *track = pad->track;

262
vendor/gst-mse/nacre.patch vendored Normal file
View file

@ -0,0 +1,262 @@
Nacre patches to gst-plugins-bad 1.28.9 gst-libs/gst/mse (docs/engine/gst-mse-patches.md).
Base: https://sources.debian.org/src/gst-plugins-bad1.0/1.28.9-1/ . Apply with patch -p1 in gst-plugins-bad.
--- a/gst-libs/gst/mse/gstappendpipeline.c
+++ b/gst-libs/gst/mse/gstappendpipeline.c
@@ -95,6 +95,14 @@
gboolean encountered_error;
+ /* Nacre patch: appends pushed and appends whose end-of-append marker the
+ * background task has handled (samples handed to the source buffer), so
+ * gst_append_pipeline_append() can return only once its data is parsed. */
+ GMutex append_lock;
+ GCond append_cond;
+ guint64 appends_sent;
+ guint64 appends_done;
+
BackgroundTask *task;
Callbacks callbacks;
@@ -108,6 +116,21 @@
static void process_init_segment (GstAppendPipeline *);
+/* Nacre patch: one more append is fully processed, or (all) every append is
+ * settled because the pipeline stopped, failed or was reset. */
+static void
+finish_appends (GstAppendPipeline * self, gboolean all)
+{
+ g_mutex_lock (&self->append_lock);
+ if (all) {
+ self->appends_done = self->appends_sent;
+ } else if (self->appends_done < self->appends_sent) {
+ self->appends_done++;
+ }
+ g_cond_broadcast (&self->append_cond);
+ g_mutex_unlock (&self->append_lock);
+}
+
static gboolean
send_abort (GstAppendPipeline * self)
{
@@ -313,12 +336,14 @@
call_eos (self, track->mse_track);
}
call_eos (self, NULL);
+ finish_appends (self, TRUE);
}
static void
handle_abort (BackgroundTask * task)
{
gst_task_stop (task->task);
+ finish_appends (task->pipeline, TRUE);
}
static void
@@ -332,6 +357,7 @@
if (gst_message_has_name (message, END_OF_APPEND)) {
GST_TRACE_OBJECT (self, "end of append");
consume_all_samples (self);
+ finish_appends (self, FALSE);
goto done;
}
if (gst_message_has_name (message, SHUTDOWN)) {
@@ -742,6 +768,11 @@
self->encountered_error = FALSE;
self->tracks = new_tracks_array ();
init_segment_init (&self->init_segment);
+
+ g_mutex_init (&self->append_lock);
+ g_cond_init (&self->append_cond);
+ self->appends_sent = 0;
+ self->appends_done = 0;
}
static void
@@ -770,6 +801,9 @@
g_array_free (self->tracks, TRUE);
gst_clear_object (&self->streams);
+ g_mutex_clear (&self->append_lock);
+ g_cond_clear (&self->append_cond);
+
G_OBJECT_CLASS (gst_append_pipeline_parent_class)->finalize (object);
}
@@ -815,19 +849,48 @@
return NULL;
}
+/* Nacre patch: an append that never settles (a stuck parser) would leave the
+ * source buffer updating forever; give up waiting after this long. */
+#define APPEND_TIMEOUT (10 * G_TIME_SPAN_SECOND)
+
+/* Nacre patch: blocks until the background task has handled this append's
+ * end-of-append marker, i.e. every sample parsed from @buffer has been handed
+ * to the source buffer (consume_all_samples), so `buffered` is current when the
+ * caller signals update-end. Upstream returned once the bytes were queued in
+ * appsrc. Must be called without locks the new-sample callback takes. */
GstFlowReturn
gst_append_pipeline_append (GstAppendPipeline * self, GstBuffer * buffer)
{
g_return_val_if_fail (GST_IS_APPEND_PIPELINE (self), GST_FLOW_ERROR);
+
+ g_mutex_lock (&self->append_lock);
+ guint64 ticket = ++self->appends_sent;
+ g_mutex_unlock (&self->append_lock);
+
GstFlowReturn push_result = gst_app_src_push_buffer (self->src, buffer);
- if (push_result != GST_FLOW_OK)
+ if (push_result != GST_FLOW_OK) {
+ finish_appends (self, FALSE);
return push_result;
+ }
if (!gst_element_send_event (GST_ELEMENT_CAST (self->src),
new_end_of_append_event ())) {
GST_ERROR_OBJECT (self, "failed to push end-of-append event");
+ finish_appends (self, FALSE);
return GST_FLOW_ERROR;
}
+
+ gint64 deadline = g_get_monotonic_time () + APPEND_TIMEOUT;
+ g_mutex_lock (&self->append_lock);
+ while (self->appends_done < ticket) {
+ if (!g_cond_wait_until (&self->append_cond, &self->append_lock, deadline)) {
+ GST_WARNING_OBJECT (self, "append %" G_GUINT64_FORMAT " not processed "
+ "after %" G_GINT64_FORMAT " s, giving up waiting", ticket,
+ APPEND_TIMEOUT / G_TIME_SPAN_SECOND);
+ break;
+ }
+ }
+ g_mutex_unlock (&self->append_lock);
return GST_FLOW_OK;
}
--- a/gst-libs/gst/mse/gstsourcebuffer.c
+++ b/gst-libs/gst/mse/gstsourcebuffer.c
@@ -1761,13 +1761,26 @@
}
if (!GST_IS_BUFFER (pending_data)) {
+ /* Nacre patch: the wait above times out every second; with nothing
+ * appended there is nothing to report. Upstream signalled update and
+ * update-end here, a spurious pair every second while idle. */
GST_TRACE_OBJECT (self, "no pending data");
- append_successful_unlocked (self, is_ended_unlocked (self));
goto done;
}
- GstFlowReturn result = gst_append_pipeline_append (self->append_pipeline,
- pending_data);
+ /* Nacre patch: the append now waits until its samples reach the track
+ * 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);
+ GST_OBJECT_UNLOCK (self);
+ GstFlowReturn result = gst_append_pipeline_append (pipeline, pending_data);
+ gst_object_unref (pipeline);
+ GST_OBJECT_LOCK (self);
+
+ if (is_removed_unlocked (self)) {
+ append_successful_unlocked (self, TRUE);
+ goto done;
+ }
if (result != GST_FLOW_OK) {
GST_ERROR_OBJECT (self, "failed to append: %s", gst_flow_get_name (result));
--- a/gst-libs/gst/mse/gstmsesrc.c
+++ b/gst-libs/gst/mse/gstmsesrc.c
@@ -266,7 +266,7 @@
static GstStateChangeReturn gst_mse_src_change_state (GstElement * element,
GstStateChange transition);
static gboolean gst_mse_src_send_event (GstElement * element, GstEvent * event);
-static void update_ready_state_for_init_segment (GstMseSrc * self);
+static gboolean update_ready_state_for_init_segment (GstMseSrc * self);
static void update_ready_state (GstMseSrc * self);
G_DEFINE_TYPE_WITH_CODE (GstMseSrc, gst_mse_src, GST_TYPE_ELEMENT,
@@ -973,6 +973,21 @@
goto pause;
}
+ /* Nacre patch: urisourcebin links a new pad to a typefind element before it
+ * activates that element, and linking resumes this task. Pushing then gets
+ * FLUSHING, which paused the task for good and dropped the sample it had
+ * popped, so that stream never started (the pad order is the streams hash
+ * table's, so either stream of a split audio/video source could hang). Wait
+ * for the peer to become active before taking data from the track. */
+ GstPad *peer = gst_pad_get_peer (GST_PAD (pad));
+ gboolean peer_inactive = peer != NULL && GST_PAD_IS_FLUSHING (peer);
+ gst_clear_object (&peer);
+ if (peer_inactive) {
+ GST_TRACE_OBJECT (pad, "peer is not active yet");
+ g_usleep (10 * 1000);
+ return;
+ }
+
self = GST_MSE_SRC (gst_pad_get_parent_element (GST_PAD (pad)));
GstMediaSourceTrack *track = pad->track;
@@ -1216,7 +1231,15 @@
GstElement *element = GST_ELEMENT (self);
GstObject *object = GST_OBJECT (self);
- update_ready_state_for_init_segment (self);
+ /* Nacre patch: expose no stream until every SourceBuffer of the attached
+ * MediaSource has received its first init segment (MSE "init segment
+ * received" step 5 / HAVE_METADATA). Exposing the first buffer's tracks alone
+ * made playbin preroll on them and never take the later ones, so separate
+ * audio and video SourceBuffers stalled at HAVE_NOTHING. */
+ if (!update_ready_state_for_init_segment (self)) {
+ GST_DEBUG_OBJECT (self, "waiting for every source buffer's init segment");
+ return;
+ }
STREAMS_LOCK (self);
@@ -1337,9 +1360,15 @@
g_object_notify_by_pspec (G_OBJECT (self), properties[PROP_READY_STATE]);
}
-static void
+/* Nacre patch: returns whether every source buffer has received an init
+ * segment (TRUE once past HAVE_NOTHING, or when detached), and no longer leaves
+ * media_source_lock held on the "not yet" path, which deadlocked the ready
+ * state task and anything else taking that lock. */
+static gboolean
update_ready_state_for_init_segment (GstMseSrc * self)
{
+ gboolean all_received_init_segment = TRUE;
+
MEDIA_SOURCE_LOCK (self);
if (self->media_source == NULL) {
@@ -1350,7 +1379,6 @@
}
GstSourceBufferList *buffers = gst_media_source_get_source_buffers
(self->media_source);
- gboolean all_received_init_segment = TRUE;
for (guint i = 0; all_received_init_segment; i++) {
GstSourceBuffer *buf = gst_source_buffer_list_index (buffers, i);
if (buf == NULL) {
@@ -1359,14 +1387,16 @@
all_received_init_segment &= gst_source_buffer_has_init_segment (buf);
gst_object_unref (buf);
}
+ gst_object_unref (buffers);
if (!all_received_init_segment) {
- return;
+ goto done;
}
set_ready_state (self, MAX (self->ready_state,
GST_MSE_SRC_READY_STATE_HAVE_METADATA));
done:
MEDIA_SOURCE_UNLOCK (self);
+ return all_received_init_segment;
}
static gboolean