Skip to main content

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