pub struct Stream { /* private fields */ }
Expand description

An opaque stream for playback or recording.

Note: Saves a copy of active multi-use closure callbacks, which it frees on drop.

Implementations§

source§

impl Stream

source

pub fn new( ctx: &mut Context, name: &str, ss: &Spec, map: Option<&Map> ) -> Option<Self>

Creates a new, unconnected stream with the specified name and sample type.

It is recommended to use new_with_proplist() instead and specify some initial properties.

Params
  • ctx: The context to create this stream in
  • name: A name for this stream
  • ss: The desired sample format
  • map: The desired channel map, or None for default
source

pub fn new_with_proplist( ctx: &mut Context, name: &str, ss: &Spec, map: Option<&Map>, proplist: &mut Proplist ) -> Option<Self>

Creates a new, unconnected stream with the specified name and sample type, and specify the initial stream property list.

Params
  • ctx: The context to create this stream in
  • name: A name for this stream
  • ss: The desired sample format
  • map: The desired channel map, or None for default
  • proplist: The initial property list
source

pub fn new_extended( ctx: &mut Context, name: &str, formats: &[&Info], proplist: &mut Proplist ) -> Option<Self>

Creates a new, unconnected stream with the specified name, the set of formats this client can provide, and an initial list of properties.

While connecting, the server will select the most appropriate format which the client must then provide.

Params
  • ctx: The context to create this stream in
  • name: A name for this stream
  • formats: The list of formats that can be provided
  • proplist: The initial property list
source

pub fn get_state(&self) -> State

Gets the current state of the stream.

source

pub fn get_index(&self) -> Option<u32>

Gets the sink input resp. source output index this stream is identified in the server with.

This is useful with the introspection functions such as Introspector::get_sink_input_info() or Introspector::get_source_output_info().

source

pub fn get_device_index(&self) -> Option<u32>

Gets the index of the sink or source this stream is connected to in the server.

This is useful with the introspection functions such as Introspector::get_sink_info_by_index() or Introspector::get_source_info_by_index().

Please note that streams may be moved between sinks/sources and thus it is recommended to use set_moved_callback() to be notified about this.

source

pub fn get_device_name(&self) -> Option<Cow<'static, str>>

Gets the name of the sink or source this stream is connected to in the server.

This is useful with the introspection functions such as Introspector::get_sink_info_by_name() or Introspector::get_source_info_by_name().

Please note that streams may be moved between sinks/sources and thus it is recommended to use set_moved_callback() to be notified about this.

source

pub fn is_suspended(&self) -> Result<bool, PAErr>

Checks whether or not the sink or source this stream is connected to has been suspended.

source

pub fn is_corked(&self) -> Result<bool, PAErr>

Checks whether or not this stream has been corked.

source

pub fn connect_playback( &mut self, dev: Option<&str>, attr: Option<&BufferAttr>, flags: FlagSet, volume: Option<&ChannelVolumes>, sync_stream: Option<&mut Self> ) -> Result<(), PAErr>

Connects the stream to a sink.

It is strongly recommended to pass None in both dev and volume and to set neither FlagSet::START_MUTED nor FlagSet::START_UNMUTED – unless these options are directly dependent on user input or configuration.

If you follow this rule then the sound server will have the full flexibility to choose the device, volume and mute status automatically, based on server-side policies, heuristics and stored information from previous uses. Also the server may choose to reconfigure audio devices to make other sinks/sources or capabilities available to be able to accept the stream.

Before PA 0.9.20 it was not defined whether the ‘volume’ parameter was interpreted relative to the sink’s current volume or treated as an absolute device volume. Since PA 0.9.20 it is an absolute volume when the sink is in flat volume mode, and relative otherwise, thus making sure the volume passed here has always the same semantics as the volume passed to Introspector::set_sink_input_volume(). It is possible to figure out whether flat volume mode is in effect for a given sink by calling Introspector::get_sink_info_by_name().

Since PA 5.0, it’s possible to specify a single-channel volume even if the stream has multiple channels. In that case the same volume is applied to all channels.

Params
  • dev: Name of the sink to connect to, or None to let the server decide
  • attr: Buffering attributes, or None for default
  • flags: Additional flags, or 0 for default
  • volume: Initial volume, or None for default
  • sync_stream: Synchronize this stream with the specified one, or None for a standalone stream.
source

pub fn connect_record( &mut self, dev: Option<&str>, attr: Option<&BufferAttr>, flags: FlagSet ) -> Result<(), PAErr>

Connects the stream to a source.

Params
  • dev: Name of the source to connect to, or None to let the server decide
  • attr: Buffering attributes, or None for default
  • flags: Additional flags, or 0 for default
source

pub fn connect_upload(&mut self, length: usize) -> Result<(), PAErr>

Makes this stream a sample upload stream.

(See scache).

source

pub fn finish_upload(&mut self) -> Result<(), PAErr>

Finishes the sample upload, the stream name will become the sample name.

You cancel a sample upload by issuing disconnect().

source

pub fn disconnect(&mut self) -> Result<(), PAErr>

Disconnects a stream from a source/sink.

source

pub fn begin_write<'a>( &mut self, nbytes: Option<usize> ) -> Result<Option<&'a mut [u8]>, PAErr>

Prepares writing data to the server (for playback streams).

This function may be used to optimize the number of memory copies when doing playback (“zero-copy”). It is recommended to call this function before each call to write(). It is used to obtain a chunk of PA internally allocated memory, into which you can directly write your data before calling write() to actually execute the write.

This function should be called with nbytes set to the number of bytes you want to write, or None, in which case the size will be chosen automatically (which is recommended).

The return value is a Result type, with the Ok variant wrapping an Option. Err will be returned if PA encountered an error; Ok(None) will be returned if it appeared to be successful, but the pointer returned was NULL, otherwise the buffer will be returned as Ok(Some(_)).

After placing your data in the memory area returned, call write() with a sub-slice of it, to actually execute the write. Note, the buffer may only be used once, i.e. if you were thinking of getting a large buffer, placing a large chunk of data into it, then perform multiple small writes from it, you cannot do this. Any attempt at accessing the memory returned after the following write() or cancel_write() is invalid.

If you want to cancel a previously called begin_write() without calling write() use cancel_write().

The memory should not be explicitly freed by the caller.

An invocation of write() should “quickly” follow a begin_write(). It is not recommended letting an unbounded amount of time pass after calling begin_write() and before calling write(). Calling begin_write() twice without calling write() or cancel_write() in between will return exactly the same data pointer and nbytes values.

source

pub fn cancel_write(&mut self) -> Result<(), PAErr>

Reverses the effect of begin_write() dropping any data that has already been placed in the memory area returned by begin_write().

Only valid to call after a call to begin_write() has been made, and neither cancel_write() nor write() have been called yet. Accessing the memory previously returned by begin_write() after calling this function is invalid.

source

pub fn write( &mut self, data: &[u8], free_cb: Option<FreeCb>, offset: i64, seek: SeekMode ) -> Result<(), PAErr>

Writes some data to the server (for playback streams).

If free_cb is provided, this routine is called when all data has been written out. An internal reference to the specified data is kept, the data is not copied. If None, the data is copied into an internal buffer.

The client may freely seek around in the output buffer. For most applications it is typical to pass 0 and SeekMode::Relative as values for the arguments offset and seek respectively. After a successful write call the write index will be at the position after where this chunk of data has been written to.

As an optimization for avoiding needless memory copies you may call begin_write() before this call and then place your audio data directly in the memory area returned by that call. Then, pass a pointer to that memory area to write(). After the invocation of write() the memory area may no longer be accessed. Any further explicit freeing of the memory area is not necessary. It is OK to write to the memory area returned by begin_write() only partially with this call, skipping bytes both at the end and at the beginning of the reserved memory area.

Params
  • data: The data to write. The length must be in multiples of the stream’s sample spec frame size.
  • free_cb: A cleanup routine for the data or None to request an internal copy of the data.
  • offset: Offset for seeking. Must be 0 for upload streams. Must be in multiples of the stream’s sample spec frame size.
  • seek: Seek mode. Must be SeekMode::Relative for upload streams.
source

pub fn write_copy( &mut self, data: &[u8], offset: i64, seek: SeekMode ) -> Result<(), PAErr>

Writes some data to the server (for playback streams).

This function does exactly the same as write() as though None had been specified for the free_cb param. I.e. an internal copy will be made of the provided data.

Params
  • data: The data to write. The length must be in multiples of the stream’s sample spec frame size.
  • offset: Offset for seeking. Must be 0 for upload streams. Must be in multiples of the stream’s sample spec frame size.
  • seek: Seek mode. Must be SeekMode::Relative for upload streams.
source

pub fn write_ext_free( &mut self, data: &[u8], free_cb: Option<(FreeCb, *mut c_void)>, offset: i64, seek: SeekMode ) -> Result<(), PAErr>

Available on crate feature pa_v6 only.

Writes some data to the server (for playback streams).

This function does exactly the same as write() with the only difference being that a void pointer is provided along with the free_cb callback pointer, and this void pointer will be passed to the callback instead of the data pointer.

Params
  • data: The data to write. The length must be in multiples of the stream’s sample spec frame size.
  • free_cb: A cleanup routine for the data or None to request an internal copy of the data. If provided, the accompanying data pointer will be supplied to the callback.
  • offset: Offset for seeking. Must be 0 for upload streams.
  • seek: Seek mode, must be SeekMode::Relative for upload streams.
source

pub fn peek<'a>(&mut self) -> Result<PeekResult<'a>, PAErr>

Reads the next fragment from the buffer (for recording streams).

This function returns one of the PeekResult variants - either Empty, Hole or Data:

  • If there is data at the current read index, the Data variant will be returned, which contains a slice giving a view of the data. (The length of this slice can be less or more than a complete fragment). This is pointing into an internal buffer, so obviously you must make a copy of it if you want to keep it.
  • If there is no data at the current read index, it means that either the buffer is empty or it contains a hole (that is, the write index is ahead of the read index but there’s no data where the read index points at). If the buffer is empty, the Empty result variant will be returned. If there is a hole, the Hole variant will be returned, containing the length of the hole in bytes.

Use discard() to actually remove the data from the buffer and move the read index forward. discard() should not be called if the buffer is empty, but it should be called if there is a hole.

source

pub fn discard(&mut self) -> Result<(), PAErr>

Removes the current fragment on record streams.

It is invalid to do this without first calling peek().

Note: The original C function name used the term drop; We instead use discard here to avoid conflict with the Rust Drop trait!

source

pub fn writable_size(&self) -> Option<usize>

Gets the number of bytes requested by the server that have not yet been written.

It is possible to write more than this amount, up to the stream’s buffer_attr.maxlength bytes. This is usually not desirable, though, as it would increase stream latency to be higher than requested (buffer_attr.tlength).

source

pub fn readable_size(&self) -> Option<usize>

Gets the number of bytes that may be read using peek().

Returns None on error.

source

pub fn drain( &mut self, callback: Option<Box<dyn FnMut(bool) + 'static>> ) -> Operation<dyn FnMut(bool)>

Drains a playback stream.

Use this for notification when the playback buffer is empty after playing all the audio in the buffer. Please note that only one drain operation per stream may be issued at a time.

The optional callback must accept a bool, which indicates success.

Panics if the underlying C function returns a null pointer.

source

pub fn update_timing_info( &mut self, callback: Option<Box<dyn FnMut(bool) + 'static>> ) -> Operation<dyn FnMut(bool)>

Requests a timing info structure update for a stream.

Use get_timing_info() to get access to the raw timing data, or get_time() or get_latency() to get cleaned up values.

The optional callback must accept a bool, which indicates success.

Panics if the underlying C function returns a null pointer.

source

pub fn set_state_callback( &mut self, callback: Option<Box<dyn FnMut() + 'static>> )

Sets the callback function that is called whenever the state of the stream changes.

source

pub fn set_write_callback( &mut self, callback: Option<Box<dyn FnMut(usize) + 'static>> )

Sets the callback function that is called when new data may be written to the stream.

The callback accepts an argument giving the number of bytes.

source

pub fn set_read_callback( &mut self, callback: Option<Box<dyn FnMut(usize) + 'static>> )

Sets the callback function that is called when new data is available from the stream.

The callback accepts an argument giving the number of bytes.

source

pub fn set_overflow_callback( &mut self, callback: Option<Box<dyn FnMut() + 'static>> )

Sets the callback function that is called when a buffer overflow happens. (Only for playback streams).

source

pub fn get_underflow_index(&self) -> Option<u64>

Gets at what position the latest underflow occurred.

None is returned if this information is not known (e.g. if no underflow has occurred).

This can be used inside the underflow callback to get information about the current underflow. (Only for playback streams).

source

pub fn set_underflow_callback( &mut self, callback: Option<Box<dyn FnMut() + 'static>> )

Sets the callback function that is called when a buffer underflow happens.

(Only for playback streams).

source

pub fn set_started_callback( &mut self, callback: Option<Box<dyn FnMut() + 'static>> )

Sets the callback function that is called when the server starts playback after an underrun or on initial startup.

This only informs that audio is flowing again, it is no indication that audio started to reach the speakers already. (Only for playback streams).

source

pub fn set_latency_update_callback( &mut self, callback: Option<Box<dyn FnMut() + 'static>> )

Sets the callback function that is called whenever a latency information update happens.

Useful on FlagSet::AUTO_TIMING_UPDATE streams only.

source

pub fn set_moved_callback( &mut self, callback: Option<Box<dyn FnMut() + 'static>> )

Sets the callback function that is called whenever the stream is moved to a different sink/source.

Use get_device_name() or get_device_index() to query the new sink/source.

source

pub fn set_suspended_callback( &mut self, callback: Option<Box<dyn FnMut() + 'static>> )

Sets the callback function that is called whenever the sink/source this stream is connected to is suspended or resumed.

Use is_suspended() to query the new suspend status. Please note that the suspend status might also change when the stream is moved between devices. Thus if you call this function you very likely want to call set_moved_callback() too.

source

pub fn set_event_callback( &mut self, callback: Option<Box<dyn FnMut(String, Proplist) + 'static>> )

Sets the callback function that is called whenever a meta/policy control event is received.

The callback is given a name which represents what event occurred. The set of defined events can be extended at any time. Also, server modules may introduce additional message types so make sure that your callback function ignores messages it doesn’t know. Some well known event names can be found in the event_names submodule. It is also given an (owned) property list.

source

pub fn set_buffer_attr_callback( &mut self, callback: Option<Box<dyn FnMut() + 'static>> )

Sets the callback function that is called whenever the buffer attributes on the server side change.

Please note that the buffer attributes can change when moving a stream to a different sink/source too, hence if you use this callback you should use set_moved_callback() as well.

source

pub fn cork( &mut self, callback: Option<Box<dyn FnMut(bool) + 'static>> ) -> Operation<dyn FnMut(bool)>

Pauses playback of this stream temporarily.

Available on both playback and recording streams.

The pause operation is executed as quickly as possible. If a cork is very quickly followed by an uncork, this might not actually have any effect on the stream that is output. You can use is_corked() to find out whether the stream is currently paused or not. Normally a stream will be created in uncorked state. If you pass FlagSet::START_CORKED as a flag when connecting the stream, it will be created in corked state.

The optional callback must accept a bool, which indicates success.

Panics if the underlying C function returns a null pointer.

source

pub fn uncork( &mut self, callback: Option<Box<dyn FnMut(bool) + 'static>> ) -> Operation<dyn FnMut(bool)>

Resumes playback of this stream.

Available on both playback and recording streams.

The un-pause operation is executed as quickly as possible. If an uncork is very quickly followed by a cork, this might not actually have any effect on the stream that is output. You can use is_corked() to find out whether the stream is currently paused or not. Normally a stream will be created in uncorked state. If you pass FlagSet::START_CORKED as a flag when connecting the stream, it will be created in corked state.

The optional callback must accept a bool, which indicates success.

Panics if the underlying C function returns a null pointer.

source

pub fn flush( &mut self, callback: Option<Box<dyn FnMut(bool) + 'static>> ) -> Operation<dyn FnMut(bool)>

Flushes the playback or record buffer of this stream.

This discards any audio data in the buffer. Most of the time you’re better off using the parameter seek of write() instead of this function.

The optional callback must accept a bool, which indicates success.

Panics if the underlying C function returns a null pointer.

source

pub fn prebuf( &mut self, callback: Option<Box<dyn FnMut(bool) + 'static>> ) -> Operation<dyn FnMut(bool)>

Re-enables prebuffering if specified in the BufferAttr structure.

Available for playback streams only.

The optional callback must accept a bool, which indicates success.

Panics if the underlying C function returns a null pointer.

source

pub fn trigger( &mut self, callback: Option<Box<dyn FnMut(bool) + 'static>> ) -> Operation<dyn FnMut(bool)>

Requests immediate start of playback on this stream.

This disables prebuffering temporarily if specified in the BufferAttr structure. Available for playback streams only.

The optional callback must accept a bool, which indicates success.

Panics if the underlying C function returns a null pointer.

source

pub fn set_name( &mut self, name: &str, callback: Option<Box<dyn FnMut(bool) + 'static>> ) -> Operation<dyn FnMut(bool)>

Renames the stream.

The optional callback must accept a bool, which indicates success.

Panics if the underlying C function returns a null pointer.

source

pub fn get_time(&self) -> Result<Option<MicroSeconds>, PAErr>

Gets the current playback/recording time.

This is based on the data in the timing info structure returned by get_timing_info(). The returned time is in the sound card clock domain, which usually runs at a slightly different rate than the system clock.

This function will usually only return new data if a timing info update has been received. Only if timing interpolation has been requested (FlagSet::INTERPOLATE_TIMING) the data from the last timing update is used for an estimation of the current playback/recording time based on the local time that passed since the timing info structure has been acquired.

The time value returned by this function is guaranteed to increase monotonically (the returned value is always greater or equal to the value returned by the last call). This behaviour can be disabled by using FlagSet::NOT_MONOTONIC. This may be desirable to better deal with bad estimations of transport latencies, but may have strange effects if the application is not able to deal with time going ‘backwards’.

The time interpolator activated by FlagSet::INTERPOLATE_TIMING favours ‘smooth’ time graphs over accurate ones to improve the smoothness of UI operations that are tied to the audio clock. If accuracy is more important to you, you might need to estimate your timing based on the data from get_timing_info() yourself or not work with interpolated timing at all and instead always query the server side for the most up to date timing with update_timing_info().

If no timing information has been received yet this call will return Ok(None). For more details see get_timing_info().

source

pub fn get_latency(&self) -> Result<Latency, PAErr>

Determines the total stream latency.

This function is based on get_time(). The returned time is in the sound card clock domain, which usually runs at a slightly different rate than the system clock.

In case the stream is a monitoring stream the result can be negative, i.e. the captured samples are not yet played, in which case Ok(Latency::Negative(usecs)) will be returned instead of Ok(Latency::Positive(usecs))

If no timing information has been received yet, this call will return Ok(Latency::None).

For more details see get_timing_info() and get_time().

source

pub fn get_timing_info<'a>(&mut self) -> Option<&'a TimingInfo>

Gets the latest raw timing data structure.

The returned pointer refers to an internal read-only instance of the timing structure. The user should make a copy of this structure if wanting to modify it. An in-place update to this data structure may be requested using update_timing_info().

If no timing information has been received before (i.e. by requesting update_timing_info() or by using FlagSet::AUTO_TIMING_UPDATE), this function will return None (as it will also if an error occurs).

Please note that the write_index member field (and only this field) is updated on each write() call, not just when a timing update has been received.

source

pub fn get_sample_spec<'a>(&mut self) -> Option<&'a Spec>

Gets a pointer to the stream’s sample specification.

source

pub fn get_channel_map<'a>(&mut self) -> Option<&'a Map>

Gets a pointer to the stream’s channel map.

source

pub fn get_format_info(&self) -> Option<Info>

Gets a pointer to the stream’s format.

source

pub fn get_buffer_attr<'a>(&mut self) -> Option<&'a BufferAttr>

Gets the per-stream server-side buffer metrics of the stream.

Only valid after the stream has been connected successfully. This will return the actual configured buffering metrics, which may differ from what was requested during connect_record() or connect_playback(). This call will always return the actual per-stream server-side buffer metrics, regardless whether FlagSet::ADJUST_LATENCY is set or not.

source

pub fn set_buffer_attr<F>( &mut self, attr: &BufferAttr, callback: F ) -> Operation<dyn FnMut(bool)>where F: FnMut(bool) + 'static,

Changes the buffer metrics of the stream during playback.

The server might have chosen different buffer metrics then requested. The selected metrics may be queried with get_buffer_attr() as soon as the callback is called. Only valid after the stream has been connected successfully. Please be aware of the slightly different semantics of the call depending whether FlagSet::ADJUST_LATENCY is set or not.

The callback must accept a bool, which indicates success.

Panics if the underlying C function returns a null pointer.

source

pub fn update_sample_rate<F>( &mut self, rate: u32, callback: F ) -> Operation<dyn FnMut(bool)>where F: FnMut(bool) + 'static,

Changes the stream sampling rate during playback.

You need to pass FlagSet::VARIABLE_RATE in the flags parameter of connect_playback() if you plan to use this function. Only valid after the stream has been connected successfully.

The callback must accept a bool, which indicates success.

Panics if the underlying C function returns a null pointer.

source

pub fn update_proplist<F>( &mut self, mode: UpdateMode, proplist: &mut Proplist, callback: F ) -> Operation<dyn FnMut(bool)>where F: FnMut(bool) + 'static,

Updates the property list of the sink input/source output of this stream, adding new entries.

Please note that it is highly recommended to set as many properties initially via new_with_proplist() as possible instead a posteriori with this function, since that information may be used to route this stream to the right device.

The callback must accept a bool, which indicates success.

Panics if the underlying C function returns a null pointer.

source

pub fn remove_proplist<F>( &mut self, keys: &[&str], callback: F ) -> Operation<dyn FnMut(bool)>where F: FnMut(bool) + 'static,

Updates the property list of the sink input/source output of this stream, removing entries.

The callback must accept a bool, which indicates success.

Panics if the underlying C function returns a null pointer.

source

pub fn set_monitor_stream(&mut self, sink_input_index: u32) -> Result<(), PAErr>

For record streams connected to a monitor source: monitors only a very specific sink input of the sink.

This function needs to be called before connect_record() is called.

source

pub fn get_monitor_stream(&self) -> Option<u32>

Gets the sink input index previously set with set_monitor_stream().

Trait Implementations§

source§

impl Drop for Stream

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl Send for Stream

source§

impl Sync for Stream

Auto Trait Implementations§

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere 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, U> Into<U> for Twhere 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, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

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

§

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.