Skip to main content

Producer

Struct Producer 

Source
pub struct Producer<C: Container, R = ()> { /* private fields */ }
Expand description

A producer for media tracks that manages group boundaries.

Generic over C: Container to support different container encodings (Legacy, CMAF, LOC). Use catalog::hang::Wire to dispatch on the catalog at runtime.

§Group Management

keyframe = true means “start a new group”: it closes the previous group (if any) and opens a new one, so every group begins with a keyframe. A non-keyframe extends the current group, and writing one when no group is open is a protocol violation.

A stream where every frame is independently decodable (e.g. audio) still drives grouping through this bit: mark only the first frame of each group a keyframe and the rest non-keyframes, so the caller’s cut boundaries define the groups instead of every frame opening its own (one QUIC stream per frame). needs_keyframe reports whether the next frame has to be one.

cut closes the current group early, ideally saying where its content ends; the next write must be a keyframe. Reach for it when the following keyframe won’t supply that boundary in time, or to bound each group of an accumulating audio track. discontinuity publishes a marker group with no media, for when the timeline is about to jump rather than merely continue. Timestamps never fall below the live edge earlier groups reached.

§Buffering

When the buffer duration is zero (default), each frame is written immediately as its own container frame. When non-zero, frames are buffered and flushed together when:

  • A keyframe arrives (flushes the previous group’s buffer, starts new group),
  • The buffered duration exceeds the configured duration,
  • finish() is called.

This is useful for CMAF where multiple samples should be packed into one moof+mdat.

Implementations§

Source§

impl<C: Container> Producer<C>

Source

pub fn new(track: Producer, container: C) -> Self

Create a Producer wrapping the given moq-lite producer, muxing into container.

A plain media track by default: no buffering, no timeline. Add buffering with with_buffer; the join interval is wired by the catalog (see catalog::Producer::video and its sibling APIs).

Source§

impl<C: Container, R: Clone + Send + 'static> Producer<C, R>
where Error: From<C::Error>,

Source

pub fn set(&mut self, config: R) -> Result<()>

Publish or replace this track’s catalog config.

Unset jitter and delay keep their published floor; explicitly lowering either is refused.

Source

pub fn set_bitrate(&mut self, bitrate: u64) -> Result<()>

Advertise bitrate as the rendition’s maximum, such as an encoder’s retuned target, which later measurement no longer replaces. Every other published field stays as it is.

Source

pub fn modify(&mut self) -> Result<Guard<'_, R>>

Modify the published catalog config.

Estimate fields the config left to detection at set stay owned by detection: an edit to them here is published but replaced by the next measurement, except that jitter and delay never drop below the published value. Call set with the field filled in to pin it.

Source

pub fn timestamp(&self, hint: Option<Timestamp>) -> Result<Timestamp>

Resolve a timestamp on the broadcast’s shared clock: hint, or the clock’s reading now.

A reading comes from the clock rather than media, so one landing on the newest group’s start, as a burst of untimed frames can, is moved one unit of the track’s timescale past it: group starts strictly increase.

Source

pub fn name(&self) -> &str

The catalog key owned by this producer.

Source

pub fn demand(&self) -> Demand

A watch-only handle to this track’s subscriber demand.

Source§

impl<C: Container, R: Clone + Send + 'static> Producer<C, R>
where Error: From<C::Error>,

Source

pub fn estimate(&self) -> Estimate

The jitter, bitrate, delay, and framerate measured from the frames written so far.

A catalog-owned producer publishes this automatically.

Source

pub fn reorder(&mut self, delay: Duration)

Record a frame’s reorder delay (PTS - DTS), raising the measured jitter to the decode buffer a B-frame stream needs.

A decode-order container measures it from each frame’s decode time; for the others, a caller that demuxed one supplies it.

Source

pub fn history(&mut self, until: Timestamp)

Mark frames at or before until as retained history being caught up, rather than live frames written late.

History never measures delay against the other tracks: a publisher replaying a backlog behind the live edge would otherwise advertise the backlog’s age as playout delay for the rest of the track.

Source

pub fn needs_keyframe(&self) -> bool

Whether the next write has to be a keyframe, i.e. no group is currently open (at the start, or after a cut).

A stream where every frame is independently decodable (audio) uses this to mark only the first frame of each group a keyframe: write(Frame { keyframe: producer.needs_keyframe(), .. }), so grouping follows the caller’s cut boundaries rather than opening a group per frame.

Source

pub fn with_buffer(self, duration: Duration) -> Self

Buffer up to duration of frames into each container frame.

When non-zero, frames are buffered and flushed together once the buffered duration exceeds it, or a keyframe arrives, packing multiple samples into one container frame (e.g. a CMAF moof+mdat). Zero (the default) flushes each frame immediately.

This is the publisher-side counterpart to the consumer’s max delay, and the one knob here that genuinely adds delay. A batch’s oldest frame reaches the transport as late as the batch’s span, so the catalog advertises that span as jitter. A group a keyframe closes ends only once the next group’s first batch flushes or the producer ends, since a CMAF fragment may start that group below the keyframe.

Source

pub fn with_bandwidth(self, allocator: Allocator) -> Self

Claim this track’s peak-hold catalog bitrate on allocator.

A passthrough track has no configured ceiling, so it reserves the measured maximum instead: nothing until the first 1 s window closes, then only upward. A co-resident encoder targets what is left. The claim is named bandwidth so it is not confused with the catalog-gate Reserved.

Source

pub fn report_skipped(&self, frames: u64)

Report frames frames the source produced but never handed to this track, such as ones an encoder fell behind on, in its catalog’s stats.

Source

pub fn report_bitrate(&self, bitrate: Rate)

Report the encoder’s latest target bitrate in its catalog’s stats. The catalog’s bitrate stays the maximum.

Source

pub fn track(&self) -> &Producer

The underlying moq-lite track producer. Read-only; mutating it directly would sidestep group/keyframe invariants.

Source

pub fn live_edge(&self) -> Option<Timestamp>

The exclusive presentation end earlier groups have reached, if any.

A source with no timestamp of its own (a section, a PES without PTS) lands on it. It is not a floor: a keyframe may start below it (see write).

Source

pub fn write(&mut self, frame: Frame) -> Result<()>

Write a frame to the track.

A keyframe closes any open group and starts a new one. A non-keyframe extends the current group; if no group is open it returns MissingKeyframe, so a caller joining mid-stream can skip frames until the first keyframe. A source where every frame is independently decodable (audio) marks only the first frame of each group a keyframe (see needs_keyframe) so the group spans more than one frame.

A group starts at its keyframe’s timestamp, in the track’s timescale, and every frame of a group presents after every frame of the groups before it. Frames within a group may still reorder (B-frames, open-GOP leading pictures). A keyframe that doesn’t start after the newest frame written continues the open group, as at a splice whose keyframe dips below the old content’s last frames. A later frame presenting at or before the previous groups’ newest, such as a leading picture after a splice, is dropped and counted as skipped, and so is a keyframe at or before the newest frame with no group open, such as after a cut, with the frames after it until a keyframe opens a group.

Group starts strictly increase, and no group starts inside the span of one that ended whole at a cut’s end. So with no group open, a keyframe past the newest frame but at the latest group’s start, such as media resuming right at a discontinuity’s marker, or below that end, such as one a cadence or a rounded duration estimated past it, is stamped at the first start past both. A frame at that keyframe’s own timestamp, such as the picture its parameter sets precede, is stamped with it, and the group’s End is still estimated from the source’s timestamps, so a move never adds up across groups.

Group starts never go backwards: a keyframe below the start of the latest group, or any frame below the start of the group before its own, returns TimestampRewind with the refused timestamp and that start, without writing, the way an oversized frame is refused. That is a restart, which is a new broadcast.

In a decode-order container, a frame with a decode time is judged by it instead, and groups by decode time: those never decrease within a group, so one decoding below the newest frame closes the open group and is dropped, with the frames after it until a keyframe past the newest. The transport carries each frame’s decode time. Elsewhere decode times are ignored and the transport carries the latest presentation time so far in the group, which never decreases either, while the payload keeps the frame’s own.

Source

pub fn cut(&mut self, end: Option<Timestamp>) -> Result<()>

Cut the current group, flushing buffered frames and closing it.

end bounds the final buffered frame when the publisher knows where the group’s content stops. A video track that writes duration markers appends an empty frame at that bound, or at the last timestamp plus its estimated duration. Reordered groups omit this marker because their presentation end does not bound the last frame in decode order. An unreordered media group, or one given an explicit bound, ends whole there, so the next group starts at or after it (see write). The next write must be a keyframe. An explicit bound below a frame the group holds, in the track’s timescale, returns InvalidEnd without flushing or closing the group. A bound at or past the source timestamp of a keyframe write moved past an earlier group’s end is the source’s: the group ends at the moved keyframe instead.

Source

pub fn discontinuity(&mut self) -> Result<()>

Publish a marker group standing for a break in the timeline: content stopped, and whatever comes next does not continue it.

Call this whenever the timeline is about to jump – pausing an encoder, switching source, resuming on a re-anchored clock. Without it a break is invisible: the next group looks exactly like the one that would have followed, and a consumer bounding a sample by the next group’s first frame hands it the entire gap as its duration. That produced a 2405 second video sample out of a publisher that had been paused 40 minutes. Group starts alone can’t rule a pause out, so this marker is the only thing that can say one happened.

It also fixes what a subscriber joining mid-break sees. A subscription starts at the track’s latest group, and creating this one advances that – so a late joiner lands on the marker and waits for real media, instead of being served the group from before the break as though it were live.

Audio and video write one empty frame one unit of the track’s timescale before the exclusive end of the previous epoch, so what resumes at that end starts after it, but never below the latest frame written: a frame without a duration ends where it starts, so what resumes then has to start after that frame. Nor below the end a cut gave the closing group, whose span runs to there: the marker starts at that end. That object exists on moq-transport, so the live edge moves immediately; a consumer MUST NOT submit it to a decoder. An empty payload is data on a data track, so its marker is one object with no bytes at all, not even the container’s timestamp. The next write opens the group after the marker, which it has to start after: group starts strictly increase, so a keyframe at the marker is stamped one unit past it.

Before anything is written there is no timeline to break, so it publishes nothing.

To bound the closing group’s final frame, cut(end) before calling this. Otherwise the open group closes without a duration marker: what resumes may land sooner than one estimated frame later (a capture that reopens at once), and a guessed end past it would read as a rewind to every consumer.

Source

pub fn finish(self) -> Result<Finished<C, R>>

Finish the track, flushing any buffered frames and closing any open group, and return the Finished track.

A finish that fails ends the track with the cause instead, so it can’t be retried.

Source

pub fn fail(self, err: Error) -> Result<Finished<C, R>>

finish the track with err, for a source that failed after producing media worth keeping.

Unlike abort, every group written stays readable and keeps being served; a reader reaching the end gets err instead of the end of stream. Over IETF moq-transport, a remote subscriber is told only of a generic internal error.

Source

pub fn abort(self, err: Error)

Abort the track and any open group with the given error.

The counterpart to Self::finish for a failed teardown: consumers observe err instead of the generic [moq_net::Error::Dropped] a bare drop surfaces, so the real cause (a disconnect, a decode failure) reaches them. Any buffered frames are discarded, not flushed. Consumes the producer.

Source

pub fn consume(&self) -> Subscriber

Create a consumer for this track.

Methods from Deref<Target = Producer>§

pub fn name(&self) -> &str

The track’s name, unique within its broadcast.

pub fn broadcast(&self) -> &Info

The parent broadcast this track belongs to.

pub fn info(&self) -> &Info

The properties this track was created with.

pub fn create_group(&self, frame: Frame) -> Result<Producer, Error>

Create a group whose first frame is frame, whose timestamp is where the group starts: its key on the track, in the track’s timescale.

It says nothing about the starts around it: groups may be created out of order, and an aborted or evicted start created again. A gap it leaves is skipped only once the producer says it will not fill it, with [Self::skip_groups] or [Self::append_group]. A start already skipped is refused with [Error::Skipped], and a timestamp that doesn’t match the track with [Error::TimestampMismatch], as [Self::write_frame] says.

A start another group holds is replaced: the new group takes the slot, and readers already draining the old one keep their own handle. The same broadcast, track, and group start always name the same content, and nothing checks it, as with [Self::append_group]. Two writers that may race to one start use [Self::claim_group] instead.

pub fn claim_group(&self, frame: Frame) -> Result<Option<Producer>, Error>

[Self::create_group], unless another live group already holds the start: then None, and that group is left alone. The first writer of a start wins.

pub fn create_frame(&self, frame: Info) -> Result<Producer, Error>

[Self::create_group] with its first frame streamed: the group exists once this returns, and [frame::Producer::finish] hands it back to write the rest.

pub fn has_group(&self, start: u64) -> bool

Whether a live group holds start, the key [Self::claim_group] would find taken: for a writer that skips the work of producing a group another writer already holds.

pub fn append_group(&self, frame: Frame) -> Result<Producer, Error>

Create the next group, after every group this track holds, whose first frame is frame, whose timestamp is where the group starts.

A timed track converts that timestamp into its timescale, as [Self::write_frame] does; a scale-less track takes [Timestamp::unscaled] at the group’s key. A timestamp that doesn’t match the track, or that its scale can’t hold, is [Error::TimestampMismatch].

Appending says the producer will not go back, so it skips every start below the new group that it never produced, from just past its previous append (before the first, from the lowest group it created, or from 0 when it creates the track’s first group), as [Self::skip_groups] would, replacing any drop there: consecutive appends name the span between their starts. Those starts are then final: creating one is refused. A start at or before a group this track holds is [Error::TimestampMismatch], like a rewound frame.

The same broadcast, track, and group start always name the same content, and nothing checks it: the broadcast remembers nothing of an earlier producer of the name. A recreated track, or a restarted publisher keeping its identity, keeps its starts moving forward, as its media time does, or uses a new track name or identity. Reusing a start only corrupts this broadcast for its readers. Datagram sequences name no cached content and are exempt.

pub fn append_frame(&self, frame: Info) -> Result<Producer, Error>

[Self::append_group] with its first frame streamed: the group exists once this returns, and [frame::Producer::finish] hands it back to write the rest.

pub fn drop_groups(&self, groups: Range<u64>, err: StreamError)

Record that the publisher gave up groups with err: none will arrive, so a reader waiting on one moves past it, a group still arriving in them ends with err, the declared end does not wait for them, and a relay serving this track forwards the drop.

For a producer that knows a group existed but cannot produce it, such as a replay whose copy was pruned; one that never will produce it says so with [Self::skip_groups].

pub fn skip_groups(&self, groups: Range<u64>)

Declare that this producer will never produce groups: none will arrive, so a reader waiting on one moves past it, the declared end does not wait for them, and a relay serving this track forwards the skip (a lite-07 SUBSCRIBE_SKIP). Unlike a drop, it ends no reader.

This and [Self::append_group] are the only sources of a skip: a gap between created groups says nothing, since groups may be created out of order, so only the producer knows a key will never exist. A skip is final: creating a group at a skipped key is refused with [Error::Skipped], and a later drop of it is ignored.

A skip replaces any drop of the same keys, whatever its error: a reader the drop already ended stays ended, and every later reader and relay sees the skip. A group already cached keeps what it is, since it was produced after all.

pub fn finished(&self) -> Option<Position>

The exclusive end, once [Self::finish] or [Self::finish_at] declared one.

None while the track is still open ended. Both methods reject a second end, so callers that may have already declared one check here first.

pub fn poll_closed(&self, waiter: &Waiter) -> Poll<Result<(), Error>>

Resolves once the track’s outcome is final: Ok once its declared end is reached (its error, if declared with one), or the abort error. Every producer leaving without either ends it cleanly at its live edge while nobody wants it, and with [Error::Dropped] while a reader does and no broadcast asks for it again.

pub async fn closed(&self) -> Result<(), Error>

Resolves once the track’s outcome is final: Ok once its declared end is reached (its error, if declared with one), or the abort error. Every producer leaving without either ends it cleanly at its live edge while nobody wants it, and with [Error::Dropped] while a reader does and no broadcast asks for it again.

Awaits poll_closed.

pub fn is_closed(&self) -> bool

Return true if the track has been closed.

pub fn largest(&self) -> Option<Position>

The track’s largest location: its newest group at the newest frame (0 while empty), None before any.

pub fn is_clone(&self, other: &Producer) -> bool

Return true if this is the same track.

pub fn abort_handle(&self) -> AbortHandle

A handle that aborts the track without keeping it open, for an owner that hands this producer out and must end the track on its own shutdown.

pub fn demand(&self) -> Demand

Create a [Demand]: a cloneable, watch-only handle to this track’s subscriber demand.

Lets a publisher gate work (e.g. on-demand capture) on whether anyone is subscribed, without the ability to publish frames or close the track. The handle is weak, so holding one neither keeps the track alive nor pins its cached groups.

pub fn consume(&self) -> Consumer

Get a consumer handle for this in-process track.

Unlike a wire subscription, the info is already known, so a subscription opened from this handle resolves immediately.

pub fn subscribe( &self, subscription: impl Into<Option<Subscription>>, ) -> Subscriber

Subscribing to this in-process track, resolving synchronously.

The info is fixed at creation, so there’s nothing to wait for (no SUBSCRIBE_OK round trip). Pass None for [Subscription::default].

Reads only the groups the subscription’s ranges cover. A group reached only through live joins is skipped once the widest of their max convicts it, so the default [Start::LATEST] delivers only the latest group; a history range delivers every group it covers.

pub fn subscription(&self) -> Option<Subscription>

A non-blocking snapshot of the current aggregate subscription, or None when there are no live subscribers. Unlike [Self::subscription], this doesn’t wait for a change or advance the change cursor.

Each live join’s max in the aggregate is the subscribers’ own, capped only by the local cache ceiling ([broadcast::Info::cache_duration]). The publisher enforces its own [Info::max_age], which each reader’s lateness budget also applies, so the demand asked upstream is the same before and after the info lands.

pub fn requests(&self) -> Requests

Create a [Requests] handle that serves on-demand fetches of uncached (old) groups. Most producers never need this; a relay creates one to fetch past groups from upstream.

Trait Implementations§

Source§

impl<C: Container, R> Deref for Producer<C, R>

Source§

type Target = Producer

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.

Auto Trait Implementations§

§

impl<C, R = ()> !RefUnwindSafe for Producer<C, R>

§

impl<C, R = ()> !Sync for Producer<C, R>

§

impl<C, R = ()> !UnwindSafe for Producer<C, R>

§

impl<C, R> Freeze for Producer<C, R>
where C: Freeze,

§

impl<C, R> Send for Producer<C, R>
where C: Send,

§

impl<C, R> Unpin for Producer<C, R>
where C: Unpin,

§

impl<C, R> UnsafeUnpin for Producer<C, R>
where C: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more