media_pp/core/element.rs
1use std::{sync::Arc, time::Duration};
2
3use crate::pp_log::PpLog;
4
5use crate::{
6 buffer::MediaBuffer,
7 bus::Bus,
8 clock::Clock,
9 control::{ControlMsg, ControlReceiver},
10 error::Result,
11 graph::{ElementId, PipelineGraph},
12 pad::SrcPad,
13 playback_clock::PlaybackClock,
14};
15
16/// Which kind of element posted a [`crate::bus::BusEvent`] — cheap to
17/// compare/match, unlike the accompanying `name: Arc<str>` (an
18/// instance-level identifier chosen by whoever constructed it, needed
19/// alongside this to tell apart e.g. two `Queue`s in the same pipeline;
20/// see [`Element::element_type`]).
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum ElementType {
23 FileDemuxer,
24 AppSource,
25 RtspSource,
26 TestVideoSource,
27 TestAudioSource,
28 DxgiCaptureSource,
29 WasapiCaptureSource,
30 AudioMixer,
31 VideoCompositor,
32 D3d11VideoCompositor,
33 WebRtcPeer,
34 SwDecoder,
35 D3d12vaDecoder,
36 D3d12Upload,
37 D3d11Decoder,
38 D3d11Upload,
39 D3d11Download,
40 SwEncoder,
41 SwAudioEncoder,
42 AudioResampler,
43 AudioVolume,
44 Pacer,
45 VideoSynchronizer,
46 Scaler,
47 Tee,
48 Queue,
49 FrameCounter,
50 PacketCounter,
51 D3d12Renderer,
52 D3d11Renderer,
53 WasapiRenderer,
54 RtspSink,
55 AppSink,
56 OrtDetector,
57 HlsMuxer,
58 Mp4Muxer,
59 SegmentedMp4Muxer,
60 /// Anything outside this crate's own elements — a test double, or a
61 /// custom `Sink`/`SourceElement` implemented downstream of this
62 /// crate. Keeps this enum from needing to grow every time someone
63 /// adds their own element.
64 Other,
65}
66
67/// A node in the pipeline graph with a name. Plain identity only — says
68/// nothing about whether the node has an input, an output, both, or
69/// neither.
70pub trait Element: Send {
71 /// Returns a cheap clone (refcount bump, not a deep copy) of this
72 /// element's name — [`crate::bus::BusEvent`] stores names as
73 /// `Arc<str>` for exactly this reason: a hot path like
74 /// [`crate::queue::Queue`] posting `BusEvent::Dropped` once per
75 /// overflowed buffer shouldn't pay for a fresh heap allocation every
76 /// time it wants to report which element it is.
77 fn name(&self) -> Arc<str>;
78
79 /// See [`ElementType`].
80 fn element_type(&self) -> ElementType;
81
82 /// A pre-reserved graph identity for elements that expose dynamic
83 /// attachment handles. Most elements receive an ID from
84 /// `ChainBuilder` and keep the default `None` implementation.
85 fn graph_id(&self) -> Option<ElementId> {
86 None
87 }
88
89 /// This element's identity for [`crate::bus::Bus::post`] — same
90 /// `id`/`name` as [`Element::name`], just already wrapped as the
91 /// [`crate::pp_log::PpLog`] its `pp_info!`/`pp_warn!`/`pp_error!` macros need. A
92 /// stored private field, not built fresh per call, for the same reason
93 /// `name()` returns a cheap `Arc<str>` clone instead of a fresh `String`
94 /// — see its own docs.
95 fn pp_log(&self) -> &PpLog;
96
97 /// Mutable access to the same field [`Element::pp_log`] reads — used by
98 /// [`crate::pipeline::ChainBuilder`] to stamp the owning
99 /// [`crate::pipeline::Pipeline`]'s id onto every element that
100 /// passes through it, via [`element_pp_log`]. Not meant to be called
101 /// from anywhere else.
102 fn pp_log_mut(&mut self) -> &mut PpLog;
103}
104
105/// Builds the [`PpLog`] every element constructs for its own [`Element::pp_log`]
106/// field, and that [`crate::pipeline::ChainBuilder`]/[`crate::pipeline::Pipeline`]
107/// rebuild once they know which pipeline an element belongs to. Keeps the
108/// element type, instance name, and pipeline id as separate fields, so a log
109/// reader does not need to parse a combined display string. The pipeline id is
110/// `None` for an element that isn't wired into a `Pipeline` at all (e.g. most
111/// of this crate's own tests). Public so a custom `Element`
112/// implemented outside this crate (see [`ElementType::Other`]) can build
113/// its own `pp_log` field the same way.
114pub fn element_pp_log(element_type: ElementType, name: &str, pipeline_id: Option<&str>) -> PpLog {
115 PpLog::new(&format!("{element_type:?}"), name, pipeline_id)
116}
117
118/// Builds the [`PpLog`] used for records a [`crate::pipeline::Pipeline`]
119/// emits about itself rather than about any one element — `run` and the
120/// `topology` diagram. A pipeline is not a graph node and so has no
121/// [`ElementType`]; its instance name is its own id. Kept here next to
122/// [`element_pp_log`] so the literal element name appears exactly once.
123pub(crate) fn pipeline_pp_log(pipeline_id: &str) -> PpLog {
124 PpLog::new("Pipeline", pipeline_id, Some(pipeline_id))
125}
126
127/// Everything a [`crate::pipeline::ChainBuilder`]/[`crate::elements::Tee`]
128/// needs to wire itself into a [`crate::pipeline::Pipeline`] — bundled into
129/// one `Arc` instead of threading `bus`/`pipeline_id`/`graph`/the wall and
130/// playback clocks through separately. Built once per source by
131/// [`crate::pipeline::PipelineBuilder::add_source`] (what
132/// [`crate::pipeline::Pipeline::new`] itself calls, for its own
133/// single-source case) and handed to that source's own `wire` closure; a
134/// [`crate::elements::Tee`] keeps its own clone while it is alive, and its
135/// [`crate::elements::TeeHandle`] accesses that clone weakly so retaining
136/// the handle cannot keep the pipeline's `Bus` open after the `Tee` itself
137/// is gone.
138pub struct Context {
139 pub bus: Bus,
140 pub pipeline_id: Arc<str>,
141 pub graph: PipelineGraph,
142 pub clock: Arc<Clock>,
143 /// Shared media-position clock used to hand video scheduling from the
144 /// wall clock to an audio output master without changing pipelines.
145 pub playback_clock: Arc<PlaybackClock>,
146 /// Graph identity of the source whose wiring closure owns this context.
147 pub source_id: ElementId,
148}
149
150#[cfg(test)]
151impl Context {
152 pub(crate) fn for_test(
153 bus: Bus,
154 pipeline_id: impl Into<Arc<str>>,
155 graph: PipelineGraph,
156 source_id: ElementId,
157 ) -> Self {
158 let clock = Arc::new(Clock::new());
159 Self {
160 bus,
161 pipeline_id: pipeline_id.into(),
162 graph,
163 playback_clock: Arc::new(PlaybackClock::new(clock.clone())),
164 clock,
165 source_id,
166 }
167 }
168}
169
170/// Anything that can receive a buffer pushed from upstream — the input
171/// side of an element, or a plain terminal sink. Every `Sink` is named
172/// (via `Element`) so bus events (e.g. EOS) can identify which one they
173/// came from.
174///
175/// This is the only "connection" primitive in the pipeline. By default,
176/// consuming a buffer is a plain function call on the caller's thread —
177/// zero overhead. Thread boundaries are introduced explicitly by wrapping
178/// a `Sink` in a [`crate::queue::Queue`], not by elements spawning their
179/// own threads.
180pub trait Sink: Element {
181 fn consume(&mut self, buf: MediaBuffer) -> Result<()>;
182
183 /// Reacts to a [`ControlMsg`] (pause/resume/stop) and, for anything
184 /// with a downstream of its own, forwards it on — same shape as
185 /// `consume`, just a separate channel from `MediaBuffer` so it can
186 /// reach every element (not just ones that already know how to
187 /// interpret a data buffer) and, at a [`crate::queue::Queue`], jump
188 /// ahead of whatever data is backed up instead of waiting behind it.
189 /// No default: every `Sink` has to consciously decide what this means
190 /// for it, rather than silently dropping it.
191 fn control(&mut self, msg: ControlMsg) -> Result<()>;
192}
193
194/// An element with one or more output ports. It sends data downstream by
195/// pushing into its own `src_pads()` (e.g. `self.src_pads()[0].push(buf)`)
196/// — it's never handed a `downstream` argument from the outside. See
197/// [`SrcPad`].
198///
199/// `Source` and `Sink` are the two halves of the duality: `Sink` is "has
200/// an input", `Source` is "has an output". An element that both receives
201/// and produces (a decoder, say) implements both side by side — `Sink` to
202/// receive, `Source` to push whatever it produces into its own pad(s)
203/// from inside `consume`. There's no separate "processing element" trait
204/// or wrapper needed for that.
205pub trait Source: Element {
206 fn src_pads(&mut self) -> &mut [SrcPad];
207}
208
209/// A pure source: has output but no input. Its `run` method drives the
210/// production loop and pushes buffers into its own src pad(s) until EOS or
211/// an error. [`crate::pipeline::Pipeline::run`] normally invokes that loop
212/// on the pipeline's background source thread; a caller may also invoke a
213/// concrete implementation directly. Sources typically wrap blocking I/O
214/// reads (demuxer, file/network source).
215pub trait SourceElement: Source {
216 /// Drives this source until `Eos` (normal completion) or `Stop` (see
217 /// [`ControlMsg::Stop`]) — call [`crate::control::drain_control`]
218 /// once per loop iteration to make `control` responsive between
219 /// blocking reads.
220 ///
221 /// `bus` is this source's own way to report a failure pushing into
222 /// one of its pads *without* treating it as fatal — post a
223 /// [`crate::bus::BusEvent::Error`] and keep going (drop that one
224 /// buffer), the same way a [`crate::queue::Queue`] handles a failing
225 /// downstream `Sink` — rather than returning `Err` and ending this
226 /// source's thread over one bad buffer. A returned `Err` is still
227 /// how genuinely fatal failures (this source can't continue at all)
228 /// reach [`crate::pipeline::Pipeline::run`], which posts it to `bus`
229 /// itself.
230 fn run(&mut self, control: &ControlReceiver, bus: &Bus) -> Result<()>;
231
232 /// Repositions this source to `target`, an absolute position from the
233 /// start of the media (e.g. `av_seek_frame` for
234 /// [`crate::elements::FileDemuxer`]). Called by
235 /// [`crate::control::drain_control`] as part of handling
236 /// [`ControlMsg::Seek`], *before* that message is forwarded to the
237 /// source's own pads — so whatever's read next comes from the new
238 /// position by the time downstream elements are told to flush for it.
239 ///
240 /// Returns where this actually landed, which is allowed to differ
241 /// from `target` — a container seek can only ever reposition to a
242 /// keyframe at or before it (landing mid-GOP would leave downstream
243 /// decoders/muxers with no reference frame to start from), so
244 /// `target` is a request, not a guarantee. `drain_control` reports
245 /// the gap between the two via [`crate::bus::BusEvent::Seeked`];
246 /// callers that need to know where playback actually resumed should
247 /// watch that instead of assuming `target` took effect verbatim.
248 fn seek(&mut self, target: Duration) -> Result<Duration>;
249}
250
251/// An element with both an input and an output — decoder, encoder,
252/// filter, thumbnail extractor, ... Just a name for "has a `Sink` to
253/// receive and a `Source` to push what it produces into"; nothing new to
254/// implement beyond those two.
255pub trait Filter: Source + Sink {}
256
257impl<T: Source + Sink> Filter for T {}