/src/adhd/audio_processor/src/util.rs
Line | Count | Source |
1 | | // Copyright 2024 The ChromiumOS Authors |
2 | | // Use of this source code is governed by a BSD-style license that can be |
3 | | // found in the LICENSE file. |
4 | | |
5 | | use std::path::Path; |
6 | | |
7 | | use anyhow::ensure; |
8 | | use anyhow::Context; |
9 | | use hound::WavReader; |
10 | | use nix::sys::resource::setrlimit; |
11 | | use nix::sys::resource::Resource; |
12 | | |
13 | | use crate::MultiBuffer; |
14 | | use crate::Sample; |
15 | | |
16 | | /// Read the WAVE file at path into a single MultiBuffer<T>. |
17 | 0 | pub fn read_wav<T: Sample + hound::Sample>( |
18 | 0 | path: &Path, |
19 | 0 | ) -> anyhow::Result<(hound::WavSpec, MultiBuffer<T>)> { |
20 | 0 | let r = WavReader::open(path).context("WavReader::open")?; |
21 | 0 | let spec = r.spec(); |
22 | 0 | let channels = spec.channels as usize; |
23 | 0 | let frames = r.len() as usize / channels; |
24 | 0 | let mut out = MultiBuffer::<T>::new_equilibrium(crate::Shape { channels, frames }); |
25 | 0 | for (i, sample) in r.into_samples().enumerate() { |
26 | 0 | out[i % channels][i / channels] = sample?; |
27 | | } |
28 | | |
29 | 0 | Ok((spec, out)) |
30 | 0 | } |
31 | | |
32 | | // TODO(b/268271100): Call the C version when we can build C code before Rust. |
33 | 0 | pub fn set_thread_priority() -> anyhow::Result<()> { |
34 | | // CRAS_SERVER_RT_THREAD_PRIORITY 12 |
35 | 0 | let p = 12; |
36 | 0 | setrlimit(Resource::RLIMIT_RTPRIO, p, p).context("setrlimit")?; |
37 | | |
38 | | // SAFETY: sched_param is properly initialized. |
39 | | unsafe { |
40 | 0 | let sched_param = libc::sched_param { |
41 | 0 | sched_priority: p as i32, |
42 | 0 | }; |
43 | 0 | let rc = libc::pthread_setschedparam(libc::pthread_self(), libc::SCHED_RR, &sched_param); |
44 | 0 | ensure!(rc == 0, "pthread_setschedparam returned {rc}"); |
45 | | } |
46 | | |
47 | 0 | Ok(()) |
48 | 0 | } |