Skip to main content

sonora_aec3/
block.rs

1//! Multi-band, multi-channel audio block.
2//!
3//! Ported from `modules/audio_processing/aec3/block.h`.
4
5use std::mem;
6
7use crate::common::BLOCK_SIZE;
8
9/// Contains one or more channels of 4 ms of audio data.
10///
11/// The audio is split into one or more frequency bands, each with a sampling
12/// rate of 16 kHz. Each band/channel combination holds `BLOCK_SIZE` (64)
13/// samples.
14#[derive(Clone, Debug)]
15pub struct Block {
16    num_bands: usize,
17    num_channels: usize,
18    data: Vec<f32>,
19}
20
21impl Block {
22    pub fn new(num_bands: usize, num_channels: usize) -> Self {
23        Self {
24            num_bands,
25            num_channels,
26            data: vec![0.0; num_bands * num_channels * BLOCK_SIZE],
27        }
28    }
29
30    pub fn new_with_value(num_bands: usize, num_channels: usize, value: f32) -> Self {
31        Self {
32            num_bands,
33            num_channels,
34            data: vec![value; num_bands * num_channels * BLOCK_SIZE],
35        }
36    }
37
38    pub fn num_bands(&self) -> usize {
39        self.num_bands
40    }
41
42    pub fn num_channels(&self) -> usize {
43        self.num_channels
44    }
45
46    /// Modifies the number of channels and zeros all samples.
47    pub fn set_num_channels(&mut self, num_channels: usize) {
48        self.num_channels = num_channels;
49        self.data
50            .resize(self.num_bands * self.num_channels * BLOCK_SIZE, 0.0);
51        self.data.fill(0.0);
52    }
53
54    /// Returns a slice of `BLOCK_SIZE` samples for the given band and channel.
55    pub fn view(&self, band: usize, channel: usize) -> &[f32] {
56        let idx = self.get_index(band, channel);
57        &self.data[idx..idx + BLOCK_SIZE]
58    }
59
60    /// Returns a mutable slice of `BLOCK_SIZE` samples for the given band and channel.
61    pub fn view_mut(&mut self, band: usize, channel: usize) -> &mut [f32] {
62        let idx = self.get_index(band, channel);
63        &mut self.data[idx..idx + BLOCK_SIZE]
64    }
65
66    /// Swaps audio data with another block.
67    pub fn swap(&mut self, other: &mut Self) {
68        mem::swap(&mut self.num_bands, &mut other.num_bands);
69        mem::swap(&mut self.num_channels, &mut other.num_channels);
70        mem::swap(&mut self.data, &mut other.data);
71    }
72
73    fn get_index(&self, band: usize, channel: usize) -> usize {
74        (band * self.num_channels + channel) * BLOCK_SIZE
75    }
76}