Skip to main content

LocalBroadcast

Struct LocalBroadcast 

Source
pub struct LocalBroadcast { /* private fields */ }
Expand description

A broadcast this process produces.

It holds a catalog, a media clock, one video slot and one audio slot. A transport that publishes it hands it the broadcast to fill: build it with new_in or TryFrom<broadcast::Producer>, as iroh-live’s publish does. A standalone one from new reads in-process through consume.

Cloning is cheap. close ends the broadcast for every clone. The setters spawn an encoding task, so call them from within a Tokio runtime.

Dropping the last clone ends the broadcast without waiting: it aborts the encoding tasks and closes the catalog and the broadcast.

Implementations§

Source§

impl LocalBroadcast

Source

pub async fn set_spec( &self, spec: &MediaSpec, encoding: impl Into<MediaEncoding>, ) -> Result<(), Error>

Opens the sources spec names with default options and publishes them.

The same as set_spec_with with the default [VideoOpenOptions]. See there for what opens and what it replaces.

§Errors

As set_spec_with.

§Panics

Panics when called outside a Tokio runtime.

§Examples
use moq_ext_publisher::{LocalBroadcast, MediaEncoding};
use moq_ext_sources::spec::MediaSpec;

let broadcast = LocalBroadcast::new();
broadcast.set_spec(&MediaSpec::test(), MediaEncoding::default()).await?;
Source

pub async fn set_spec_with( &self, spec: &MediaSpec, options: &VideoOpenOptions, encoding: impl Into<MediaEncoding>, ) -> Result<(), Error>

Opens the sources spec names with options and publishes them.

The video opens with options and its raw pictures encode into encoding.video. A file: video goes out as it is stored, its H.264 in one rendition, unless [MediaSpec::reencode] decodes it into the renditions. Without [MediaSpec::audio], a file: video brings the file’s own audio, passed through or decoded as the video is, and any other video leaves the audio as it is. An audio source of the video’s file plays against the file’s clock, as does any file VideoOpenOptions::with_file holds. The file’s own audio is left out with a warning if it does not open, for example in another codec than AAC. Passed through, the video is left out the same way if the audio goes out, as set_encoded_file does. A file without video publishes its audio alone.

Every source opens before any is set, so a source that fails to open leaves the broadcast as it was. A microphone opens without echo cancellation, as [AudioSourceSpec::open] does: open it with a canceller and pass it to set_audio instead. A passthrough file leaves video_source empty.

Cancellation safe: dropping the future drops the sources it opened.

§Errors

Fails if a source does not open, as VideoSourceSpec::open and [AudioSourceSpec::open] do, with Error::InvalidConfig for a file that has neither video nor audio while the spec names no other audio, for a file whose video does not open and whose own audio does not go out instead, for an encoding that set_video or set_audio refuses, and with Error::Closed after close.

§Panics

Panics when called outside a Tokio runtime.

§Examples
use moq_ext_publisher::{LocalBroadcast, VideoEncoding, VideoRendition};
use moq_ext_sources::spec::{AudioSourceSpec, MediaSpec, TestTone, VideoOpenOptions};

let broadcast = LocalBroadcast::new();
let spec = MediaSpec::new("test:bounce".parse()?)
    .with_audio(AudioSourceSpec::Test(TestTone::Beeps));
let encoding = VideoEncoding::single(VideoRendition::p360());
let options = VideoOpenOptions::default().with_size(moq_video::Size::new(640, 360));
broadcast.set_spec_with(&spec, &options, encoding).await?;
Source§

impl LocalBroadcast

Source

pub fn new() -> Self

Creates an empty broadcast of its own, published nowhere.

For a local preview, a test, or a transport that takes any broadcast::Consumer.

Source

pub fn new_in(producer: Producer) -> Result<Self, Error>

Creates an empty broadcast that fills producer.

Pass the broadcast a transport created for publishing, such as an iroh_live_node::Publication’s: its readers read what this writes, with nothing copied in between. Closing this closes producer, which withdraws the publication.

§Errors

Returns Error::Broadcast if producer already holds a catalog track, or is closed.

Source

pub fn set_video( &self, source: VideoSource, encoding: VideoEncoding, ) -> Result<(), Error>

Encodes source into every rendition of encoding, replacing the current video.

Returns once the encoding task has started. Its progress shows in status.

A rendition with the name of one the replaced video published goes on in the same track, so its viewers see the new source from its first keyframe without subscribing again. If the new encoder’s stream needs another decoder, for example a new H.264 level after a switch to a larger source, the rendition moves to a newly named track such as video/1, and a player in automatic mode follows the catalog to it. Renditions the new ladder lacks end.

§Errors

Fails on invalid configuration: an empty ladder, duplicate rendition names, a rate above the source’s, or a codec no compiled-in encoder supports. Returns Error::Closed after close.

§Panics

Panics when called outside a Tokio runtime.

Source

pub fn set_encoded_video(&self, source: EncodedVideo) -> Result<(), Error>

Publishes pre-encoded H.264 as the one video rendition, video, replacing the current video.

The source is an Annex-B byte stream, such as rpicam_h264 returns, or the access units of a file, such as MediaFile::encoded_video returns, which also lists the trade-offs of publishing without an encoder. The stream’s own parameter sets describe the rendition, so an Annex-B stream should repeat them before every keyframe. A source that ends before its first access unit shows as failed in status. Whatever produces the frames stops when the broadcast drops the source.

§Errors

Returns Error::Closed after close.

§Panics

Panics when called outside a Tokio runtime.

Source

pub fn set_encoded_audio(&self, source: EncodedAudio) -> Result<(), Error>

Publishes pre-encoded audio as it is, replacing the current audio.

For the AAC of a file, as MediaFile::encoded_audio returns it. Each frame goes out in a group of its own. A source that ends before its first frame shows as failed in status.

§Errors

Returns Error::Closed after close.

§Panics

Panics when called outside a Tokio runtime.

Source

pub fn set_encoded_file(&self, file: &MediaFile) -> Result<(), Error>

Publishes the H.264 video and the AAC audio of file as they are.

Either track may be missing. A track in another codec is left out with a warning, and the slot of a missing or left-out track keeps what it had. MediaFile::encoded_video lists the trade-offs against decoding the file.

§Errors

Returns Error::InvalidConfig if the file has neither H.264 video nor AAC audio, and Error::Closed after close.

§Panics

Panics when called outside a Tokio runtime.

Source

pub fn set_audio( &self, source: AudioSource, encoding: impl Into<AudioEncoding>, ) -> Result<(), Error>

Encodes source as the broadcast’s audio, replacing the current audio.

encoding is an AudioEncoding, such as a preset from audio_encoding, or a moq-audio encode::Config with the default group span.

A microphone opens when the publication starts. If it fails then or later, the audio slot shows the failure in status and stays failed until the audio is set again.

§Errors

Fails for an invalid encoding, or with Error::Closed after close.

§Panics

Panics when called outside a Tokio runtime.

Source

pub fn value_track<T: Serialize>( &self, name: &str, ) -> Result<ValueWriter<T>, Error>

Creates a latest-value JSON track name in the broadcast, next to the media.

For a setting or a status that rides along with the video and audio: each update replaces the value, and a reader that subscribes late gets the current one at once. The track counts milliseconds, and the ValueWriter stamps each update with the time it is made; update_at takes a time of the caller’s choice instead. The last clone of the writer to drop finishes the track. A reader that asks for the track before it exists does not find it, so create it before the broadcast is announced, for example in the fill of iroh_live_node::Node::publish_with.

§Errors

Fails with Error::Closed after close, and with Error::Broadcast if the broadcast already has a track name.

§Examples
use moq_ext_publisher::LocalBroadcast;

let broadcast = LocalBroadcast::new();
let control = broadcast.value_track::<u32>("control")?;
control.update(&30)?;
Source

pub fn video_source(&self) -> Option<VideoSource>

Returns the raw video source this broadcast encodes, if any.

For a preview, read its frames. None without video, and for a stream from set_encoded_video. The source stays here after it fails, until the video is set again or cleared.

Source

pub fn audio_source(&self) -> Option<AudioSource>

Returns the audio source this broadcast encodes, if any.

The source stays here after it fails, until the audio is set again or cleared.

Source

pub fn clear_video(&self)

Stops publishing video.

Source

pub fn clear_audio(&self)

Stops publishing audio.

Source

pub fn status(&self) -> Receiver<PublishStatus>

Returns a receiver of the state of both slots and of every rendition.

A borrow of the receiver blocks the broadcast’s writes, so keep it short and do not hold it across a call into the broadcast.

Source

pub fn video_source_timestamp(&self, published: Timestamp) -> Option<Timestamp>

Returns the source timestamp of the video frame this broadcast published at published.

The broadcast moves every source timestamp onto its own clock. A subscriber that sends a decoded frame’s timestamp back lets the publisher find its own frame with this, without marking the pixels.

It needs VideoEncoding::record_timestamps on the encoding the frame was published with. Returns None without it, for a timestamp this broadcast did not publish, for one older than the last 512 frames, and for a pre-encoded source, whose timestamps are published as they are. The record keeps only timestamps, 32 KiB at most, and no pixels or encoded data.

§Examples
// `echoed` is the timestamp of a frame a subscriber decoded, published
// with `VideoEncoding::record_timestamps` on.
if let Some(source) = broadcast.video_source_timestamp(echoed) {
    println!("the subscriber saw the frame the source stamped {source:?}");
}
Source

pub fn video_captured_at(&self, published: Timestamp) -> Option<Instant>

Returns when the video frame this broadcast published at published entered its source.

That is when the application pushed the frame into a [VideoSource::push] sender, or when a capture or generator thread handed it over, before it waited for an encoder. A subscriber that sends a decoded frame’s timestamp back lets the publisher measure the round trip from capture with this, without a clock of its own for the source’s timestamps.

It needs VideoEncoding::record_timestamps too, and returns None in the same cases as video_source_timestamp. The instant is recorded per frame, not derived from the source timestamp, because a source’s timestamps come from its own clock: a camera’s from the device, a pushed frame’s from the application.

§Examples
// `echoed` is the timestamp of a frame a subscriber decoded and reported
// back, published with `VideoEncoding::record_timestamps` on.
if let Some(captured) = broadcast.video_captured_at(echoed) {
    println!("{:?} from capture to the report", captured.elapsed());
}
Source

pub fn video_encoded_at(&self, published: Timestamp) -> Option<Instant>

Returns when the video frame this broadcast published at published left its encoder.

That is when the first rendition to encode the frame handed its encoded data to the track. Less video_captured_at, it is the time the frame spent in the publisher: the wait for the encoder, any scaling, and the encoding itself.

It needs VideoEncoding::record_timestamps too, and returns None in the same cases as video_source_timestamp, and for a frame still in the encoder.

§Examples
let captured = broadcast.video_captured_at(echoed);
let encoded = broadcast.video_encoded_at(echoed);
if let (Some(captured), Some(encoded)) = (captured, encoded) {
    println!("{:?} from capture to the track", encoded - captured);
}
Source

pub fn stats(&self) -> PublishStats

Returns what the broadcast is sending, per rendition.

Source

pub fn consume(&self) -> Consumer

Returns a reader of the broadcast, for playing it in-process.

The same as the Consume impl, without importing the trait: RemoteBroadcast::from_local(&broadcast) plays it.

Source

pub fn close(&self)

Closes the broadcast for every clone.

Stops the encoders and lets each finish its track. Then it ends the catalog and the broadcast, which withdraws the broadcast everywhere it was published. Returns at once, and closed waits for the end. Calling it again does nothing.

Source

pub async fn closed(&self)

Waits until the broadcast is closed and every track has finished.

Cancellation safe.

Trait Implementations§

Source§

impl Clone for LocalBroadcast

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Consume<Consumer> for LocalBroadcast

Source§

fn consume(&self) -> Consumer

Derive a read view (a consumer) from this handle.
Source§

impl Debug for LocalBroadcast

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for LocalBroadcast

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl TryFrom<Producer> for LocalBroadcast

Source§

fn try_from(producer: Producer) -> Result<Self, Error>

Fills producer, as LocalBroadcast::new_in does.

Source§

type Error = Error

The type returned in the event of a conversion error.

Auto Trait Implementations§

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> Downcast<T> for T

Source§

fn downcast(&self) -> &T

Source§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<S> FromSample<S> for S

Source§

fn from_sample_(s: S) -> S

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<F, T> IntoSample<T> for F
where T: FromSample<F>,

Source§

fn into_sample(self) -> T

Source§

impl<T> NoneValue for T
where T: Default,

Source§

type NoneType = T

Source§

fn null_value() -> T

The none-equivalent value.
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<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

Source§

fn to_sample_(self) -> U

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> Upcast<T> for T

Source§

fn upcast(&self) -> Option<&T>

Source§

impl<T> WasmNotSend for T
where T: Send,

Source§

impl<T> WasmNotSendSync for T

Source§

impl<T> WasmNotSync for T
where T: Sync,

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