corevm-guest 0.1.28

API/SDK for CoreVM guest programs
Documentation
#![allow(clippy::missing_safety_doc)]

use crate::{c, AudioSample};
use core::mem::size_of_val;
use corevm_types::{flags::ReadAudioFrames, AudioMode};

/// Get audio input mode.
///
/// Returns `None` if there is no audio input.
#[inline]
pub fn audio_input_mode() -> Option<AudioMode> {
	let regs = unsafe { c::audio_input_mode() };
	AudioMode::from_regs(regs).ok()
}

/// Read frames from the audio input into the supplied buffer.
///
/// Returns `None` if the there are no more frames in the audio input.
/// On success returns `Some(Ok(n))` where `n` is the number of _samples_.
///
/// This is a non-blocking variant of [`read_audio_frames_into`].
#[inline]
pub fn try_read_audio_frames_into<T: AudioSample>(buf: &mut [T]) -> Option<usize> {
	let buf_len_in_bytes = size_of_val(buf) as u64;
	let len_in_bytes = unsafe {
		c::read_audio_frames(
			buf.as_mut_ptr() as u64,
			buf_len_in_bytes,
			ReadAudioFrames::NON_BLOCKING.bits(),
		)
	};
	if len_in_bytes == u64::MAX {
		return None;
	}
	let len = len_in_bytes as usize / size_of::<T>();
	Some(len)
}

/// Read frames from the audio input into the supplied buffer.
///
/// Blocks execution if there are no more frames in the audio input until new data arrives.
/// For a non-blocking variant see [`try_read_audio_frames_into`].
///
/// Returns the number of _samples_ copied.
#[inline]
pub fn read_audio_frames_into<T: AudioSample>(buf: &mut [T]) -> usize {
	let len_bytes =
		unsafe { c::read_audio_frames(buf.as_mut_ptr() as u64, size_of_val(buf) as u64, 0) };
	len_bytes as usize / size_of::<T>()
}