Skip to main content

oa/audio/
batch.rs

1//! Variable-length batching helpers composed from existing operations.
2//!
3//! `Audio` remains a rank-two `[channels, samples]` value; a batch of
4//! variable-length clips is represented by stacking clips as channel rows
5//! after `pad_to`/`crop_to` equalizes lengths. Every per-row operation —
6//! `stft`, `stft_complex`, `istft`, `mel_spectrogram`, `mix_snr`, and the
7//! signal family — then batches across items for free, and [`length_mask`]
8//! provides the row-wise mask losses and reductions need.
9
10use crate::{Audio, Error, Matrix, Result, matrix};
11
12use super::audio::AudioChannelLayout;
13
14/// Right-pad `input` with silence to exactly `samples` per channel.
15///
16/// # Errors
17///
18/// Returns an error when `samples` is smaller than the input length; use
19/// [`crop_to`] to shorten instead. Allocation or dispatch failures propagate.
20pub fn pad_to(input: &Audio, samples: usize) -> Result<Audio> {
21	let current = input.samples();
22	if samples < current {
23		return Err(Error::invalid_argument(format!(
24			"audio::pad_to target {samples} is smaller than input length {current}"
25		)));
26	}
27	if samples == current {
28		return Audio::new(
29			input.as_matrix().clone(),
30			input.sample_rate(),
31			input.layout(),
32		);
33	}
34	let zeros = Matrix::allocate(
35		input.as_matrix().runtime(),
36		vec![input.channels(), samples - current],
37		input.channels() * (samples - current),
38		crate::DType::F32,
39	)?;
40	let padded = matrix::concat(&[input.as_matrix().clone(), zeros], 1)?;
41	Audio::new(padded, input.sample_rate(), input.layout())
42}
43
44/// Crop `input` to its first `samples` samples per channel.
45///
46/// # Errors
47///
48/// Returns an error when `samples` is zero or exceeds the input length; use
49/// [`pad_to`] to extend instead.
50pub fn crop_to(input: &Audio, samples: usize) -> Result<Audio> {
51	let current = input.samples();
52	if samples == 0 || samples > current {
53		return Err(Error::invalid_argument(format!(
54			"audio::crop_to target {samples} must be in 1..={current}"
55		)));
56	}
57	let cropped = matrix::slice(
58		input.as_matrix(),
59		1,
60		0,
61		i64::try_from(samples)
62			.map_err(|_| Error::out_of_range("audio::crop_to samples exceeds i64"))?,
63	)?;
64	Audio::new(cropped, input.sample_rate(), input.layout())
65}
66
67/// Stack clips as consecutive channel rows, producing one batched
68/// `[total_channels, samples]` audio.
69///
70/// All inputs must share sample rate, sample count, and channel layout;
71/// use [`pad_to`] or [`crop_to`] first for variable-length sources. Item
72/// `i`'s channels occupy the contiguous rows following items `0..i`, which
73/// keeps per-item channel grouping recoverable from the layouts.
74///
75/// # Errors
76///
77/// Returns an error for an empty input list, mismatched metadata, or a
78/// failing concatenate dispatch.
79pub fn stack(inputs: &[Audio]) -> Result<Audio> {
80	let Some(first) = inputs.first() else {
81		return Err(Error::invalid_argument(
82			"audio::stack requires at least one input",
83		));
84	};
85	let (rate, samples, layout) = (first.sample_rate(), first.samples(), first.layout());
86	for (index, input) in inputs.iter().enumerate().skip(1) {
87		if input.sample_rate() != rate || input.samples() != samples || input.layout() != layout {
88			return Err(Error::invalid_argument(format!(
89				"audio::stack input {index} must share rate, samples, and layout"
90			)));
91		}
92	}
93	let matrices: Vec<Matrix> = inputs
94		.iter()
95		.map(|input| input.as_matrix().clone())
96		.collect();
97	let channels: usize = inputs.iter().map(Audio::channels).sum();
98	let stacked = matrix::concat(&matrices, 0)?;
99	Audio::new(
100		stacked,
101		rate,
102		AudioChannelLayout::for_channel_count(channels),
103	)
104}
105
106/// Build a per-row `0/1` length mask matching `reference`'s channel count and
107/// sample width: `mask[r, n] = 1` when `n < lengths[r]`.
108///
109/// Pair with [`stack`]: one length entry per output row marks each clip's
110/// true sample count so masked losses and reductions can ignore padding.
111/// The mask is deterministic metadata and is uploaded like the mel
112/// filterbank.
113///
114/// # Errors
115///
116/// Returns an error when `lengths` does not have one entry per channel or any
117/// entry exceeds the reference's sample count.
118pub fn length_mask(reference: &Audio, lengths: &[usize]) -> Result<Matrix> {
119	if lengths.len() != reference.channels() {
120		return Err(Error::invalid_argument(format!(
121			"audio::length_mask expects {} lengths; found {}",
122			reference.channels(),
123			lengths.len()
124		)));
125	}
126	let samples = reference.samples();
127	if let Some(length) = lengths.iter().find(|length| **length > samples) {
128		return Err(Error::invalid_argument(format!(
129			"audio::length_mask entry {length} exceeds sample count {samples}"
130		)));
131	}
132	let mut values = vec![0.0_f32; lengths.len() * samples];
133	for (row, length) in lengths.iter().enumerate() {
134		for value in values.iter_mut().skip(row * samples).take(*length) {
135			*value = 1.0;
136		}
137	}
138	Matrix::new_from_slice_handle(
139		reference.as_matrix().runtime(),
140		vec![lengths.len(), samples],
141		&values,
142	)
143}