Skip to main content

VideoSource

Struct VideoSource 

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

A raw video source running on its own thread.

Capture runs while any clone exists, including the clone a broadcast holds. Any number of broadcasts and previews can read it at once. Encoding runs only while something wants the frames. Cheap to clone.

Implementations§

Source§

impl VideoSource

Source

pub fn scaled(&self, size: Size) -> Result<Self, Error>

Returns a source of this source’s frames scaled to size, as I420 in CPU memory.

The output is always CPU I420, so this is not meant for publishing: a GPU frame would be downloaded and uploaded again for a hardware encoder. Use VideoRendition::with_size in moq-ext-publisher instead, which keeps GPU frames on the GPU.

GPU frames are scaled on their device where supported. The picture is stretched to exactly size, and only the newest frame is scaled.

A frame that can never be scaled ends the source, even over a switchable input that later moves on, and failure returns why.

§Errors

Returns Error::InvalidConfig if size is zero or odd.

§Panics

Panics when called outside a Tokio runtime.

Source§

impl VideoSource

Source

pub fn switchable(format: VideoFormat) -> (VideoSwitch, Self)

Returns a source whose input the returned VideoSwitch swaps.

Publish the source once, and switch cameras, screens or test patterns behind it without touching the broadcast: its encoders keep running, and its subscribers keep their tracks. A broadcast anchors each new source’s timestamps at its clock again and starts a group there, so the new picture starts with a keyframe. format describes the frames the switch carries, as for push, and a frame of another size is scaled to the rendition’s.

The source reports the switch’s state in VideoSwitch::status and starts Off, with no frames until a source is set.

§Examples
use moq_ext_sources::VideoSource;

let (switch, source) = VideoSource::switchable(format);
// Hand `source` to a broadcast once, then switch behind it.
switch.replace(VideoSource::test_pattern(size, rate)?);
switch.open(VideoSource::capture(Default::default()));
Source§

impl VideoSource

Source

pub async fn capture(config: Config) -> Result<Self, Error>

Opens the camera, display or window that config.source names.

Returns once the device has produced a frame. An opened camera that produces none within 10 seconds fails, any other device within 30 seconds. A permission dialog the platform shows while the device opens does not count against that time.

A camera first waits, for at most 3 seconds, until every camera source dropped before this call has closed its device, so a switch back to the same camera does not fail as busy. Drop the old source before opening its replacement. A capture that does not let go in time is stuck in a read: the open proceeds without it, and that thread may hold its device until the read returns. A V4L2 read gives up after a second, but a Media Foundation read on Windows has no timeout.

With the pipewire feature on Linux, the defaults go through PipeWire first. The default camera is PipeWire’s, which shares the device with other applications, and the default V4L2 device opens if it does not. The default display is the one the user picks in the desktop portal’s screen-sharing dialog. On an X11 session the main X11 display opens if the portal is unavailable. On Wayland there is no fallback, because X11 capture there sees only XWayland’s windows.

A window or display that settles at a new size, or a device that changes its format, is reopened behind the same source, so its frames go on at the new size while format keeps the size it opened at. The source fails if the reopen does not succeed after a few attempts, and ends when the user stops sharing, the window closes or the device goes away.

Cancellation safe: dropping the future stops the thread and releases the device.

§Errors

Returns Error::Device if the device does not open or produces no frame.

Source

pub async fn camera(id: Option<String>) -> Result<Self, Error>

Opens camera id at its default mode, or the default camera for None.

The ids are the ones moq_video::capture::cameras reports. For a size or a rate, build a capture::Config and call capture.

§Errors

As capture.

Source

pub async fn screen() -> Result<Self, Error>

Opens the main screen at its own size.

Opens screen_source: on Wayland in a build with the pipewire feature, the user picks the screen in the desktop portal’s dialog, since Wayland refuses a direct display capture. The portal asks on each call; see VideoOpenOptions::with_portal_grants to keep the grant.

§Errors

As capture, and fails on Wayland without the pipewire feature.

Source

pub fn test_pattern(size: Size, rate: FrameRate) -> Result<Self, Error>

Returns a generated test pattern at size and rate.

The pattern shows a sweeping bar, a frame counter and a clock. A marker flashes in step with the beep of AudioSource::test_pattern.

§Errors

Fails if the thread that draws the pattern cannot be started.

Source

pub fn test_gradient(size: Size, rate: FrameRate) -> Result<Self, Error>

Returns a diagonal gradient at size and rate that shifts every frame.

Cheap to draw, and different in every frame, so a stalled pipeline does not look like a working one. Unlike test_pattern, it carries no clock or counter.

§Errors

Fails if the thread that draws the gradient cannot be started.

Source

pub fn test_bounce(size: Size, rate: FrameRate) -> Result<Self, Error>

Returns a bouncing square on a drifting hue at size and rate.

Draws BouncePattern at each frame’s media time.

§Errors

Fails with Error::InvalidConfig if a dimension of size is zero or odd, and if the thread that draws the pattern cannot be started.

Source

pub fn push(format: VideoFormat) -> (FrameSender<Frame>, Self)

Returns a source fed by the returned sender.

The source ends when every sender is dropped. format describes what the sender will push, and a broadcast advertises its size. A frame of another size is scaled to the rendition’s.

An application may switch devices while it pushes. Timestamps only have to rise within one device’s run: a broadcast re-anchors a timeline that goes back or jumps far ahead, and starts a new group there.

Source

pub fn spawn<F>(name: &str, format: VideoFormat, run: F) -> Result<Self, Error>
where F: FnOnce(FrameSender<Frame>) -> Result<(), Error> + Send + 'static,

Runs run on a dedicated thread that feeds the source.

Use it for thread-bound platform objects. The thread has a current-thread Tokio runtime entered, so run can drive async code with tokio::runtime::Handle::current().block_on. The source ends once run returns and every clone of its sender is dropped. If run fails, the source fails with its error. run should return once FrameSender::push reports SourceClosed.

§Errors

Fails if the thread or its runtime cannot be started.

Source

pub async fn rpicam(config: RpicamConfig) -> Result<Self, Error>

Starts the Raspberry Pi camera through rpicam-vid, for raw pictures.

The width is rounded up to one libcamera writes without row padding, so format may be a few columns wider than asked for. For the camera’s hardware H.264, use rpicam_h264.

Cancellation safe: dropping the future kills the subprocess.

§Errors

Fails if rpicam-vid is not installed or cannot open the camera.

Source

pub fn frames(&self) -> VideoFrames

Returns the source’s frames, for a local preview or a QR scanner.

Every call returns a handle onto the same stream. The handle counts as demand, which FrameSender::demand reports, until it and its clones are dropped, so a source that idles until wanted produces frames for it. Reading it does not encode.

Source

pub fn observe(&self) -> VideoFrames

Returns the source’s frames without counting as demand.

For a reader that wants the frames only some of the time, and holds a want guard while it does. A publisher’s encoder reads the source this way, and wants it only while somebody watches. A source that idles until wanted produces nothing for this handle alone.

Source

pub fn format(&self) -> VideoFormat

Returns the format the source opened at.

It may differ from what the config asked for. Frames can come at another size later, such as from a captured window that was resized, so a consumer that cares takes the size from each frame.

Source

pub fn failure(&self) -> Option<Arc<Error>>

Returns why the source stopped, if it failed.

Source

pub fn label(&self) -> &str

Returns a short name of the source, for logs.

Source

pub fn released(&self) -> WaitForCancellationFutureOwned ⓘ

Returns a future that resolves once the source has closed its device.

The device closes on the capture thread after the last handle is dropped. Bound the wait: a thread stuck in a read lets go only once the read returns, which takes up to a second on V4L2 and has no limit for Media Foundation on Windows. Resolves at once for a source without a device. capture already waits for dropped cameras, so this is for a device something other than this crate opens next.

Trait Implementations§

Source§

impl Clone for VideoSource

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 Debug for VideoSource

Source§

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

Formats the value using the given formatter. Read more

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> 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