Skip to main content

AudioPlayback

Struct AudioPlayback 

Source
pub(crate) struct AudioPlayback {
    pub(crate) shared: Arc<PbShared>,
}
Expand description

Python-facing mic-playback handle, symmetric to AudioCapture.

Same lifecycle protocol, but a PA playback stream instead of a record stream, and a bounded drop-oldest queue fed by write / write_red instead of a Python callback. Python never holds the PA handle — only the playback thread touches it — so a close-versus-inflight-write use-after-free is structurally impossible here.

Fields§

§shared: Arc<PbShared>

Implementations§

Source§

impl AudioPlayback

Source

pub(crate) fn inner(&self) -> &Arc<Inner>

Source

pub(crate) fn decode_packet( &self, py: Python<'_>, data: &Bound<'_, PyAny>, decode: impl FnOnce(&mut OpusPlaybackDecoder, &[u8], &PlayQueue) + Send, ) -> PyResult<()>

Run decode on this run’s Opus decoder with the bytes of a bytes-like data, off the GIL. The shared body of write and write_red.

Gated on worker_alive: it raises once no playback thread services the queue (start failure, stop, or a PA outage the session loop could not reconnect through), so the caller’s reopen-on-error path engages instead of the audio being swallowed silently. A reconnect in progress stays “alive” and keeps queueing.

A bytes payload is immutable, so it is borrowed in place across the GIL release. Any other bytes-like object — a C-contiguous buffer-protocol exporter of any item format, the same set CPython’s own y* argument parsing accepts (memoryview, bytearray, array, NumPy, an AudioFrame, …) — may be mutated by another Python thread once the GIL is dropped, so its bytes are copied under the GIL into the decoder’s reusable scratch buffer first; an Opus packet is a few hundred bytes, and the steady state allocates nothing.

Source§

impl AudioPlayback

Source

pub(crate) fn new() -> Self

Source

pub(crate) fn start( &self, py: Python<'_>, settings: &Bound<'_, PyAny>, ) -> PyResult<()>

Start (or restart) mic playback into the virtual sink. The playback mirror of start_capture.

Same shape as capture: a re-entrant start from the playback thread just undoes a nested self-stop; the worker is spawned with the GIL released (the stop/clear ordering lives in spawn_worker); the handle is registered for the atexit sweep; and the ~2 s await_start handshake raises a FAILED start (with last_error) after tearing down only the thread THIS call spawned (identity-checked, sparing a concurrent winner), while a start still in its retry ladder returns Ok and is watched through state / last_error. Before spawning, it applies this run’s byte bound + frame alignment to the queue (dropping any stale audio) and creates the Opus decoder up front, since the mic uplink is always Opus and write / write_red decode packets to PCM off the GIL for this same run.

Source

pub(crate) fn write( &self, py: Python<'_>, data: &Bound<'_, PyAny>, ) -> PyResult<()>

Push one Opus mic packet for playback. The steady-state hot path.

data is any bytes-like object (bytes, memoryview, bytearray, an AudioFrame, …); see decode_packet for the liveness gate and how the payload is borrowed. The decode runs with the GIL released — it touches no Python state, so dropping the GIL lets it run concurrently with the rest of the app — and a bad packet is dropped rather than corrupting the stream. It never blocks on PA (drop-oldest happens inside PlayQueue::push).

Source

pub(crate) fn write_red( &self, py: Python<'_>, data: &Bound<'_, PyAny>, primary_ts: i64, ) -> PyResult<()>

Play one RFC 2198 RED mic frame from the WebRTC/UDP uplink, recovering across any packet loss on the way in. The lossy-transport counterpart of write.

The payload is de-framed, loss-recovered, and decoded entirely off the GIL by decode_red_into_queue (see there for why RED exists and why the decode runs off the GIL). primary_ts is the packet’s monotonic RTP timestamp; the redundant blocks carry offsets back from it. Accepts any bytes-like data and is gated on worker_alive exactly like write (see decode_packet).

Source

pub(crate) fn stop(&self, py: Python<'_>)

Stop mic playback, joining the playback thread.

A re-entrant stop from the playback thread records a self-stop only (it cannot self-join) and never clobbers an external stop already in effect. Otherwise it joins with the GIL released so a slow PA disconnect cannot stall the interpreter; stop returns only once the thread is joined and the sink is released.

Source

pub(crate) fn is_running(&self) -> bool

True while a playback worker is connected and running with no stop pending; false while still starting and after a failure — see state to tell those apart.

Source

pub(crate) fn state(&self) -> &'static str

Lifecycle phase: "idle", "starting", "running" or "failed", the playback mirror of AudioCapture.state.

Source

pub(crate) fn last_error(&self) -> Option<String>

Why the last run failed, or None while no run has failed since the last start.

Trait Implementations§

Source§

impl DerefToPyAny for AudioPlayback

Source§

impl Drop for AudioPlayback

Source§

fn drop(&mut self)

Best-effort stop on GC/dealloc; symmetric to AudioCapture::drop.

Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more
Source§

impl ExtractPyClassWithClone for AudioPlayback

Source§

impl<'py> IntoPyObject<'py> for AudioPlayback

Source§

type Target = AudioPlayback

The Python output type
Source§

type Output = Bound<'py, <AudioPlayback as IntoPyObject<'py>>::Target>

The smart pointer type to use. Read more
Source§

type Error = PyErr

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

fn into_pyobject( self, py: Python<'py>, ) -> Result<<Self as IntoPyObject<'_>>::Output, <Self as IntoPyObject<'_>>::Error>

Performs the conversion.
Source§

impl PyClass for AudioPlayback

Source§

const NAME: &str = "AudioPlayback"

Name of the class. Read more
Source§

type Frozen = False

Whether the pyclass is frozen. Read more
Source§

impl PyClassImpl for AudioPlayback

Source§

const MODULE: Option<&str> = ::core::option::Option::None

Module which the class will be associated with. Read more
Source§

const IS_BASETYPE: bool = false

#[pyclass(subclass)]
Source§

const IS_SUBCLASS: bool = false

#[pyclass(extends=…)]
Source§

const IS_MAPPING: bool = false

#[pyclass(mapping)]
Source§

const IS_SEQUENCE: bool = false

#[pyclass(sequence)]
Source§

const IS_IMMUTABLE_TYPE: bool = false

#[pyclass(immutable_type)]
Source§

const RAW_DOC: &'static CStr = c"Python-facing mic-playback handle, symmetric to `AudioCapture`.\n\nSame lifecycle protocol, but a PA playback stream instead of a record stream, and a\nbounded drop-oldest queue fed by `write` / `write_red` instead of a Python callback.\nPython never holds the PA handle \xe2\x80\x94 only the playback thread touches it \xe2\x80\x94 so a\nclose-versus-inflight-write use-after-free is structurally impossible here.\x00"

Docstring for the class provided on the struct or enum. Read more
Source§

const DOC: &'static CStr

Fully rendered class doc, including the text_signature if a constructor is defined. Read more
Source§

type Layout = <<AudioPlayback as PyClassImpl>::BaseNativeType as PyClassBaseType>::Layout<AudioPlayback>

Description of how this class is laid out in memory
Source§

type BaseType = PyAny

Base class
Source§

type ThreadChecker = NoopThreadChecker

This handles following two situations: Read more
Source§

type PyClassMutability = <<PyAny as PyClassBaseType>::PyClassMutability as PyClassMutability>::MutableChild

Immutable or mutable
Source§

type Dict = PyClassDummySlot

Specify this class has #[pyclass(dict)] or not.
Source§

type WeakRef = PyClassDummySlot

Specify this class has #[pyclass(weakref)] or not.
Source§

type BaseNativeType = PyAny

The closest native ancestor. This is PyAny by default, and when you declare #[pyclass(extends=PyDict)], it’s PyDict.
Source§

fn items_iter() -> PyClassItemsIter

Source§

fn lazy_type_object() -> &'static LazyTypeObject<Self>

§

fn dict_offset() -> Option<PyObjectOffset>

Used to provide the dictoffset slot (equivalent to tp_dictoffset)
§

fn weaklist_offset() -> Option<PyObjectOffset>

Used to provide the weaklistoffset slot (equivalent to tp_weaklistoffset
Source§

impl PyClassNewTextSignature for AudioPlayback

Source§

const TEXT_SIGNATURE: &'static str = "()"

Source§

impl PyMethods<AudioPlayback> for PyClassImplCollector<AudioPlayback>

Source§

fn py_methods(self) -> &'static PyClassItems

Source§

impl PyTypeInfo for AudioPlayback

Source§

const NAME: &str = <Self as ::pyo3::PyClass>::NAME

👎Deprecated since 0.28.0:

prefer using ::type_object(py).name() to get the correct runtime value

Class name.
Source§

const MODULE: Option<&str> = <Self as ::pyo3::impl_::pyclass::PyClassImpl>::MODULE

👎Deprecated since 0.28.0:

prefer using ::type_object(py).module() to get the correct runtime value

Module name, if any.
Source§

fn type_object_raw(py: Python<'_>) -> *mut PyTypeObject

Returns the PyTypeObject instance for this type.
§

fn type_object(py: Python<'_>) -> Bound<'_, PyType>

Returns the safe abstraction over the type object.
§

fn is_type_of(object: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of this type or a subclass of this type.
§

fn is_exact_type_of(object: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of this type.

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

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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.

§

impl<'py, T> IntoPyObjectExt<'py> for T
where T: IntoPyObject<'py>,

§

fn into_bound_py_any(self, py: Python<'py>) -> Result<Bound<'py, PyAny>, PyErr>

Converts self into an owned Python object, dropping type information.
§

fn into_py_any(self, py: Python<'py>) -> Result<Py<PyAny>, PyErr>

Converts self into an owned Python object, dropping type information and unbinding it from the 'py lifetime.
§

fn into_pyobject_or_pyerr(self, py: Python<'py>) -> Result<Self::Output, PyErr>

Converts self into a Python object. Read more
§

impl<T> PyErrArguments for T
where T: for<'py> IntoPyObject<'py> + Send + Sync,

§

fn arguments(self, py: Python<'_>) -> Py<PyAny>

Arguments for exception
§

impl<T> PyTypeCheck for T
where T: PyTypeInfo,

§

fn type_check(object: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of Self, which may include a subtype. Read more
§

fn classinfo_object(py: Python<'_>) -> Bound<'_, PyAny>

Returns the expected type as a possible argument for the isinstance and issubclass function. Read more
Source§

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

Source§

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

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