Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 73 additions & 1 deletion backend/src/blocks/builtin/mediaplayer/bridge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use super::state::MediaPlayerState;
use super::timing;
use crate::blocks::BlockBuildError;
use crate::events::EventBroadcaster;
use crate::gst::rtp_hdrext;
use crate::gst::{context_forward, rtp_hdrext};
use gstreamer as gst;
use gstreamer::prelude::*;
use gstreamer_app as gst_app;
Expand Down Expand Up @@ -200,10 +200,26 @@ pub fn create_decode_pipeline(
// An `rtsp://` URI makes the source bin autoplug an RTP depayloader, so this
// internal pipeline needs the same gstreamer#5057 workaround as the main one.
rtp_hdrext::install(&pipeline);
share_flow_contexts(&pipeline, state);

Ok(pipeline)
}

/// Let the internal pipeline use the flow's GL context (#1099). A decoder that
/// outputs GL memory, VideoToolbox on macOS, otherwise hands the flow frames
/// from a GL context of its own, which no GL element in the flow can convert.
///
/// Only decode mode needs it: passthrough carries encoded media. The flow's
/// GL elements make their display when the flow goes to READY, and the
/// internal pipeline starts once the flow plays, so it asks for a display the
/// flow already has. A stinger clip may preroll earlier, but its appsink takes
/// system memory, so it makes no GL context of its own.
fn share_flow_contexts(pipeline: &gst::Pipeline, state: &MediaPlayerState) {
if let Some(appsrc) = state.flow_anchor() {
context_forward::install(pipeline, appsrc);
}
}

/// Create the internal pipeline for passthrough mode.
///
/// Pipeline: `urisourcebin(parse-streams=true)` → (pad-added) → `clocksync` → `appsink`
Expand Down Expand Up @@ -1594,6 +1610,62 @@ mod tests {
}
}

/// In decode mode the internal pipeline asks the flow for its GL context
/// and gives the flow the one it makes (#1099). A GL decoder in it would
/// otherwise make a GL context of its own, and its frames would fail at
/// the flow's first GL converter. The contexts here carry a test value, so
/// no GL is needed; `mediaplayer_gl_context_test` runs real GL frames.
#[test]
fn the_decode_pipeline_shares_the_flows_gl_context() {
let _ = gst::init();
const TYPE: &str = "gst.gl.app_context";
let context = |value: &str| {
let mut context = gst::Context::new(TYPE, true);
context
.get_mut()
.unwrap()
.structure_mut()
.set("value", value);
context
};
let value = |context: Option<gst::Context>| {
context.and_then(|c| c.structure().get::<String>("value").ok())
};

let state = state_with_slots(1, 1);
let flow = gst::Pipeline::new();
flow.add(&state.video_appsrcs[0]).unwrap();
flow.set_context(&context("flow"));
let internal = create_decode_pipeline("mp", &state, None, Decoder::Decodebin3).unwrap();
let source = internal.by_name("mp_uridecodebin3").unwrap();

source
.post_message(
gst::message::NeedContext::builder(TYPE)
.src(&source)
.build(),
)
.unwrap();
assert_eq!(
value(source.context(TYPE)),
Some("flow".to_string()),
"the flow answers the decoder's request"
);

const MADE: &str = "gst.gl.GLDisplay";
source
.post_message(
gst::message::HaveContext::builder(gst::Context::new(MADE, true))
.src(&source)
.build(),
)
.unwrap();
assert!(
flow.context(MADE).is_some(),
"the flow keeps a GL display the internal pipeline made"
);
}

#[test]
fn decodebin3_is_the_default_and_classic_stays_on_request() {
assert_eq!(Decoder::from_property(None), Decoder::Decodebin3);
Expand Down
6 changes: 1 addition & 5 deletions backend/src/blocks/builtin/mediaplayer/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -413,11 +413,7 @@ fn connect_main_pipeline_handler(

// Store main pipeline reference for timestamp offset computation in the bridge.
// The appsrc lives in the main pipeline, so we traverse up from it to find the pipeline.
if let Some(appsrc) = state
.video_appsrcs
.first()
.or_else(|| state.audio_appsrcs.first())
{
if let Some(appsrc) = state.flow_anchor() {
let mut current: Option<gst::Object> =
Some(appsrc.clone().upcast::<gst::Element>().upcast());
while let Some(obj) = current {
Expand Down
9 changes: 9 additions & 0 deletions backend/src/blocks/builtin/mediaplayer/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,15 @@ impl ParkFlags {
pub const CUE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);

impl MediaPlayerState {
/// The block's element in the flow that stands for it: its first video
/// output, else its first audio output. Finds the flow's pipeline, and is
/// where the internal pipeline's context messages are posted.
pub fn flow_anchor(&self) -> Option<&gst_app::AppSrc> {
self.video_appsrcs
.first()
.or_else(|| self.audio_appsrcs.first())
}

/// `n` free slots.
pub fn free_slots(n: usize) -> Mutex<Vec<Option<String>>> {
Mutex::new(vec![None; n])
Expand Down
185 changes: 185 additions & 0 deletions backend/src/gst/context_forward.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
//! Share a flow's GL context with a pipeline a block runs of its own.
//!
//! A pipeline shares contexts among its elements: an element that needs one
//! posts `NEED_CONTEXT`, and the bin answers from the contexts it has cached
//! from earlier `HAVE_CONTEXT` messages. Two pipelines share nothing, so a
//! block that decodes in a pipeline of its own and hands the frames to the
//! flow over an appsink/appsrc pair ends up with two GL contexts. GL memory is
//! only usable in the context that made it, and the first GL element in the
//! flow that converts such a frame fails:
//!
//! ```text
//! glcolorconvert0 input memory OpenGL context is different. we have <glcontext…1> memory has <glcontext…0>
//! ```
//!
//! [`install`] posts the internal pipeline's `NEED_CONTEXT` and
//! `HAVE_CONTEXT` messages again from an element in the flow. The flow's bin
//! then answers the internal pipeline's requests from its cache and caches
//! what the internal pipeline creates, so both sides use the same context,
//! whichever pipeline asks first. webrtcsink does the same for its session
//! pipelines.
//!
//! Only GL context types go through. CUDA and D3D memory cross between
//! pipelines without a shared context (measured, #1099). Their contexts are
//! tied to a device, and a bin caches one context per type, so forwarding an
//! internal decoder's CUDA context or D3D device would replace the flow's own
//! on a host where the two use different GPUs.
//!
//! Two flows cannot share a context this way: each starts and stops on its
//! own. See issue #1099.

use gstreamer as gst;
use gstreamer::prelude::*;

/// Hand `internal`'s GL context requests and GL contexts to the pipeline that
/// `flow_element` is in.
///
/// Holds `flow_element` weakly: once the flow is torn down, the messages stay
/// in `internal` as if this were never installed. A message posted while
/// `flow_element` has no parent yet reaches no bin, and the internal pipeline
/// makes its own context, as it would without this.
///
/// Installs `internal`'s bus sync handler. A bus has only one, so `internal`
/// must not need another.
pub fn install(internal: &gst::Pipeline, flow_element: &impl IsA<gst::Element>) {
let Some(bus) = internal.bus() else {
return;
};
let target = flow_element.as_ref().downgrade();
bus.set_sync_handler(move |_, msg| {
let gl = match msg.view() {
gst::MessageView::NeedContext(m) => is_gl_context_type(m.context_type()),
gst::MessageView::HaveContext(m) => is_gl_context_type(m.context().context_type()),
_ => false,
};
if gl {
if let Some(target) = target.upgrade() {
let _ = target.post_message(msg.clone());
}
}
gst::BusSyncReply::Pass
});
}

/// The context types GStreamer's GL library asks for and posts: the GL
/// display, the application's and the local GL context, and the window
/// system display handles a GL display is made from.
fn is_gl_context_type(context_type: &str) -> bool {
context_type.starts_with("gst.gl.")
|| context_type == "gst.x11.display.handle"
|| context_type == "GstWaylandDisplayHandleContextType"
}

#[cfg(test)]
mod tests {
use super::*;

/// A GL context type, carrying a test value instead of a display: no GL
/// element is in these pipelines to read it.
const CONTEXT_TYPE: &str = "gst.gl.app_context";

fn context(value: &str) -> gst::Context {
let mut context = gst::Context::new(CONTEXT_TYPE, true);
context
.get_mut()
.unwrap()
.structure_mut()
.set("value", value);
context
}

fn value(context: Option<gst::Context>) -> Option<String> {
context.and_then(|c| c.structure().get::<String>("value").ok())
}

/// A flow with one element in it, and an internal pipeline with one
/// element in it, wired with [`install`].
fn rig() -> (gst::Pipeline, gst::Pipeline, gst::Element) {
gst::init().unwrap();
let flow = gst::Pipeline::new();
let flow_element = gst::ElementFactory::make("fakesink").build().unwrap();
flow.add(&flow_element).unwrap();
let internal = gst::Pipeline::new();
let inner = gst::ElementFactory::make("fakesrc").build().unwrap();
internal.add(&inner).unwrap();
install(&internal, &flow_element);
(flow, internal, inner)
}

#[test]
fn a_request_from_inside_is_answered_by_the_flow() {
let (flow, _internal, inner) = rig();
flow.set_context(&context("from the flow"));

inner
.post_message(
gst::message::NeedContext::builder(CONTEXT_TYPE)
.src(&inner)
.build(),
)
.unwrap();

assert_eq!(
value(inner.context(CONTEXT_TYPE)),
Some("from the flow".into())
);
}

#[test]
fn a_context_made_inside_is_kept_by_the_flow() {
let (flow, _internal, inner) = rig();

inner
.post_message(
gst::message::HaveContext::builder(context("from inside"))
.src(&inner)
.build(),
)
.unwrap();

assert_eq!(
value(flow.context(CONTEXT_TYPE)),
Some("from inside".into())
);
}

#[test]
fn a_device_context_stays_inside() {
let (flow, _internal, inner) = rig();
const CUDA: &str = "gst.cuda.context";

inner
.post_message(
gst::message::HaveContext::builder(gst::Context::new(CUDA, true))
.src(&inner)
.build(),
)
.unwrap();

assert!(
flow.context(CUDA).is_none(),
"the flow keeps its own device context"
);
}

#[test]
fn a_torn_down_flow_leaves_the_messages_inside() {
let (flow, internal, inner) = rig();
drop(flow);

inner
.post_message(
gst::message::NeedContext::builder(CONTEXT_TYPE)
.src(&inner)
.build(),
)
.unwrap();

assert_eq!(value(inner.context(CONTEXT_TYPE)), None);
let msg = internal
.bus()
.unwrap()
.pop_filtered(&[gst::MessageType::NeedContext]);
assert!(msg.is_some(), "the request still reaches the internal bus");
}
}
1 change: 1 addition & 0 deletions backend/src/gst/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
pub(crate) mod aggregator_start;
mod block_expansion;
pub mod buffer_age_probe;
pub mod context_forward;
pub(crate) mod control_bindings;
pub(crate) mod crop;
pub mod discovery;
Expand Down
Loading
Loading