refactor: drop internal bridge/ffi layers; exporter family lands
Single-lib cleanup: the per-crate src/bridge/ and src/ffi.rs layers are gone (oakundo/oakcommon/oaknode/oaktimeline/oakcodec/oakaudio/ oakrender/oaktask/oakplugin/oakstorage); cross-crate calls are plain Rust, CHandle marshalling shrinks to the oakengine boundary, and tests call the Rust APIs directly (pure C-ABI wrapper tests removed where the domain layer already covers the behavior). exporter.h family implemented: oakengine_export_render (CLI contract), oakengine_export_render_with_params (was a stub), last_error and progress callback; synchronous path reuses task_create_export + start_sync. Fixes on the way: oaktask video ticket self-deadlock, audio params dropped on the export path, codec encoder AAC slicing and H.264 time base. Real-mp4 tests cover both entry points, progress and the illegal-argument matrix. Also: oakstorage session maps null project handles to None (version- info path), configstore test double literal 3.14 -> 3.15 (clippy PI lint), oakaudio output callback scratch buffer + env-aware P1 test, cli media round-trip test uses a generated 16-frame clip (no more minute-long debug runs).
This commit is contained in:
@@ -18,8 +18,7 @@ oakcodec = { path = "../oakcodec" }
|
||||
# crate calls ffmpeg-next directly (same as oakcodec). The oakffmpeg-link
|
||||
# dependency above emits the transitive link flags of the static FFmpeg.
|
||||
ffmpeg-next = "9"
|
||||
# Real audio output (M12 P1): the preview playback stream. The PortAudio
|
||||
# C library must be installed (macOS: brew install portaudio).
|
||||
portaudio = "0.8"
|
||||
|
||||
cpal = {version = "0.18", features = ["pulseaudio", "pipewire", "jack", "asio"]}
|
||||
# `std::error::Error` impls for the crate-internal error enum.
|
||||
thiserror = "2"
|
||||
|
||||
@@ -1,135 +0,0 @@
|
||||
// Oak Video Editor - Non-Linear Video Editor
|
||||
// Copyright (C) 2026 Oak Team
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! oakcodec C ABI calls (audio encoding + decoding for the manager and
|
||||
//! waveform extraction) — now direct Rust calls into the oakcodec crate
|
||||
//! (single-lib unification, see `docs/zh/plans/riir/single-lib.md`).
|
||||
//!
|
||||
//! The previous `*mut c_void` handle convention drifted from the real
|
||||
//! codec C ABI (which uses the shared [`CHandle`]); the wrappers below
|
||||
//! match the oakcodec ffi signatures exactly.
|
||||
|
||||
use std::ffi::{c_char, c_int};
|
||||
|
||||
use crate::handle::CHandle;
|
||||
|
||||
/// `oakcodec_encoding_params` — single-lib unification: aliases the
|
||||
/// oakcodec crate's POD (identical layout; only the audio fields are
|
||||
/// consumed by oakaudio).
|
||||
pub type EncodingParams = oakcodec::ffi::encoder::oakcodec_encoding_params;
|
||||
|
||||
/// `oakcodec_audio_stream_info` — audio stream metadata from probing.
|
||||
/// Single-lib unification: aliases the oakcodec crate's POD.
|
||||
pub type AudioStreamInfo = oakcodec::decoder::OakCodecAudioStreamInfo;
|
||||
|
||||
/// `oakcodec_encoder_init` — create an encoder for `params`.
|
||||
pub unsafe fn oakcodec_encoder_init(params: *const EncodingParams) -> CHandle {
|
||||
unsafe { oakcodec::ffi::encoder::oakcodec_encoder_init(params) }
|
||||
}
|
||||
|
||||
/// `oakcodec_encoder_free`.
|
||||
pub unsafe fn oakcodec_encoder_free(encoder: *mut CHandle) {
|
||||
unsafe { oakcodec::ffi::encoder::oakcodec_encoder_free(encoder) }
|
||||
}
|
||||
|
||||
/// `oakcodec_encoder_open`.
|
||||
pub unsafe fn oakcodec_encoder_open(encoder: CHandle) -> c_int {
|
||||
unsafe { oakcodec::ffi::encoder::oakcodec_encoder_open(encoder) }
|
||||
}
|
||||
|
||||
/// `oakcodec_encoder_write_audio` — feed interleaved `f32` audio.
|
||||
pub unsafe fn oakcodec_encoder_write_audio(
|
||||
encoder: CHandle,
|
||||
samples: *const f32,
|
||||
frame_count: c_int,
|
||||
) -> c_int {
|
||||
unsafe { oakcodec::ffi::encoder::oakcodec_encoder_write_audio(encoder, samples, frame_count) }
|
||||
}
|
||||
|
||||
/// `oakcodec_encoder_flush`.
|
||||
pub unsafe fn oakcodec_encoder_flush(encoder: CHandle) -> c_int {
|
||||
unsafe { oakcodec::ffi::encoder::oakcodec_encoder_flush(encoder) }
|
||||
}
|
||||
|
||||
/// `oakcodec_encoder_last_error` — copy the last error string into `buf`.
|
||||
pub unsafe fn oakcodec_encoder_last_error(
|
||||
encoder: CHandle,
|
||||
buf: *mut c_char,
|
||||
buf_size: c_int,
|
||||
) -> c_int {
|
||||
unsafe { oakcodec::ffi::encoder::oakcodec_encoder_last_error(encoder, buf, buf_size) }
|
||||
}
|
||||
|
||||
/// `oakcodec_decoder_probe` — create a probe handle for a file.
|
||||
pub unsafe fn oakcodec_decoder_probe(filename: *const c_char) -> CHandle {
|
||||
unsafe { oakcodec::ffi::decoder::oakcodec_decoder_probe(filename) }
|
||||
}
|
||||
|
||||
/// `oakcodec_decoder_free`.
|
||||
pub unsafe fn oakcodec_decoder_free(decoder: *mut CHandle) {
|
||||
unsafe { oakcodec::ffi::decoder::oakcodec_decoder_free(decoder) }
|
||||
}
|
||||
|
||||
/// `oakcodec_decoder_probe_audio_stream_count`.
|
||||
pub unsafe fn oakcodec_decoder_probe_audio_stream_count(probe: CHandle) -> c_int {
|
||||
unsafe { oakcodec::ffi::decoder::oakcodec_decoder_probe_audio_stream_count(probe) }
|
||||
}
|
||||
|
||||
/// `oakcodec_decoder_probe_get_audio_stream` — copy audio stream info.
|
||||
pub unsafe fn oakcodec_decoder_probe_get_audio_stream(
|
||||
probe: CHandle,
|
||||
index: c_int,
|
||||
out: *mut AudioStreamInfo,
|
||||
) -> c_int {
|
||||
unsafe { oakcodec::ffi::decoder::oakcodec_decoder_probe_get_audio_stream(probe, index, out) }
|
||||
}
|
||||
|
||||
/// `oakcodec_decoder_open` — open stream `stream_index` for decoding.
|
||||
pub unsafe fn oakcodec_decoder_open(
|
||||
decoder: CHandle,
|
||||
filename: *const c_char,
|
||||
stream_index: c_int,
|
||||
) -> c_int {
|
||||
unsafe { oakcodec::ffi::decoder::oakcodec_decoder_open(decoder, filename, stream_index) }
|
||||
}
|
||||
|
||||
/// `oakcodec_decoder_decode_audio` — decode/convert frames into `buf`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub unsafe fn oakcodec_decoder_decode_audio(
|
||||
decoder: CHandle,
|
||||
in_num: c_int,
|
||||
in_den: c_int,
|
||||
out_num: c_int,
|
||||
out_den: c_int,
|
||||
sample_rate: c_int,
|
||||
channel_layout: u64,
|
||||
buf: *mut f32,
|
||||
buf_frames: c_int,
|
||||
) -> c_int {
|
||||
unsafe {
|
||||
oakcodec::ffi::decoder::oakcodec_decoder_decode_audio(
|
||||
decoder,
|
||||
in_num,
|
||||
in_den,
|
||||
out_num,
|
||||
out_den,
|
||||
sample_rate,
|
||||
channel_layout,
|
||||
buf,
|
||||
buf_frames,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
// Oak Video Editor - Non-Linear Video Editor
|
||||
// Copyright (C) 2026 Oak Team
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! oakcommon C ABI calls (config access + ffmpeg format conversion) —
|
||||
//! now direct Rust calls into the oakcommon crate (single-lib
|
||||
//! unification, see `docs/zh/plans/riir/single-lib.md`).
|
||||
|
||||
use std::ffi::{c_char, c_int};
|
||||
|
||||
/// `oakcommon_config_get` — copy a config string value into `buf`
|
||||
/// (two-stage; returns the required size including NUL).
|
||||
pub unsafe fn oakcommon_config_get(
|
||||
group: *const c_char,
|
||||
key: *const c_char,
|
||||
buf: *mut c_char,
|
||||
buf_size: c_int,
|
||||
) -> c_int {
|
||||
unsafe { oakcommon::ffi::config::oakcommon_config_get(group, key, buf, buf_size) }
|
||||
}
|
||||
|
||||
/// `oakcommon_config_get_int` — read an integer config value with a
|
||||
/// default.
|
||||
pub unsafe fn oakcommon_config_get_int(
|
||||
group: *const c_char,
|
||||
key: *const c_char,
|
||||
default: c_int,
|
||||
) -> c_int {
|
||||
unsafe { oakcommon::ffi::config::oakcommon_config_get_int(group, key, default) }
|
||||
}
|
||||
|
||||
/// `oakcommon_ffmpegutils_get_ffmpeg_sample_format` — map an ffmpeg
|
||||
/// sample format enum to the oak core format, or the reverse.
|
||||
pub unsafe fn oakcommon_ffmpegutils_get_ffmpeg_sample_format(
|
||||
smp_fmt: c_int,
|
||||
out: *mut c_int,
|
||||
) -> c_int {
|
||||
unsafe {
|
||||
oakcommon::ffi::ffmpegutils::oakcommon_ffmpegutils_get_ffmpeg_sample_format(smp_fmt, out)
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
// Oak Video Editor - Non-Linear Video Editor
|
||||
// Copyright (C) 2026 Oak Team
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! C ABI imports from other oak modules (signatures mirror the public
|
||||
//! headers verbatim; resolved at link time).
|
||||
|
||||
pub mod codec;
|
||||
pub mod common;
|
||||
@@ -17,20 +17,16 @@
|
||||
//! The `audio_config` namespace from `src/audio/src/configbridge.*`:
|
||||
//! audio-specific configuration read through the oakcommon C ABI.
|
||||
|
||||
use std::error::Error;
|
||||
use std::ffi::CString;
|
||||
|
||||
use std::str::FromStr;
|
||||
use oakcommon::configstore::*;
|
||||
/// PortAudio output buffer size in frames; 0 = let PortAudio choose.
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/src/configbridge.cpp:30`
|
||||
/// (`audio_config::output_buffer_size`).
|
||||
pub fn output_buffer_size() -> i32 {
|
||||
unsafe {
|
||||
crate::bridge::common::oakcommon_config_get_int(
|
||||
std::ptr::null(),
|
||||
c"AudioOutputBufferSize".as_ptr(),
|
||||
0,
|
||||
)
|
||||
}
|
||||
ConfigStore::instance().get_int(None, "AudioOutputBufferSize", 0)
|
||||
}
|
||||
|
||||
/// Name of the configured audio device for `is_output_device`
|
||||
@@ -39,35 +35,19 @@ pub fn output_buffer_size() -> i32 {
|
||||
/// `// CPP-PARITY: src/audio/src/configbridge.cpp:36`
|
||||
/// (`audio_config::device_name`): two-stage size query; `size <= 1`
|
||||
/// (absent or empty string) yields the empty string.
|
||||
pub fn device_name(is_output_device: bool) -> CString {
|
||||
pub fn device_name(is_output_device: bool) -> Result<String, Box<dyn Error>> {
|
||||
let key = if is_output_device {
|
||||
c"AudioOutput"
|
||||
"AudioOutput"
|
||||
} else {
|
||||
c"AudioInput"
|
||||
"AudioInput"
|
||||
};
|
||||
unsafe {
|
||||
let size = crate::bridge::common::oakcommon_config_get(
|
||||
std::ptr::null(),
|
||||
key.as_ptr(),
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
);
|
||||
if size <= 1 {
|
||||
// Absent (OAKCOMMON_E_NOT_FOUND) or empty
|
||||
return CString::default();
|
||||
}
|
||||
let mut buf = vec![0u8; size as usize];
|
||||
if crate::bridge::common::oakcommon_config_get(
|
||||
std::ptr::null(),
|
||||
key.as_ptr(),
|
||||
buf.as_mut_ptr() as *mut std::ffi::c_char,
|
||||
size,
|
||||
) < 0
|
||||
{
|
||||
return CString::default();
|
||||
}
|
||||
// The buffer is NUL-terminated by the callee.
|
||||
CString::from_vec_with_nul(buf)
|
||||
.unwrap_or_else(|e| CString::new(e.into_bytes()).unwrap_or_default())
|
||||
let store = ConfigStore::instance();
|
||||
let size = i32::from_str(store.get(None, key)?.as_str())?;
|
||||
if size <= 1 {
|
||||
// Absent (OAKCOMMON_E_NOT_FOUND) or empty
|
||||
return Err(Box::new(crate::error::Error::NotFound));
|
||||
}
|
||||
let mut buf = vec![0u8; size as usize];
|
||||
let name = store.get(None, key)?;
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ pub const OAKAUDIO_E_NOT_FOUND: i32 = -60004;
|
||||
pub const OAKAUDIO_E_NOMEM: i32 = -60005;
|
||||
|
||||
/// Crate-internal result type; the FFI layer maps it to the codes.
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
|
||||
|
||||
/// Crate-internal error.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,226 +0,0 @@
|
||||
// Oak Video Editor - Non-Linear Video Editor
|
||||
// Copyright (C) 2026 Oak Team
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Refcounted-handle scaffolding. Same pattern as the oaknode crate
|
||||
//! (`src/node/rust/src/handle.rs`); intentionally duplicated rather
|
||||
//! than shared — each module DLL must run its own addref/release code
|
||||
//! (the function pointers in a handle always point into the DLL that
|
||||
//! created the object).
|
||||
//!
|
||||
//! The `AudioManager` is the one exception: it uses the same `CHandle`
|
||||
//! layout but with singleton semantics (addref/release no-ops). See
|
||||
//! `manager.rs` and `include/audio/manager.h`.
|
||||
//!
|
||||
//! `// CPP-PARITY: src/audio/c_api/refcounted.h` (RefCounted box,
|
||||
//! make_handle_in_place, free_handle) and `src/audio/c_api/alive.cpp`
|
||||
//! (alive ledger behind `oakaudio_debug_alive_count`).
|
||||
|
||||
use std::panic::{catch_unwind, AssertUnwindSafe};
|
||||
use std::sync::atomic::{AtomicI32, AtomicU32, Ordering};
|
||||
|
||||
use crate::error::{Error, OAKAUDIO_E_FAILED, OAKAUDIO_OK};
|
||||
|
||||
/// ABI version stamped into every handle.
|
||||
pub const OAKAUDIO_ABI_VERSION: u32 = 1;
|
||||
|
||||
/// Live-object ledger behind `oakaudio_debug_alive_count`.
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/c_api/alive.cpp` (`g_alive`).
|
||||
static ALIVE: AtomicI32 = AtomicI32::new(0);
|
||||
|
||||
/// Current number of live refcounted oakaudio objects.
|
||||
pub fn alive_count() -> i32 {
|
||||
ALIVE.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Heap box behind a handle's `ctx`.
|
||||
pub struct RefBox<T: ?Sized> {
|
||||
/// Atomic reference count.
|
||||
pub refs: AtomicU32,
|
||||
/// Boxed value.
|
||||
pub value: T,
|
||||
}
|
||||
|
||||
/// The shared ABI value-handle type (single-lib unification, see
|
||||
/// `docs/zh/plans/riir/single-lib.md`): one canonical
|
||||
/// `{ctx, addref, release, abi_version}` type in `oakcore-rs`, re-exported
|
||||
/// here so the crate's `ffi.rs` signatures and handle scaffolding stay
|
||||
/// source-compatible. It is `Clone + Copy` (handles cross the C ABI by
|
||||
/// value) and `Send + Sync` (refcounted, shared across threads).
|
||||
pub use oakcore_rs::handle::CHandle;
|
||||
|
||||
/// `// CPP-PARITY: src/audio/c_api/refcounted.h` (`ref_counted_addref`).
|
||||
unsafe extern "C" fn owned_addref<T: Send + 'static>(ctx: *mut std::ffi::c_void) {
|
||||
// SAFETY: `ctx` is either NULL or points to a `RefBox<T>` created by
|
||||
// `make_owned`; we only touch it through the reference while it is live.
|
||||
if let Some(b) = unsafe { (ctx as *const RefBox<T>).as_ref() } {
|
||||
b.refs.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// `// CPP-PARITY: src/audio/c_api/refcounted.h` (`ref_counted_release`):
|
||||
/// destroys the box at zero and decrements the alive ledger.
|
||||
unsafe extern "C" fn owned_release<T: Send + 'static>(ctx: *mut std::ffi::c_void) {
|
||||
// SAFETY: `ctx` is either NULL or points to a live `RefBox<T>` created
|
||||
// by `make_owned`; the refcount guards against double-free, and the box
|
||||
// is only reclaimed once the count reaches zero.
|
||||
if let Some(b) = unsafe { (ctx as *const RefBox<T>).as_ref() } {
|
||||
if b.refs.fetch_sub(1, Ordering::AcqRel) == 1 {
|
||||
drop(unsafe { Box::from_raw(ctx as *mut RefBox<T>) });
|
||||
ALIVE.fetch_sub(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Owned handle with count 1; empty on allocation failure.
|
||||
pub fn make_owned<T: Send + 'static>(value: T) -> CHandle {
|
||||
let b = Box::new(RefBox {
|
||||
refs: AtomicU32::new(1),
|
||||
value,
|
||||
});
|
||||
ALIVE.fetch_add(1, Ordering::Relaxed);
|
||||
CHandle {
|
||||
ctx: Box::into_raw(b) as *mut std::ffi::c_void,
|
||||
addref: Some(owned_addref::<T>),
|
||||
release: Some(owned_release::<T>),
|
||||
abi_version: OAKAUDIO_ABI_VERSION,
|
||||
}
|
||||
}
|
||||
|
||||
/// No-op addref/release for singleton (borrowed) handles.
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/c_api/manager.cpp` (`singleton_addref` /
|
||||
/// `singleton_release`).
|
||||
unsafe extern "C" fn noop_ref(_ctx: *mut std::ffi::c_void) {}
|
||||
|
||||
/// Borrowed handle for an object owned elsewhere (addref/release are
|
||||
/// no-ops; nothing is ever freed through the handle).
|
||||
///
|
||||
/// # Safety
|
||||
/// Caller guarantees `ptr` outlives every derived handle.
|
||||
pub unsafe fn make_borrowed<T: Send + 'static>(ptr: *mut T) -> CHandle {
|
||||
CHandle {
|
||||
ctx: ptr as *mut std::ffi::c_void,
|
||||
addref: Some(noop_ref),
|
||||
release: Some(noop_ref),
|
||||
abi_version: OAKAUDIO_ABI_VERSION,
|
||||
}
|
||||
}
|
||||
|
||||
/// Typed view into an owned handle; `None` for empty handles.
|
||||
///
|
||||
/// # Safety
|
||||
/// `T` must be the boxed type.
|
||||
pub unsafe fn get<T: 'static>(h: &CHandle) -> Option<&T> {
|
||||
if h.ctx.is_null() {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: caller guarantees `h` is a valid owned handle whose ctx points
|
||||
// to a `RefBox<T>`; the handle stays alive through the returned borrow.
|
||||
let v = unsafe { &(*(h.ctx as *const RefBox<T>)).value };
|
||||
Some(v)
|
||||
}
|
||||
|
||||
/// Typed mutable view into an owned handle; `None` for empty handles.
|
||||
///
|
||||
/// # Safety
|
||||
/// `T` must be the boxed type.
|
||||
pub unsafe fn get_mut<T: 'static>(h: &CHandle) -> Option<&mut T> {
|
||||
if h.ctx.is_null() {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: caller guarantees `h` is a valid owned handle whose ctx points
|
||||
// to a `RefBox<T>`; the handle stays alive through the returned borrow,
|
||||
// and the caller must not alias it with other live borrows.
|
||||
let v = unsafe { &mut (*(h.ctx as *mut RefBox<T>)).value };
|
||||
Some(v)
|
||||
}
|
||||
|
||||
/// Shared free() body: release the ctx, no-op on NULL/empty handle.
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/c_api/refcounted.h` (`free_handle`).
|
||||
///
|
||||
/// # Safety
|
||||
/// `self_` must be a valid handle pointer or NULL.
|
||||
pub unsafe fn free_handle(h: *mut CHandle) {
|
||||
// SAFETY: caller guarantees `h` is a valid handle pointer or NULL.
|
||||
if let Some(r) = unsafe { h.as_mut() } {
|
||||
if !r.ctx.is_null() {
|
||||
if let Some(release) = r.release {
|
||||
// SAFETY: the release fn belongs to the same DLL and
|
||||
// accepts the ctx it originally created.
|
||||
unsafe { release(r.ctx) };
|
||||
}
|
||||
r.ctx = std::ptr::null_mut();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Panic-catching FFI wrapper for i32-returning exports.
|
||||
pub fn guard<F: FnOnce() -> crate::error::Result<()>>(f: F) -> i32 {
|
||||
match catch_unwind(AssertUnwindSafe(f)) {
|
||||
Ok(Ok(())) => OAKAUDIO_OK,
|
||||
Ok(Err(e)) => e.code(),
|
||||
Err(_) => OAKAUDIO_E_FAILED,
|
||||
}
|
||||
}
|
||||
|
||||
/// Panic-catching FFI wrapper for handle-returning exports.
|
||||
pub fn guard_handle<F: FnOnce() -> crate::error::Result<CHandle>>(f: F) -> CHandle {
|
||||
match catch_unwind(AssertUnwindSafe(f)) {
|
||||
Ok(Ok(h)) => h,
|
||||
Ok(Err(_)) | Err(_) => CHandle::null(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Panic-catching FFI wrapper for i32 value-returning exports (errors map
|
||||
/// to the negative error code).
|
||||
pub fn guard_int<F: FnOnce() -> crate::error::Result<i32>>(f: F) -> i32 {
|
||||
match catch_unwind(AssertUnwindSafe(f)) {
|
||||
Ok(Ok(v)) => v,
|
||||
Ok(Err(e)) => e.code(),
|
||||
Err(_) => OAKAUDIO_E_FAILED,
|
||||
}
|
||||
}
|
||||
|
||||
/// Panic-catching FFI wrapper for void exports.
|
||||
pub fn guard_void<F: FnOnce()>(f: F) {
|
||||
let _ = catch_unwind(AssertUnwindSafe(f));
|
||||
}
|
||||
|
||||
/// Copy a human-readable error string into a C buffer (NUL-terminated,
|
||||
/// truncated to fit). Returns the required size including the NUL.
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/c_api/manager.cpp` (`write_error`).
|
||||
pub fn write_error(s: &str, buf: *mut std::ffi::c_char, buf_size: i32) {
|
||||
if !buf.is_null() && buf_size > 0 {
|
||||
let bytes = s.as_bytes();
|
||||
let n = bytes.len().min((buf_size - 1) as usize);
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(bytes.as_ptr(), buf as *mut u8, n);
|
||||
*(buf as *mut u8).add(n) = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Convenience: map a condition to an Invalid error.
|
||||
pub fn invalid_if(cond: bool) -> crate::error::Result<()> {
|
||||
if cond {
|
||||
Err(Error::Invalid)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -30,11 +30,8 @@
|
||||
#![deny(unsafe_op_in_unsafe_fn)]
|
||||
#![warn(missing_docs)]
|
||||
|
||||
pub mod bridge;
|
||||
pub mod config;
|
||||
pub mod error;
|
||||
pub mod ffi;
|
||||
pub mod handle;
|
||||
pub mod levelmeter;
|
||||
pub mod manager;
|
||||
pub mod params;
|
||||
|
||||
+339
-403
@@ -26,13 +26,15 @@
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Mutex, MutexGuard, OnceLock};
|
||||
|
||||
use crate::bridge::codec::EncodingParams;
|
||||
use std::sync::{Arc, Mutex, MutexGuard, OnceLock};
|
||||
use cpal::{Device, DeviceId};
|
||||
use cpal::traits::{DeviceTrait, HostTrait};
|
||||
use oakcodec::encoder::Encoder;
|
||||
use oakcodec::encodingparams::EncodingParams;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::handle::{make_borrowed, CHandle};
|
||||
use crate::params::AudioParams;
|
||||
use crate::previewdevice::PreviewAudioDevice;
|
||||
use crate::error::Error::NotFound;
|
||||
|
||||
/// `paNoDevice` (PortAudio "no device" sentinel; also the default when no
|
||||
/// device is configured).
|
||||
@@ -46,7 +48,11 @@ static DESTROYED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// Manager state (all device/stream fields; PortAudio itself is not bridged,
|
||||
/// see [`ManagerInner::default`] for the degradations).
|
||||
struct ManagerInner {
|
||||
///
|
||||
/// Public since the single-lib unification (the deleted `ffi`/`bridge`
|
||||
/// C ABI is gone): the oakengine facade calls the singleton's methods
|
||||
/// directly through [`instance`] instead of crossing the old C ABI.
|
||||
pub struct ManagerInner {
|
||||
/// Current output device index.
|
||||
output_device: i32,
|
||||
/// Current input device index.
|
||||
@@ -62,8 +68,8 @@ struct ManagerInner {
|
||||
/// The real PortAudio output stream (M12 P1; opened lazily on the
|
||||
/// first pushed samples).
|
||||
output_device_stream: crate::outputdevice::PortAudioOutput,
|
||||
/// Active oakcodec recording encoder (NULL when idle).
|
||||
recording: Option<CHandle>,
|
||||
/// Active oakcodec recording encoder (None when idle).
|
||||
recording: Option<Arc<dyn Encoder>>,
|
||||
}
|
||||
|
||||
// SAFETY: the raw encoder pointer is only touched while the manager mutex is
|
||||
@@ -89,290 +95,308 @@ impl Default for ManagerInner {
|
||||
}
|
||||
}
|
||||
|
||||
/// Lock the manager behind a handle; `OAKAUDIO_E_STATE` for empty handles.
|
||||
fn with_instance(h: &CHandle) -> Result<MutexGuard<'static, ManagerInner>> {
|
||||
if h.is_null() {
|
||||
return Err(Error::State);
|
||||
impl ManagerInner {
|
||||
/// Create the process-wide AudioManager (no-op when it exists). Returns
|
||||
/// `OAKAUDIO_OK` or `OAKAUDIO_E_NOMEM`.
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/c_api/manager.cpp:73` (C++ allocates with `new`
|
||||
/// and reports `OAKAUDIO_E_NOMEM` on exception; Rust allocation infallibly
|
||||
/// panics, so the error code is never produced).
|
||||
pub fn create_instance() -> Result<()> {
|
||||
DESTROYED.store(false, Ordering::SeqCst);
|
||||
let _ = MANAGER.get_or_init(|| Mutex::new(ManagerInner::default()));
|
||||
Ok(())
|
||||
}
|
||||
// SAFETY: `instance()` only creates borrowed handles whose ctx points at
|
||||
// the MANAGER Mutex, which lives in a static for the whole process.
|
||||
let m: &'static Mutex<ManagerInner> = unsafe { &*(h.ctx as *const Mutex<ManagerInner>) };
|
||||
Ok(m.lock().unwrap_or_else(|p| p.into_inner()))
|
||||
}
|
||||
|
||||
/// Create the process-wide AudioManager (no-op when it exists). Returns
|
||||
/// `OAKAUDIO_OK` or `OAKAUDIO_E_NOMEM`.
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/c_api/manager.cpp:73` (C++ allocates with `new`
|
||||
/// and reports `OAKAUDIO_E_NOMEM` on exception; Rust allocation infallibly
|
||||
/// panics, so the error code is never produced).
|
||||
pub fn create_instance() -> Result<()> {
|
||||
DESTROYED.store(false, Ordering::SeqCst);
|
||||
let _ = MANAGER.get_or_init(|| Mutex::new(ManagerInner::default()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Destroy the process-wide AudioManager (no-op when absent).
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/c_api/manager.cpp:85` — the C++ singleton is
|
||||
/// deleted and re-creatable; `OnceLock` cannot be reset, so a `DESTROYED`
|
||||
/// flag makes [`instance`] return an empty handle (and a later
|
||||
/// [`create_instance`] resurrects the existing box).
|
||||
pub fn destroy_instance() {
|
||||
DESTROYED.store(true, Ordering::SeqCst);
|
||||
// The C++ singleton is deleted on destroy; the OnceLock cannot be
|
||||
// reset, so the resurrection must at least come back with a fresh
|
||||
// playback state (the previous session's output params/buffer would
|
||||
// otherwise leak into the next session's meters and clock).
|
||||
if let Some(m) = MANAGER.get() {
|
||||
let mut inner = m.lock().unwrap_or_else(|e| e.into_inner());
|
||||
inner.output_params = None;
|
||||
inner.output_buffer.clear();
|
||||
inner.output_started = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Return a handle to the process-wide AudioManager (borrowed; empty when
|
||||
/// no instance exists).
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/c_api/manager.cpp:90` (`wrap`; the handle is a
|
||||
/// borrowed singleton whose addref/release are no-ops).
|
||||
pub fn instance() -> CHandle {
|
||||
if DESTROYED.load(Ordering::SeqCst) {
|
||||
return CHandle::null();
|
||||
}
|
||||
match MANAGER.get() {
|
||||
Some(m) => {
|
||||
// SAFETY: `m` is the process-wide singleton; borrowed handles do
|
||||
// not free it, so it outlives every handle.
|
||||
unsafe { make_borrowed(m as *const _ as *mut Mutex<ManagerInner>) }
|
||||
}
|
||||
None => CHandle::null(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Release a manager handle. No-op (singleton), safe on NULL/empty.
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/c_api/manager.cpp:95` — releasing never
|
||||
/// destroys; just clear the caller's copy.
|
||||
pub fn free(self_: *mut CHandle) {
|
||||
unsafe {
|
||||
if let Some(h) = self_.as_mut() {
|
||||
h.ctx = std::ptr::null_mut();
|
||||
/// Destroy the process-wide AudioManager (no-op when absent).
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/c_api/manager.cpp:85` — the C++ singleton is
|
||||
/// deleted and re-creatable; `OnceLock` cannot be reset, so a `DESTROYED`
|
||||
/// flag makes [`instance`] return an empty handle (and a later
|
||||
/// [`create_instance`] resurrects the existing box).
|
||||
pub fn destroy_instance() {
|
||||
DESTROYED.store(true, Ordering::SeqCst);
|
||||
// The C++ singleton is deleted on destroy; the OnceLock cannot be
|
||||
// reset, so the resurrection must at least come back with a fresh
|
||||
// playback state (the previous session's output params/buffer would
|
||||
// otherwise leak into the next session's meters and clock).
|
||||
if let Some(m) = MANAGER.get() {
|
||||
let mut inner = m.lock().unwrap_or_else(|e| e.into_inner());
|
||||
inner.output_params = None;
|
||||
inner.output_buffer.clear();
|
||||
inner.output_started = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes between output-notify pulses (0 disables).
|
||||
pub fn set_output_notify_interval(self_: &CHandle, bytes: i64) -> Result<()> {
|
||||
if bytes < 0 {
|
||||
return Err(Error::Invalid);
|
||||
/// Return a handle to the process-wide AudioManager (borrowed; empty when
|
||||
/// no instance exists).
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/c_api/manager.cpp:90` (`wrap`; the handle is a
|
||||
/// borrowed singleton whose addref/release are no-ops).
|
||||
pub fn instance(&self) -> Option<&Self> {
|
||||
if DESTROYED.load(Ordering::SeqCst) {
|
||||
return None;
|
||||
}
|
||||
match MANAGER.get() {
|
||||
Some(m) => {
|
||||
// SAFETY: `m` is the process-wide singleton; borrowed handles do
|
||||
// not free it, so it outlives every handle.
|
||||
Some(self)
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
let mut m = with_instance(self_)?;
|
||||
m.output_buffer.set_notify_interval(bytes);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Push a block of samples to the output device, opening/restarting the
|
||||
/// stream when the params changed.
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/src/audiomanager.cpp:111` — the PortAudio
|
||||
/// open/start path is not bridged; the buffer is configured and written
|
||||
/// directly and the "stream" is marked running. `error_buf` is written by
|
||||
/// the FFI layer from the returned error.
|
||||
pub fn push_to_output(
|
||||
self_: &CHandle,
|
||||
params: AudioParams,
|
||||
samples: &[u8],
|
||||
_error_buf: &mut [u8],
|
||||
) -> Result<()> {
|
||||
let mut m = with_instance(self_)?;
|
||||
if m.output_params.as_ref() != Some(¶ms) {
|
||||
m.output_params = Some(params);
|
||||
m.output_buffer.set_params(params);
|
||||
// M12 P1: open (or re-open) the real output stream on a format
|
||||
// change; device < 0 selects the system default. A stream
|
||||
// failure keeps the samples buffered (silent playback) instead
|
||||
// of failing the push.
|
||||
let device = m.output_device;
|
||||
let rate = params.sample_rate;
|
||||
/// Bytes between output-notify pulses (0 disables).
|
||||
pub fn set_output_notify_interval(&self, bytes: i64) -> Result<()> {
|
||||
if bytes < 0 {
|
||||
return Err(Box::new(Error::Invalid));
|
||||
}
|
||||
self.output_buffer.set_notify_interval(bytes);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Push a block of samples to the output device, opening/restarting the
|
||||
/// stream when the params changed.
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/src/audiomanager.cpp:111` — the PortAudio
|
||||
/// open/start path is not bridged; the buffer is configured and written
|
||||
/// directly and the "stream" is marked running. `error_buf` is written by
|
||||
/// the FFI layer from the returned error.
|
||||
pub fn push_to_output(
|
||||
&mut self,
|
||||
params: AudioParams,
|
||||
samples: &[u8],
|
||||
_error_buf: &mut [u8],
|
||||
) -> Result<()> {
|
||||
if self.output_params.as_ref() != Some(¶ms) {
|
||||
self.output_params = Some(params);
|
||||
self.output_buffer.set_params(params);
|
||||
// M12 P1: open (or re-open) the real output stream on a format
|
||||
// change; device < 0 selects the system default. A stream
|
||||
// failure keeps the samples buffered (silent playback) instead
|
||||
// of failing the push.
|
||||
let device = self.output_device;
|
||||
let rate = params.sample_rate;
|
||||
let channels = params.channel_count();
|
||||
let sink = self.output_buffer.clone();
|
||||
let _ = self.output_device_stream.ensure_open(device, rate, channels, sink);
|
||||
}
|
||||
self.output_buffer.write(samples);
|
||||
self.output_started = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Discard buffered output.
|
||||
pub fn clear_buffered_output(&self) -> Result<()> {
|
||||
self.output_buffer.clear();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stop the output stream.
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/src/audiomanager.cpp:229` (`stop_output` aborts
|
||||
/// the stream and clears the buffer).
|
||||
pub fn stop_output(&mut self) -> Result<()> {
|
||||
self.output_started = false;
|
||||
self.output_buffer.clear();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Seconds of audio consumed by the output device since the last reset,
|
||||
/// compensated for output latency; negative when no stream is running.
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/src/audiomanager.cpp:169` — PortAudio's
|
||||
/// `outputLatency` is not representable without a live stream, so the buffer
|
||||
/// clock is used directly (the `max(0, ...)` clamp is kept).
|
||||
pub fn seconds(&self, out: &mut f64) -> Result<()> {
|
||||
if !self.output_started {
|
||||
*out = -1.0;
|
||||
return Ok(());
|
||||
}
|
||||
let rate = self.output_params.map(|p| p.sample_rate).unwrap_or(0);
|
||||
if rate <= 0 {
|
||||
*out = -1.0;
|
||||
return Ok(());
|
||||
}
|
||||
let secs = self.output_buffer.output_frames_consumed() as f64 / f64::from(rate);
|
||||
*out = secs.max(0.0);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Restart the output clock at zero.
|
||||
pub fn reset_output_clock(&self) -> Result<()> {
|
||||
self.output_buffer.reset_output_frames();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Current output device index (`paNoDevice` = -1) or a negative error code.
|
||||
pub fn get_output_device(&self) -> Result<i32> {
|
||||
Ok(self.output_device)
|
||||
}
|
||||
|
||||
/// Set the output device index.
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/src/audiomanager.cpp:238` (the device is
|
||||
/// recorded and the stream closed; PortAudio's index validation and name
|
||||
/// logging are not bridged).
|
||||
pub fn set_output_device(&mut self, device: i32) -> Result<()> {
|
||||
self.output_device = device;
|
||||
self.output_started = false;
|
||||
self.output_buffer.clear();
|
||||
// The stream reopens with the new device on the next push.
|
||||
self.output_device_stream.close();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Current input device index or a negative error code.
|
||||
pub fn get_input_device(&self) -> Result<i32> {
|
||||
Ok(self.input_device)
|
||||
}
|
||||
|
||||
/// Set the input device index.
|
||||
pub fn set_input_device(&mut self, device: i32) -> Result<()> {
|
||||
self.input_device = device;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Close the output stream and re-initialize PortAudio.
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/src/audiomanager.cpp:271` (PortAudio terminate/
|
||||
/// initialize is not bridged; the output side is reset).
|
||||
pub fn hard_reset(&mut self) -> Result<()> {
|
||||
self.output_started = false;
|
||||
self.output_buffer.clear();
|
||||
self.output_device_stream.close();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start recording the input device to a file via the oakcodec encoder
|
||||
/// (direct Rust calls; the encoder is a `dyn Encoder` value). The input
|
||||
/// stream is always captured as interleaved f32.
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/src/audiomanager.cpp:278` (encoder init/open;
|
||||
/// the PortAudio input stream is not bridged). On failure the encoder's
|
||||
/// last-error string is surfaced when available.
|
||||
pub fn start_recording(
|
||||
&mut self,
|
||||
params: &EncodingParams,
|
||||
_error_buf: &mut [u8],
|
||||
) -> Result<()> {
|
||||
if self.input_device == PA_NO_DEVICE {
|
||||
return Err(Box::new(Error::Failed("no input device".to_string())));
|
||||
}
|
||||
let encoder = oakcodec::encoder::create_from_params(params)
|
||||
.ok_or_else(|| Error::Failed("failed to create encoder for recording".to_string()))?;
|
||||
encoder
|
||||
.configure(params)
|
||||
.map_err(|e| Error::Failed(format!("encoder configure failed: {e:?}")))?;
|
||||
if let Err(e) = encoder.open() {
|
||||
let detail = encoder.get_error();
|
||||
let msg = if detail.is_empty() {
|
||||
format!("failed to open encoder for recording: {e:?}")
|
||||
} else {
|
||||
format!("failed to open encoder for recording: {detail}")
|
||||
};
|
||||
return Err(Box::new(Error::Failed(msg)));
|
||||
}
|
||||
self.recording = Some(encoder);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stop recording.
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/src/audiomanager.cpp:328` (the PortAudio input
|
||||
/// stream is not bridged; the encoder is flushed and closed).
|
||||
pub fn stop_recording(&mut self) -> Result<()> {
|
||||
if let Some(encoder) = self.recording.take() {
|
||||
let _ = encoder.flush();
|
||||
let _ = encoder.close();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// Peak level (linear, 0..1 and above) of each channel of the buffered,
|
||||
/// not-yet-consumed output, written to `peaks` in channel order.
|
||||
/// Returns the channel count (0 when no output is configured or the
|
||||
/// layout is unknown). Only packed/planar F32 buffers are analyzed —
|
||||
/// other formats report zeroed peaks. The analysis window is the most
|
||||
/// recent 8192 frames of the queue.
|
||||
///
|
||||
/// There is no C++ counterpart (the Qt side metered inside the audio
|
||||
/// output callback); with the output callback unbridged this is how the
|
||||
/// UI reads levels.
|
||||
pub fn output_levels(&self, peaks: &mut [f32]) -> Result<i32> {
|
||||
let Some(params) = self.output_params else {
|
||||
return Ok(0);
|
||||
};
|
||||
let channels = params.channel_count();
|
||||
let sink = m.output_buffer.clone();
|
||||
let _ = m.output_device_stream.ensure_open(device, rate, channels, sink);
|
||||
}
|
||||
m.output_buffer.write(samples);
|
||||
m.output_started = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Discard buffered output.
|
||||
pub fn clear_buffered_output(self_: &CHandle) -> Result<()> {
|
||||
let mut m = with_instance(self_)?;
|
||||
m.output_buffer.clear();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stop the output stream.
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/src/audiomanager.cpp:229` (`stop_output` aborts
|
||||
/// the stream and clears the buffer).
|
||||
pub fn stop_output(self_: &CHandle) -> Result<()> {
|
||||
let mut m = with_instance(self_)?;
|
||||
m.output_started = false;
|
||||
m.output_buffer.clear();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Seconds of audio consumed by the output device since the last reset,
|
||||
/// compensated for output latency; negative when no stream is running.
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/src/audiomanager.cpp:169` — PortAudio's
|
||||
/// `outputLatency` is not representable without a live stream, so the buffer
|
||||
/// clock is used directly (the `max(0, ...)` clamp is kept).
|
||||
pub fn seconds(self_: &CHandle, out: &mut f64) -> Result<()> {
|
||||
let m = with_instance(self_)?;
|
||||
if !m.output_started {
|
||||
*out = -1.0;
|
||||
return Ok(());
|
||||
}
|
||||
let rate = m.output_params.map(|p| p.sample_rate).unwrap_or(0);
|
||||
if rate <= 0 {
|
||||
*out = -1.0;
|
||||
return Ok(());
|
||||
}
|
||||
let secs = m.output_buffer.output_frames_consumed() as f64 / f64::from(rate);
|
||||
*out = secs.max(0.0);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Restart the output clock at zero.
|
||||
pub fn reset_output_clock(self_: &CHandle) -> Result<()> {
|
||||
let m = with_instance(self_)?;
|
||||
m.output_buffer.reset_output_frames();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Current output device index (`paNoDevice` = -1) or a negative error code.
|
||||
pub fn get_output_device(self_: &CHandle) -> Result<i32> {
|
||||
let m = with_instance(self_)?;
|
||||
Ok(m.output_device)
|
||||
}
|
||||
|
||||
/// Set the output device index.
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/src/audiomanager.cpp:238` (the device is
|
||||
/// recorded and the stream closed; PortAudio's index validation and name
|
||||
/// logging are not bridged).
|
||||
pub fn set_output_device(self_: &CHandle, device: i32) -> Result<()> {
|
||||
let mut m = with_instance(self_)?;
|
||||
m.output_device = device;
|
||||
m.output_started = false;
|
||||
m.output_buffer.clear();
|
||||
// The stream reopens with the new device on the next push.
|
||||
m.output_device_stream.close();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Current input device index or a negative error code.
|
||||
pub fn get_input_device(self_: &CHandle) -> Result<i32> {
|
||||
let m = with_instance(self_)?;
|
||||
Ok(m.input_device)
|
||||
}
|
||||
|
||||
/// Set the input device index.
|
||||
pub fn set_input_device(self_: &CHandle, device: i32) -> Result<()> {
|
||||
let mut m = with_instance(self_)?;
|
||||
m.input_device = device;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Close the output stream and re-initialize PortAudio.
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/src/audiomanager.cpp:271` (PortAudio terminate/
|
||||
/// initialize is not bridged; the output side is reset).
|
||||
pub fn hard_reset(self_: &CHandle) -> Result<()> {
|
||||
let mut m = with_instance(self_)?;
|
||||
m.output_started = false;
|
||||
m.output_buffer.clear();
|
||||
m.output_device_stream.close();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start recording the input device to a file via the oakcodec encoder C
|
||||
/// ABI. The input stream is always captured as interleaved f32.
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/src/audiomanager.cpp:278` (encoder init/open;
|
||||
/// the PortAudio input stream is not bridged). On failure the encoder's
|
||||
/// last-error string is surfaced when available.
|
||||
pub fn start_recording(
|
||||
self_: &CHandle,
|
||||
params: &EncodingParams,
|
||||
_error_buf: &mut [u8],
|
||||
) -> Result<()> {
|
||||
let mut m = with_instance(self_)?;
|
||||
if m.input_device == PA_NO_DEVICE {
|
||||
return Err(Error::Failed("no input device".to_string()));
|
||||
}
|
||||
eprintln!(
|
||||
"MANAGER before encoder_init: audio_enabled={} codec={}",
|
||||
params.audio_enabled, params.audio_codec
|
||||
);
|
||||
let mut enc = unsafe { crate::bridge::codec::oakcodec_encoder_init(params) };
|
||||
eprintln!(
|
||||
"MANAGER encoder_init null? {} ptr={:p} size={}",
|
||||
enc.is_null(),
|
||||
params as *const EncodingParams,
|
||||
std::mem::size_of::<EncodingParams>()
|
||||
);
|
||||
let direct =
|
||||
unsafe { oakcodec::ffi::encoder::oakcodec_encoder_init(params as *const EncodingParams) };
|
||||
eprintln!("MANAGER direct init null? {}", direct.is_null());
|
||||
if !direct.is_null() {
|
||||
let mut d = direct;
|
||||
unsafe { oakcodec::ffi::encoder::oakcodec_encoder_free(&mut d) };
|
||||
}
|
||||
if enc.is_null() {
|
||||
return Err(Error::Failed(
|
||||
"failed to open encoder for recording".to_string(),
|
||||
));
|
||||
}
|
||||
let open_r = unsafe { crate::bridge::codec::oakcodec_encoder_open(enc) };
|
||||
if open_r != 0 {
|
||||
let mut buf = [0i8; 512];
|
||||
let n = unsafe {
|
||||
crate::bridge::codec::oakcodec_encoder_last_error(
|
||||
enc,
|
||||
buf.as_mut_ptr(),
|
||||
buf.len() as i32,
|
||||
)
|
||||
};
|
||||
let msg = if n > 0 {
|
||||
let s = buf.split(|c| *c == 0).next().unwrap_or(&[]);
|
||||
let bytes: Vec<u8> = s.iter().map(|&b| b as u8).collect();
|
||||
String::from_utf8_lossy(&bytes).into_owned()
|
||||
} else {
|
||||
"failed to open encoder for recording".to_string()
|
||||
};
|
||||
unsafe { crate::bridge::codec::oakcodec_encoder_free(&mut enc) };
|
||||
return Err(Error::Failed(msg));
|
||||
}
|
||||
m.recording = Some(enc);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stop recording.
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/src/audiomanager.cpp:328` (the PortAudio input
|
||||
/// stream is not bridged; the encoder is flushed and freed).
|
||||
pub fn stop_recording(self_: &CHandle) -> Result<()> {
|
||||
let mut m = with_instance(self_)?;
|
||||
if let Some(mut enc) = m.recording.take() {
|
||||
unsafe {
|
||||
crate::bridge::codec::oakcodec_encoder_flush(enc);
|
||||
crate::bridge::codec::oakcodec_encoder_free(&mut enc);
|
||||
if channels <= 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
let n = (channels as usize).min(peaks.len());
|
||||
for p in &mut peaks[..n] {
|
||||
*p = 0.0;
|
||||
}
|
||||
use crate::params::SampleFormat;
|
||||
let packed = params.format == SampleFormat::F32;
|
||||
let planar = params.format == SampleFormat::F32Planar;
|
||||
if !packed && !planar {
|
||||
return Ok(channels);
|
||||
}
|
||||
let frames_max = 8192i64;
|
||||
let bpf = channels as i64 * 4;
|
||||
let mut buf = vec![0u8; (bpf * frames_max) as usize];
|
||||
let got = self.output_buffer.peek_tail(&mut buf);
|
||||
// Whole frames only; the tail is what we hold, so leading partial
|
||||
// bytes (when the queue is not frame-aligned) are dropped.
|
||||
let frames = got / bpf;
|
||||
if frames == 0 {
|
||||
return Ok(channels);
|
||||
}
|
||||
let bytes = (frames * bpf) as usize;
|
||||
let buf = &buf[..bytes];
|
||||
let frame_count = frames as usize;
|
||||
let channel_count = channels as usize;
|
||||
let mut planes: Vec<Vec<f32>> = vec![Vec::with_capacity(frame_count); channel_count];
|
||||
if packed {
|
||||
for frame in buf.chunks_exact(bpf as usize) {
|
||||
for ch in 0..channel_count {
|
||||
let b = &frame[ch * 4..ch * 4 + 4];
|
||||
planes[ch].push(f32::from_le_bytes([b[0], b[1], b[2], b[3]]));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (ch, plane) in planes.iter_mut().enumerate() {
|
||||
let start = ch * frame_count * 4;
|
||||
for b in buf[start..start + frame_count * 4].chunks_exact(4) {
|
||||
plane.push(f32::from_le_bytes([b[0], b[1], b[2], b[3]]));
|
||||
}
|
||||
}
|
||||
}
|
||||
let views: Vec<&[f32]> = planes.iter().map(Vec::as_slice).collect();
|
||||
let stats = crate::levelmeter::analyze_sample_buffer(&views);
|
||||
for (i, p) in peaks[..n].iter_mut().enumerate() {
|
||||
*p = stats.channels[i].peak_linear as f32;
|
||||
}
|
||||
Ok(channels)
|
||||
}
|
||||
Ok(())
|
||||
|
||||
}
|
||||
|
||||
/// Lock the process-wide manager singleton (the direct-Rust replacement
|
||||
/// for the deleted C ABI's `oakaudio_manager_instance`): `None` when no
|
||||
/// instance exists (never created, or destroyed since the last
|
||||
/// [`ManagerInner::create_instance`]).
|
||||
pub fn instance() -> Option<MutexGuard<'static, ManagerInner>> {
|
||||
if DESTROYED.load(Ordering::SeqCst) {
|
||||
return None;
|
||||
}
|
||||
MANAGER
|
||||
.get()
|
||||
.map(|m| m.lock().unwrap_or_else(|e| e.into_inner()))
|
||||
}
|
||||
|
||||
/// Device index named by the configuration ("AudioOutput"/"AudioInput"), or
|
||||
@@ -380,9 +404,9 @@ pub fn stop_recording(self_: &CHandle) -> Result<()> {
|
||||
/// not initialized.
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/src/audiomanager.cpp:404`.
|
||||
pub fn find_config_device_by_name_s(is_output_device: bool) -> i32 {
|
||||
let name = crate::config::device_name(is_output_device);
|
||||
find_device_by_name_s(&name, is_output_device)
|
||||
pub fn find_config_device_by_name_s(is_output_device: bool) -> Result<Device> {
|
||||
let name = crate::config::device_name(is_output_device)?;
|
||||
find_device_by_name_s_or_default(&name, is_output_device)
|
||||
}
|
||||
|
||||
/// Device index whose name matches `name` exactly (empty matches nothing,
|
||||
@@ -391,82 +415,31 @@ pub fn find_config_device_by_name_s(is_output_device: bool) -> i32 {
|
||||
/// `// CPP-PARITY: src/audio/src/audiomanager.cpp:410` — PortAudio device
|
||||
/// enumeration cannot be bridged from this crate, so the result is always
|
||||
/// `paNoDevice` and the caller falls back to the default device.
|
||||
pub fn find_device_by_name_s(name: &std::ffi::CStr, _is_output_device: bool) -> i32 {
|
||||
let _ = name;
|
||||
PA_NO_DEVICE
|
||||
}
|
||||
|
||||
/// Peak level (linear, 0..1 and above) of each channel of the buffered,
|
||||
/// not-yet-consumed output, written to `peaks` in channel order.
|
||||
/// Returns the channel count (0 when no output is configured or the
|
||||
/// layout is unknown). Only packed/planar F32 buffers are analyzed —
|
||||
/// other formats report zeroed peaks. The analysis window is the most
|
||||
/// recent 8192 frames of the queue.
|
||||
///
|
||||
/// There is no C++ counterpart (the Qt side metered inside the audio
|
||||
/// output callback); with the output callback unbridged this is how the
|
||||
/// UI reads levels.
|
||||
pub fn output_levels(self_: &CHandle, peaks: &mut [f32]) -> Result<i32> {
|
||||
let m = with_instance(self_)?;
|
||||
let Some(params) = m.output_params else {
|
||||
return Ok(0);
|
||||
};
|
||||
let channels = params.channel_count();
|
||||
if channels <= 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
let n = (channels as usize).min(peaks.len());
|
||||
for p in &mut peaks[..n] {
|
||||
*p = 0.0;
|
||||
}
|
||||
use crate::params::SampleFormat;
|
||||
let packed = params.format == SampleFormat::F32;
|
||||
let planar = params.format == SampleFormat::F32Planar;
|
||||
if !packed && !planar {
|
||||
return Ok(channels);
|
||||
}
|
||||
let frames_max = 8192i64;
|
||||
let bpf = channels as i64 * 4;
|
||||
let mut buf = vec![0u8; (bpf * frames_max) as usize];
|
||||
let got = m.output_buffer.peek_tail(&mut buf);
|
||||
// Whole frames only; the tail is what we hold, so leading partial
|
||||
// bytes (when the queue is not frame-aligned) are dropped.
|
||||
let frames = got / bpf;
|
||||
if frames == 0 {
|
||||
return Ok(channels);
|
||||
}
|
||||
let bytes = (frames * bpf) as usize;
|
||||
let buf = &buf[..bytes];
|
||||
let frame_count = frames as usize;
|
||||
let channel_count = channels as usize;
|
||||
let mut planes: Vec<Vec<f32>> = vec![Vec::with_capacity(frame_count); channel_count];
|
||||
if packed {
|
||||
for frame in buf.chunks_exact(bpf as usize) {
|
||||
for ch in 0..channel_count {
|
||||
let b = &frame[ch * 4..ch * 4 + 4];
|
||||
planes[ch].push(f32::from_le_bytes([b[0], b[1], b[2], b[3]]));
|
||||
}
|
||||
pub fn find_device_by_name_s_or_default(name: &String, _is_output_device: bool) -> Result<Device> {
|
||||
let host = cpal::default_host();
|
||||
let device = host.devices()?.find(|d| {
|
||||
if d.id().is_err(){
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
for (ch, plane) in planes.iter_mut().enumerate() {
|
||||
let start = ch * frame_count * 4;
|
||||
for b in buf[start..start + frame_count * 4].chunks_exact(4) {
|
||||
plane.push(f32::from_le_bytes([b[0], b[1], b[2], b[3]]));
|
||||
}
|
||||
if d.supports_output() && d.id().unwrap().id() == name {
|
||||
return true;
|
||||
}
|
||||
false
|
||||
});
|
||||
if let Some(device) = device {
|
||||
Ok(device)
|
||||
}
|
||||
else{
|
||||
if let Some(device) = host.default_output_device() {
|
||||
Ok(device)
|
||||
}
|
||||
else{
|
||||
Err(Box::new(Error::NotFound))
|
||||
}
|
||||
}
|
||||
let views: Vec<&[f32]> = planes.iter().map(Vec::as_slice).collect();
|
||||
let stats = crate::levelmeter::analyze_sample_buffer(&views);
|
||||
for (i, p) in peaks[..n].iter_mut().enumerate() {
|
||||
*p = stats.channels[i].peak_linear as f32;
|
||||
}
|
||||
Ok(channels)
|
||||
|
||||
}
|
||||
|
||||
/// Number of live oakaudio reference-counted objects (leak check).
|
||||
pub fn debug_alive_count() -> i32 {
|
||||
crate::handle::alive_count()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -485,40 +458,9 @@ mod tests {
|
||||
// is_active=true while delivering zero callbacks.
|
||||
use std::sync::atomic::AtomicI64 as A;
|
||||
static PROBE: A = A::new(0);
|
||||
let can_play = (|| {
|
||||
let pa = portaudio::PortAudio::new().ok()?;
|
||||
let dev = pa.default_output_device().ok()?;
|
||||
let info = pa.device_info(dev).ok()?;
|
||||
let params = portaudio::StreamParameters::<f32>::new(
|
||||
dev,
|
||||
2,
|
||||
true,
|
||||
info.default_low_output_latency,
|
||||
);
|
||||
let settings = portaudio::OutputStreamSettings::new(params, 48000.0, 512);
|
||||
let cb = move |args: portaudio::OutputStreamCallbackArgs<f32>| {
|
||||
PROBE.fetch_add(args.frames as i64, Ordering::Relaxed);
|
||||
portaudio::Continue
|
||||
};
|
||||
let mut stream = pa.open_non_blocking_stream(settings, cb).ok()?;
|
||||
stream.start().ok()?;
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
|
||||
while std::time::Instant::now() < deadline && PROBE.load(Ordering::Relaxed) == 0 {
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
}
|
||||
let got = PROBE.load(Ordering::Relaxed) > 0;
|
||||
let _ = stream.stop();
|
||||
Some(got)
|
||||
})();
|
||||
if can_play != Some(true) {
|
||||
eprintln!("audio session cannot deliver callbacks; skipping");
|
||||
return;
|
||||
}
|
||||
|
||||
DESTROYED.store(false, Ordering::SeqCst);
|
||||
let _ = MANAGER.get_or_init(|| Mutex::new(ManagerInner::default()));
|
||||
let h = instance();
|
||||
assert!(!h.is_null());
|
||||
let manager = MANAGER.get_or_init(|| Mutex::new(ManagerInner::default()));
|
||||
|
||||
// A 440 Hz sine, 0.2 s at 48 kHz stereo, packed F32.
|
||||
let params = AudioParams {
|
||||
@@ -537,8 +479,7 @@ mod tests {
|
||||
.iter()
|
||||
.flat_map(|s| s.to_le_bytes())
|
||||
.collect();
|
||||
push_to_output(
|
||||
&h,
|
||||
manager.lock().unwrap().push_to_output(
|
||||
params,
|
||||
&bytes,
|
||||
&mut vec![0u8; 256],
|
||||
@@ -548,29 +489,24 @@ mod tests {
|
||||
// Give the audio thread time to consume. PortAudio/CoreAudio
|
||||
// stream startup can take SECONDS in some environments (audio HAL
|
||||
// device probing), so poll with a generous deadline instead of a
|
||||
// fixed sleep.
|
||||
// fixed sleep. The callback advances the clock for EVERY invocation
|
||||
// (underrun counts too), so the pushed frames drain within a couple
|
||||
// of hundred milliseconds of real audio time once the stream runs.
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
|
||||
let target = frames as i64 - 1024;
|
||||
let mut consumed = 0i64;
|
||||
while std::time::Instant::now() < deadline {
|
||||
{
|
||||
let m = with_instance(&h).unwrap();
|
||||
consumed = m.output_buffer.output_frames_consumed();
|
||||
}
|
||||
if consumed > 0 {
|
||||
consumed = manager.lock().unwrap().output_buffer.output_frames_consumed();
|
||||
if consumed >= target {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
}
|
||||
assert!(
|
||||
consumed > 0,
|
||||
"the output callback must consume pushed frames"
|
||||
);
|
||||
assert!(
|
||||
consumed >= frames as i64 - 1024,
|
||||
"most pushed frames are consumed: {consumed}"
|
||||
consumed >= target,
|
||||
"the output callback must consume the pushed frames (consumed {consumed} of {frames})"
|
||||
);
|
||||
|
||||
let mut m = with_instance(&h).unwrap();
|
||||
m.output_device_stream.close();
|
||||
manager.lock().unwrap().output_device_stream.close();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! M12 P1: the real audio output device (PortAudio, direct crate call).
|
||||
//! M12 P1: the real audio output device (cpal, direct crate call).
|
||||
//!
|
||||
//! The playback stream's callback pulls interleaved bytes from the
|
||||
//! shared [`PreviewAudioDevice`] and advances the output clock; underrun
|
||||
@@ -25,32 +25,38 @@
|
||||
//! device's mutex (a short critical section; the buffer is drained in
|
||||
//! whole frames).
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::sync::Arc;
|
||||
|
||||
use portaudio::{
|
||||
DeviceIndex, OutputStreamCallbackArgs, OutputStreamSettings, StreamParameters, Stream,
|
||||
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
|
||||
use cpal::{
|
||||
BufferSize, Device, Host, SampleFormat, SampleRate, Stream, StreamConfig,
|
||||
SupportedBufferSize,
|
||||
};
|
||||
|
||||
use crate::previewdevice::PreviewAudioDevice;
|
||||
|
||||
/// The default PortAudio frames-per-buffer for the preview stream.
|
||||
/// The default frames-per-buffer requested for the preview stream
|
||||
/// (clamped to the device's supported range).
|
||||
const FRAMES_PER_BUFFER: u32 = 512;
|
||||
|
||||
/// An open (or openable) PortAudio output stream.
|
||||
/// An open (or openable) cpal output stream.
|
||||
pub struct PortAudioOutput {
|
||||
/// PortAudio session (created lazily; `None` when unavailable).
|
||||
pa: Option<portaudio::PortAudio>,
|
||||
/// Audio host/session (created lazily; `None` when unavailable).
|
||||
host: Option<Host>,
|
||||
/// The live stream (None when closed).
|
||||
stream: Option<Stream<portaudio::NonBlocking, portaudio::Output<f32>>>,
|
||||
stream: Option<Stream>,
|
||||
/// The (device, rate, channels) the stream was opened with.
|
||||
opened: Option<(i32, i32, i32)>,
|
||||
}
|
||||
|
||||
/// Backwards-compatible name for [`PortAudioOutput`].
|
||||
pub type AudioOutput = PortAudioOutput;
|
||||
|
||||
impl PortAudioOutput {
|
||||
/// Create the device (PortAudio initialized lazily on first use).
|
||||
/// Create the device (the host is created lazily on first use).
|
||||
pub fn new() -> PortAudioOutput {
|
||||
PortAudioOutput {
|
||||
pa: None,
|
||||
host: Some(cpal::default_host()),
|
||||
stream: None,
|
||||
opened: None,
|
||||
}
|
||||
@@ -61,16 +67,17 @@ impl PortAudioOutput {
|
||||
self.stream.is_some()
|
||||
}
|
||||
|
||||
/// Close the stream (stop + drop).
|
||||
/// Close the stream (pause + drop).
|
||||
pub fn close(&mut self) {
|
||||
if let Some(mut s) = self.stream.take() {
|
||||
let _ = s.stop();
|
||||
if let Some(stream) = self.stream.take() {
|
||||
let _ = stream.pause();
|
||||
}
|
||||
self.opened = None;
|
||||
}
|
||||
|
||||
/// Ensure an output stream is open for `(device, rate, channels)` and
|
||||
/// pulling from `sink`. `device` < 0 selects the system default.
|
||||
/// pulling from `sink`. `device` < 0 selects the system default output;
|
||||
/// any other value is an index into the host's output device list.
|
||||
/// Failures leave the output silent (samples still buffer).
|
||||
pub fn ensure_open(
|
||||
&mut self,
|
||||
@@ -87,70 +94,117 @@ impl PortAudioOutput {
|
||||
}
|
||||
self.close();
|
||||
|
||||
let pa = match &self.pa {
|
||||
Some(pa) => pa.clone(),
|
||||
None => {
|
||||
let pa = portaudio::PortAudio::new()
|
||||
.map_err(|e| format!("PortAudio init failed: {e:?}"))?;
|
||||
self.pa = Some(pa);
|
||||
match self.pa.as_ref() {
|
||||
Some(pa) => pa.clone(),
|
||||
None => unreachable!("just assigned"),
|
||||
}
|
||||
}
|
||||
};
|
||||
if self.host.is_none(){
|
||||
self.host = Some(cpal::default_host())
|
||||
}
|
||||
|
||||
let dev = if device >= 0 {
|
||||
DeviceIndex(device as u32)
|
||||
} else {
|
||||
pa.default_output_device()
|
||||
.map_err(|e| format!("no default output device: {e:?}"))?
|
||||
};
|
||||
let info = pa
|
||||
.device_info(dev)
|
||||
.map_err(|e| format!("device info failed: {e:?}"))?;
|
||||
let latency = info.default_low_output_latency;
|
||||
let params = StreamParameters::<f32>::new(dev, channels, true, latency);
|
||||
let settings = OutputStreamSettings::<f32>::new(params, rate as f64, FRAMES_PER_BUFFER);
|
||||
let host = self.host.as_ref().unwrap().clone();
|
||||
|
||||
let output_device = resolve_device(&host, device)
|
||||
.ok_or_else(|| "no output device available".to_string())?;
|
||||
let config = pick_config(&output_device, rate, channels)?;
|
||||
|
||||
// The callback pulls whole frames from the shared device and
|
||||
// advances the output clock (underrun → silence). `read` locks
|
||||
// the device internally; no other locks are taken on the audio
|
||||
// thread. The scratch buffer is allocated once and reused —
|
||||
// allocating per callback would violate the real-time rule.
|
||||
let channels_usize = channels.max(1) as usize;
|
||||
let sink_cb = sink.clone();
|
||||
let scratch = std::cell::RefCell::new(Vec::<u8>::new());
|
||||
let callback = move |args: OutputStreamCallbackArgs<f32>| {
|
||||
let out = args.buffer;
|
||||
let frames = args.frames;
|
||||
let total = frames * channels.max(1) as usize;
|
||||
let scratch = RefCell::new(Vec::<u8>::new());
|
||||
let callback = move |out: &mut [f32], _info: &cpal::OutputCallbackInfo| {
|
||||
let total = out.len();
|
||||
let mut scratch = scratch.borrow_mut();
|
||||
scratch.resize(total * 4, 0);
|
||||
let byte_buf = &mut *scratch;
|
||||
let got = sink_cb.read(byte_buf);
|
||||
let frames_got = (got as usize) / (channels.max(1) as usize * 4);
|
||||
// Convert the interleaved f32 bytes in place to a sample
|
||||
// slice (PortAudio writes f32s directly).
|
||||
let n_samples = frames_got * channels.max(1) as usize;
|
||||
for i in 0..n_samples {
|
||||
let b = &byte_buf[i * 4..i * 4 + 4];
|
||||
out[i] = f32::from_le_bytes([b[0], b[1], b[2], b[3]]);
|
||||
let got = sink_cb.read(scratch.as_mut_slice());
|
||||
let frames_got = (got as usize) / (channels_usize * 4);
|
||||
// Convert the interleaved f32 bytes in place to the sample
|
||||
// slice (cpal hands us f32s directly); zero-fill the underrun
|
||||
// remainder with silence.
|
||||
let n_samples = frames_got * channels_usize;
|
||||
for (i, s) in out.iter_mut().enumerate() {
|
||||
if i < n_samples {
|
||||
let b = &scratch[i * 4..i * 4 + 4];
|
||||
*s = f32::from_le_bytes([b[0], b[1], b[2], b[3]]);
|
||||
} else {
|
||||
*s = 0.0;
|
||||
}
|
||||
}
|
||||
for s in out.iter_mut().skip(n_samples) {
|
||||
*s = 0.0; // underrun: silence
|
||||
}
|
||||
sink_cb.add_output_frames(frames as i64);
|
||||
portaudio::Continue
|
||||
sink_cb.add_output_frames((total / channels_usize) as i64);
|
||||
};
|
||||
let err_callback = |err: cpal::Error| {
|
||||
eprintln!("output stream error: {err}");
|
||||
};
|
||||
|
||||
let mut stream = pa
|
||||
.open_non_blocking_stream(settings, callback)
|
||||
.map_err(|e| format!("output stream open failed: {e:?}"))?;
|
||||
let stream = output_device
|
||||
.build_output_stream(config, callback, err_callback, None)
|
||||
.map_err(|e| format!("output stream open failed: {e}"))?;
|
||||
stream
|
||||
.start()
|
||||
.map_err(|e| format!("output stream start failed: {e:?}"))?;
|
||||
.play()
|
||||
.map_err(|e| format!("output stream start failed: {e}"))?;
|
||||
self.stream = Some(stream);
|
||||
self.opened = Some((device, rate, channels));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for PortAudioOutput {
|
||||
fn default() -> Self {
|
||||
PortAudioOutput::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve a PortAudio-style device index to a cpal device: an index >= 0
|
||||
/// picks the Nth output device of the host; anything else (notably -1,
|
||||
/// `paNoDevice`) falls back to the host's default output device.
|
||||
fn resolve_device(host: &Host, index: i32) -> Option<Device> {
|
||||
if index >= 0 {
|
||||
if let Ok(mut devices) = host.output_devices() {
|
||||
if let Some(device) = devices.nth(index as usize) {
|
||||
return Some(device);
|
||||
}
|
||||
}
|
||||
}
|
||||
host.default_output_device()
|
||||
}
|
||||
|
||||
/// Pick an F32 stream config for `(rate, channels)`. The callback always
|
||||
/// interprets the buffer as interleaved f32 with the requested channel
|
||||
/// count, so a config with another format or channel count is never used;
|
||||
/// the sample rate is clamped into the device's supported range. The
|
||||
/// requested buffer size is honored when it lies inside the supported
|
||||
/// range.
|
||||
fn pick_config(device: &Device, rate: i32, channels: i32) -> Result<StreamConfig, String> {
|
||||
let want_rate = rate as u32;
|
||||
let want_channels = channels as u16;
|
||||
|
||||
if let Ok(mut configs) = device.supported_output_configs() {
|
||||
while let Some(c) = configs.next() {
|
||||
if c.sample_format() != SampleFormat::F32 || c.channels() != want_channels {
|
||||
continue;
|
||||
}
|
||||
let rate = want_rate.clamp(c.min_sample_rate(), c.max_sample_rate());
|
||||
let buffer_size = match c.buffer_size() {
|
||||
SupportedBufferSize::Range { min, max } => {
|
||||
BufferSize::Fixed(FRAMES_PER_BUFFER.clamp(*min, *max))
|
||||
}
|
||||
SupportedBufferSize::Unknown => BufferSize::Default,
|
||||
};
|
||||
return Ok(StreamConfig {
|
||||
channels: want_channels,
|
||||
sample_rate: rate,
|
||||
buffer_size,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let fallback = device
|
||||
.default_output_config()
|
||||
.map_err(|e| format!("output device config unavailable: {e}"))?;
|
||||
if fallback.sample_format() != SampleFormat::F32 || fallback.channels() != want_channels {
|
||||
return Err(format!(
|
||||
"output device supports no F32/{want_channels}-channel stream"
|
||||
));
|
||||
}
|
||||
Ok(fallback.config())
|
||||
}
|
||||
|
||||
+208
-222
@@ -32,11 +32,10 @@ use ffmpeg::{ChannelLayout, Error as FfmpegError};
|
||||
use ffmpeg_next as ffmpeg;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::handle::{free_handle, make_owned, CHandle};
|
||||
use crate::params::{AudioParams, SampleFormat};
|
||||
|
||||
/// A closed audio processor (reference count 1; `ctx == NULL` on allocation
|
||||
/// failure).
|
||||
/// An audio processor; created closed, configured with
|
||||
/// [`open`](Processor::open).
|
||||
pub struct Processor {
|
||||
inner: Mutex<ProcessorInner>,
|
||||
}
|
||||
@@ -54,8 +53,8 @@ struct ProcessorInner {
|
||||
}
|
||||
|
||||
// SAFETY: the filter graph's raw pointers are only dereferenced through the
|
||||
// FFmpeg API while the mutex is held, so all access is serialized; the
|
||||
// handle's refcount keeps the box alive.
|
||||
// FFmpeg API while the processor's mutex is held, so all access is
|
||||
// serialized.
|
||||
unsafe impl Send for ProcessorInner {}
|
||||
|
||||
impl Default for ProcessorInner {
|
||||
@@ -136,7 +135,7 @@ fn fix_channel_layout(params: AudioParams) -> AudioParams {
|
||||
fn build_graph(from: &AudioParams, to: &AudioParams, speed: f64) -> Result<ffmpeg::filter::Graph> {
|
||||
let in_format = to_ffmpeg_sample_format(from.format);
|
||||
if in_format == Sample::None {
|
||||
return Err(Error::Failed("invalid input sample format".to_string()));
|
||||
return Err(Box::new(Error::Failed("invalid input sample format".to_string())));
|
||||
}
|
||||
|
||||
let abuffer = ffmpeg::filter::find("abuffer")
|
||||
@@ -196,236 +195,223 @@ fn is_drain(e: &FfmpegError) -> bool {
|
||||
|| matches!(e, FfmpegError::Other { errno } if *errno == ffmpeg::error::EAGAIN)
|
||||
}
|
||||
|
||||
/// Borrow the processor state behind a handle.
|
||||
fn get_processor(self_: &CHandle) -> Result<&Processor> {
|
||||
// SAFETY: every non-empty handle returned by `init` boxes a `Processor`.
|
||||
unsafe { crate::handle::get::<Processor>(self_) }.ok_or(Error::Invalid)
|
||||
}
|
||||
|
||||
/// Create a closed processor.
|
||||
pub fn init() -> Result<CHandle> {
|
||||
Ok(make_owned(Processor {
|
||||
inner: Mutex::new(ProcessorInner::default()),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Release one reference to a processor (NULL/empty no-op).
|
||||
pub fn free(self_: *mut CHandle) {
|
||||
unsafe { free_handle(self_) };
|
||||
}
|
||||
|
||||
/// Open the resampling/format-conversion graph. `out_format` is accepted for
|
||||
/// interface completeness but the conversion output is always planar f32.
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/c_api/processor.cpp:43` (validation order:
|
||||
/// empty handle, already-open state, invalid rates/speed, forced output
|
||||
/// format) and `src/audio/src/audioprocessor.cpp:82` (graph creation).
|
||||
pub fn open(self_: &CHandle, from: AudioParams, to: AudioParams, speed: f64) -> Result<()> {
|
||||
let p = get_processor(self_)?;
|
||||
let mut inner = p.inner.lock().unwrap();
|
||||
|
||||
if inner.graph.is_some() {
|
||||
// C++: "tried to open a processor that was already open"
|
||||
return Err(Error::State);
|
||||
}
|
||||
if from.sample_rate <= 0 || to.sample_rate <= 0 || speed <= 0.0 {
|
||||
return Err(Error::Invalid);
|
||||
}
|
||||
// The C ABI delivers planar float output only; force the output format
|
||||
// stage to f32p (OAKAUDIO_PROCESSOR_OUTPUT_FORMAT == 4).
|
||||
if to.format != SampleFormat::F32Planar {
|
||||
return Err(Error::Invalid);
|
||||
}
|
||||
|
||||
let from_fixed = fix_channel_layout(from);
|
||||
let to_fixed = fix_channel_layout(to);
|
||||
|
||||
// C++: "failed to create audio filter graph"
|
||||
let graph = build_graph(&from_fixed, &to_fixed, speed)?;
|
||||
|
||||
inner.graph = Some(graph);
|
||||
inner.out_frame = ffmpeg::frame::Audio::empty();
|
||||
inner.from = from_fixed;
|
||||
inner.to = to_fixed;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Close the graph (safe when closed; handle must be non-empty).
|
||||
pub fn close(self_: &CHandle) -> Result<()> {
|
||||
let p = get_processor(self_)?;
|
||||
let mut inner = p.inner.lock().unwrap();
|
||||
|
||||
inner.graph = None;
|
||||
inner.out_frame = ffmpeg::frame::Audio::empty();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 1 when open, 0 when closed; error for an empty handle.
|
||||
pub fn is_open(self_: &CHandle) -> Result<bool> {
|
||||
let p = get_processor(self_)?;
|
||||
let inner = p.inner.lock().unwrap();
|
||||
Ok(inner.graph.is_some())
|
||||
}
|
||||
|
||||
/// Push planar float input and pull converted output. Returns the number of
|
||||
/// output frames written.
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/c_api/processor.cpp:91` (validation, state
|
||||
/// check, null `out_planar` short-circuit) and
|
||||
/// `src/audio/src/audioprocessor.cpp:141` (push/pull loop, byte counting).
|
||||
pub fn convert(
|
||||
self_: &CHandle,
|
||||
in_planar: *const *const f32,
|
||||
in_frame_count: i32,
|
||||
out_planar: *const *mut f32,
|
||||
out_capacity_frames: i32,
|
||||
) -> Result<i32> {
|
||||
let p = get_processor(self_)?;
|
||||
let mut guard = p.inner.lock().unwrap();
|
||||
let inner = &mut *guard;
|
||||
|
||||
if inner.graph.is_none() {
|
||||
return Err(Error::State);
|
||||
}
|
||||
if in_frame_count < 0 || out_capacity_frames < 0 || (in_frame_count > 0 && in_planar.is_null())
|
||||
{
|
||||
return Err(Error::Invalid);
|
||||
}
|
||||
|
||||
let channels = inner.to.channel_count();
|
||||
if channels <= 0 {
|
||||
return Err(Error::State);
|
||||
}
|
||||
|
||||
let from = inner.from;
|
||||
let graph = inner.graph.as_mut().unwrap();
|
||||
let out_frame = &mut inner.out_frame;
|
||||
|
||||
if in_frame_count > 0 {
|
||||
// The FFI layer has no way to know the input plane count, so the
|
||||
// plane pointer array is walked using the input spec recorded at
|
||||
// `open` (`// CPP-PARITY: src/audio/src/audioprocessor.cpp:141`).
|
||||
let nb = in_frame_count as usize;
|
||||
let in_channels = from.channel_count().max(0) as usize;
|
||||
let layout = channel_layout_from_mask(from.channel_layout);
|
||||
let mut frame = ffmpeg::frame::Audio::new(to_ffmpeg_sample_format(from.format), nb, layout);
|
||||
frame.set_rate(from.sample_rate as u32);
|
||||
let planar = from.format.is_planar();
|
||||
// `plane_mut::<T>` requires the exact sample type of the frame
|
||||
// format, so the copy dispatches on the recorded input format.
|
||||
macro_rules! fill {
|
||||
($t:ty) => {{
|
||||
if planar {
|
||||
for ch in 0..in_channels {
|
||||
// SAFETY: `in_planar` is non-null here and the FFI
|
||||
// contract guarantees at least `from.channel_count()`
|
||||
// entries, each pointing at `nb` samples of the
|
||||
// recorded input format.
|
||||
let src = unsafe { *in_planar.add(ch) } as *const $t;
|
||||
let dst = frame.plane_mut::<$t>(ch);
|
||||
unsafe { ptr::copy_nonoverlapping(src, dst.as_mut_ptr(), nb) };
|
||||
}
|
||||
} else {
|
||||
// Packed input: a single plane at `in_planar[0]`.
|
||||
// SAFETY: see above; the plane holds `nb * channels`
|
||||
// samples.
|
||||
let src = unsafe { *in_planar } as *const $t;
|
||||
let dst = frame.plane_mut::<$t>(0);
|
||||
unsafe { ptr::copy_nonoverlapping(src, dst.as_mut_ptr(), nb * in_channels) };
|
||||
}
|
||||
}};
|
||||
impl Processor {
|
||||
/// Create a closed processor.
|
||||
pub fn init() -> Processor {
|
||||
Processor {
|
||||
inner: Mutex::new(ProcessorInner::default()),
|
||||
}
|
||||
match from.format {
|
||||
SampleFormat::U8Planar | SampleFormat::U8 => fill!(u8),
|
||||
SampleFormat::S16Planar | SampleFormat::S16 => fill!(i16),
|
||||
SampleFormat::S32Planar | SampleFormat::S32 => fill!(i32),
|
||||
SampleFormat::S64Planar | SampleFormat::S64 => {
|
||||
// ffmpeg-next's typed plane API has no `i64` impl; copy the
|
||||
// 8-byte samples through the raw plane pointers.
|
||||
if planar {
|
||||
for ch in 0..in_channels {
|
||||
}
|
||||
|
||||
/// Open the resampling/format-conversion graph. `out_format` is accepted
|
||||
/// for interface completeness but the conversion output is always planar
|
||||
/// f32.
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/c_api/processor.cpp:43` (validation order:
|
||||
/// already-open state, invalid rates/speed, forced output format) and
|
||||
/// `src/audio/src/audioprocessor.cpp:82` (graph creation).
|
||||
pub fn open(&self, from: AudioParams, to: AudioParams, speed: f64) -> Result<()> {
|
||||
let mut inner = self.inner.lock().unwrap();
|
||||
|
||||
if inner.graph.is_some() {
|
||||
// C++: "tried to open a processor that was already open"
|
||||
return Err(Box::from(Error::State));
|
||||
}
|
||||
if from.sample_rate <= 0 || to.sample_rate <= 0 || speed <= 0.0 {
|
||||
return Err(Box::from(Error::Invalid));
|
||||
}
|
||||
// The C ABI delivers planar float output only; force the output format
|
||||
// stage to f32p (OAKAUDIO_PROCESSOR_OUTPUT_FORMAT == 4).
|
||||
if to.format != SampleFormat::F32Planar {
|
||||
return Err(Box::from(Error::Invalid));
|
||||
}
|
||||
|
||||
let from_fixed = fix_channel_layout(from);
|
||||
let to_fixed = fix_channel_layout(to);
|
||||
|
||||
// C++: "failed to create audio filter graph"
|
||||
let graph = build_graph(&from_fixed, &to_fixed, speed)?;
|
||||
|
||||
inner.graph = Some(graph);
|
||||
inner.out_frame = ffmpeg::frame::Audio::empty();
|
||||
inner.from = from_fixed;
|
||||
inner.to = to_fixed;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Close the graph (safe when closed).
|
||||
pub fn close(&self) -> Result<()> {
|
||||
let mut inner = self.inner.lock().unwrap();
|
||||
|
||||
inner.graph = None;
|
||||
inner.out_frame = ffmpeg::frame::Audio::empty();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 1 when open, 0 when closed.
|
||||
pub fn is_open(&self) -> Result<bool> {
|
||||
let inner = self.inner.lock().unwrap();
|
||||
Ok(inner.graph.is_some())
|
||||
}
|
||||
|
||||
/// Push planar float input and pull converted output. Returns the number
|
||||
/// of output frames written.
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/c_api/processor.cpp:91` (validation, state
|
||||
/// check, null `out_planar` short-circuit) and
|
||||
/// `src/audio/src/audioprocessor.cpp:141` (push/pull loop, byte counting).
|
||||
pub fn convert(
|
||||
&self,
|
||||
in_planar: *const *const f32,
|
||||
in_frame_count: i32,
|
||||
out_planar: *const *mut f32,
|
||||
out_capacity_frames: i32,
|
||||
) -> Result<i32> {
|
||||
let mut guard = self.inner.lock().unwrap();
|
||||
let inner = &mut *guard;
|
||||
|
||||
if inner.graph.is_none() {
|
||||
return Err(Box::from(Error::State));
|
||||
}
|
||||
if in_frame_count < 0 || out_capacity_frames < 0 || (in_frame_count > 0 && in_planar.is_null())
|
||||
{
|
||||
return Err(Box::from(Error::Invalid));
|
||||
}
|
||||
|
||||
let channels = inner.to.channel_count();
|
||||
if channels <= 0 {
|
||||
return Err(Box::from(Error::State));
|
||||
}
|
||||
|
||||
let from = inner.from;
|
||||
let graph = inner.graph.as_mut().unwrap();
|
||||
let out_frame = &mut inner.out_frame;
|
||||
|
||||
if in_frame_count > 0 {
|
||||
// The FFI layer has no way to know the input plane count, so the
|
||||
// plane pointer array is walked using the input spec recorded at
|
||||
// `open` (`// CPP-PARITY: src/audio/src/audioprocessor.cpp:141`).
|
||||
let nb = in_frame_count as usize;
|
||||
let in_channels = from.channel_count().max(0) as usize;
|
||||
let layout = channel_layout_from_mask(from.channel_layout);
|
||||
let mut frame = ffmpeg::frame::Audio::new(to_ffmpeg_sample_format(from.format), nb, layout);
|
||||
frame.set_rate(from.sample_rate as u32);
|
||||
let planar = from.format.is_planar();
|
||||
// `plane_mut::<T>` requires the exact sample type of the frame
|
||||
// format, so the copy dispatches on the recorded input format.
|
||||
macro_rules! fill {
|
||||
($t:ty) => {{
|
||||
if planar {
|
||||
for ch in 0..in_channels {
|
||||
// SAFETY: `in_planar` is non-null here and the FFI
|
||||
// contract guarantees at least `from.channel_count()`
|
||||
// entries, each pointing at `nb` samples of the
|
||||
// recorded input format.
|
||||
let src = unsafe { *in_planar.add(ch) } as *const $t;
|
||||
let dst = frame.plane_mut::<$t>(ch);
|
||||
unsafe { ptr::copy_nonoverlapping(src, dst.as_mut_ptr(), nb) };
|
||||
}
|
||||
} else {
|
||||
// Packed input: a single plane at `in_planar[0]`.
|
||||
// SAFETY: see above; the plane holds `nb * channels`
|
||||
// samples.
|
||||
let src = unsafe { *in_planar } as *const $t;
|
||||
let dst = frame.plane_mut::<$t>(0);
|
||||
unsafe { ptr::copy_nonoverlapping(src, dst.as_mut_ptr(), nb * in_channels) };
|
||||
}
|
||||
}};
|
||||
}
|
||||
match from.format {
|
||||
SampleFormat::U8Planar | SampleFormat::U8 => fill!(u8),
|
||||
SampleFormat::S16Planar | SampleFormat::S16 => fill!(i16),
|
||||
SampleFormat::S32Planar | SampleFormat::S32 => fill!(i32),
|
||||
SampleFormat::S64Planar | SampleFormat::S64 => {
|
||||
// ffmpeg-next's typed plane API has no `i64` impl; copy the
|
||||
// 8-byte samples through the raw plane pointers.
|
||||
if planar {
|
||||
for ch in 0..in_channels {
|
||||
// SAFETY: same contract as above; the plane is
|
||||
// `nb * 8` bytes.
|
||||
let src = unsafe { *in_planar.add(ch) } as *const u8;
|
||||
let dst = unsafe { *(*frame.as_mut_ptr()).extended_data.add(ch) };
|
||||
unsafe { ptr::copy_nonoverlapping(src, dst, nb * 8) };
|
||||
}
|
||||
} else {
|
||||
// SAFETY: same contract as above; the plane is
|
||||
// `nb * 8` bytes.
|
||||
let src = unsafe { *in_planar.add(ch) } as *const u8;
|
||||
let dst = unsafe { *(*frame.as_mut_ptr()).extended_data.add(ch) };
|
||||
unsafe { ptr::copy_nonoverlapping(src, dst, nb * 8) };
|
||||
// `nb * channels * 8` bytes.
|
||||
let src = unsafe { *in_planar } as *const u8;
|
||||
let dst = unsafe { *(*frame.as_mut_ptr()).extended_data };
|
||||
unsafe { ptr::copy_nonoverlapping(src, dst, nb * in_channels * 8) };
|
||||
}
|
||||
} else {
|
||||
// SAFETY: same contract as above; the plane is
|
||||
// `nb * channels * 8` bytes.
|
||||
let src = unsafe { *in_planar } as *const u8;
|
||||
let dst = unsafe { *(*frame.as_mut_ptr()).extended_data };
|
||||
unsafe { ptr::copy_nonoverlapping(src, dst, nb * in_channels * 8) };
|
||||
}
|
||||
SampleFormat::F32Planar | SampleFormat::F32 => fill!(f32),
|
||||
SampleFormat::F64Planar | SampleFormat::F64 => fill!(f64),
|
||||
SampleFormat::Invalid => return Err(Box::new(Error::State)),
|
||||
}
|
||||
SampleFormat::F32Planar | SampleFormat::F32 => fill!(f32),
|
||||
SampleFormat::F64Planar | SampleFormat::F64 => fill!(f64),
|
||||
SampleFormat::Invalid => return Err(Error::State),
|
||||
}
|
||||
if let Err(e) = graph.get("in").unwrap().source().add(&frame) {
|
||||
return Err(Error::Failed(format!(
|
||||
"failed to add frame to buffersrc: {e}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
// C++: `out_planar ? &buf : nullptr` — with no destination, the input is
|
||||
// pushed but nothing is pulled.
|
||||
if out_planar.is_null() {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let mut total: i64 = 0;
|
||||
loop {
|
||||
let pulled = graph.get("out").unwrap().sink().frame(out_frame);
|
||||
match pulled {
|
||||
Ok(()) => {}
|
||||
Err(e) if is_drain(&e) => break,
|
||||
Err(e) => {
|
||||
return Err(Error::Failed(format!(
|
||||
"failed to pull from buffersink: {e}"
|
||||
)))
|
||||
if let Err(e) = graph.get("in").unwrap().source().add(&frame) {
|
||||
return Err(Box::new(Error::Failed(format!(
|
||||
"failed to add frame to buffersrc: {e}"
|
||||
))));
|
||||
}
|
||||
}
|
||||
|
||||
let nb = out_frame.samples() as i32;
|
||||
if nb > 0 && total < i64::from(out_capacity_frames) {
|
||||
let to_copy = (i64::from(out_capacity_frames) - total).min(i64::from(nb)) as i32;
|
||||
for ch in 0..channels {
|
||||
// SAFETY: the FFI contract guarantees at least `channels`
|
||||
// entries in `out_planar` (NULL entries are skipped).
|
||||
let dst = unsafe { *out_planar.add(ch as usize) };
|
||||
if dst.is_null() {
|
||||
continue;
|
||||
}
|
||||
// Output is planar f32 (enforced by open()); each plane is
|
||||
// `to_copy` float samples.
|
||||
let src = out_frame.plane::<f32>(ch as usize);
|
||||
unsafe {
|
||||
ptr::copy_nonoverlapping(src.as_ptr(), dst, to_copy as usize);
|
||||
// C++: `out_planar ? &buf : nullptr` — with no destination, the input is
|
||||
// pushed but nothing is pulled.
|
||||
if out_planar.is_null() {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let mut total: i64 = 0;
|
||||
loop {
|
||||
let pulled = graph.get("out").unwrap().sink().frame(out_frame);
|
||||
match pulled {
|
||||
Ok(()) => {}
|
||||
Err(e) if is_drain(&e) => break,
|
||||
Err(e) => {
|
||||
return Err(Box::from(Error::Failed(format!(
|
||||
"failed to pull from buffersink: {e}"
|
||||
))))
|
||||
}
|
||||
}
|
||||
|
||||
let nb = out_frame.samples() as i32;
|
||||
if nb > 0 && total < i64::from(out_capacity_frames) {
|
||||
let to_copy = (i64::from(out_capacity_frames) - total).min(i64::from(nb)) as i32;
|
||||
for ch in 0..channels {
|
||||
// SAFETY: the FFI contract guarantees at least `channels`
|
||||
// entries in `out_planar` (NULL entries are skipped).
|
||||
let dst = unsafe { *out_planar.add(ch as usize) };
|
||||
if dst.is_null() {
|
||||
continue;
|
||||
}
|
||||
// Output is planar f32 (enforced by open()); each plane is
|
||||
// `to_copy` float samples.
|
||||
let src = out_frame.plane::<f32>(ch as usize);
|
||||
unsafe {
|
||||
ptr::copy_nonoverlapping(src.as_ptr(), dst, to_copy as usize);
|
||||
}
|
||||
}
|
||||
}
|
||||
total += i64::from(nb);
|
||||
}
|
||||
total += i64::from(nb);
|
||||
|
||||
Ok(total.min(i64::from(out_capacity_frames)) as i32)
|
||||
}
|
||||
|
||||
Ok(total.min(i64::from(out_capacity_frames)) as i32)
|
||||
}
|
||||
/// Signal end-of-input to the graph (flushes internal delay).
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/c_api/processor.cpp:137` (state check)
|
||||
/// and `src/audio/src/audioprocessor.cpp:210` (flush has no failure path; a
|
||||
/// negative push return is logged only).
|
||||
pub fn flush(&self) -> Result<()> {
|
||||
let mut inner = self.inner.lock().unwrap();
|
||||
|
||||
/// Signal end-of-input to the graph (flushes internal delay).
|
||||
///
|
||||
/// `// CPP-PARITY: src/audio/c_api/processor.cpp:137` (empty handle, state)
|
||||
/// and `src/audio/src/audioprocessor.cpp:210` (flush has no failure path; a
|
||||
/// negative push return is logged only).
|
||||
pub fn flush(self_: &CHandle) -> Result<()> {
|
||||
let p = get_processor(self_)?;
|
||||
let mut inner = p.inner.lock().unwrap();
|
||||
|
||||
let Some(graph) = inner.graph.as_mut() else {
|
||||
return Err(Error::State);
|
||||
};
|
||||
let _ = graph.get("in").unwrap().source().flush();
|
||||
Ok(())
|
||||
let Some(graph) = inner.graph.as_mut() else {
|
||||
return Err(Box::from(Error::State));
|
||||
};
|
||||
let _ = graph.get("in").unwrap().source().flush();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Format of the conversion output (always planar f32).
|
||||
|
||||
@@ -23,13 +23,12 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::ffi::CStr;
|
||||
|
||||
use oakcodec::decoder::{CodecStream, Decoder as _, RetrieveAudioStatus};
|
||||
use oakcodec::decoder::{receive_list_of_all_decoders, CodecStream, Decoder as _, RetrieveAudioStatus};
|
||||
use oakcodec::ffmpeg::FFmpegDecoder;
|
||||
use oakcodec::footagedescription::FootageDescription;
|
||||
use oakcore_rs::{Rational, TimeRange};
|
||||
|
||||
use crate::bridge::codec::AudioStreamInfo;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::handle::{free_handle, make_owned, CHandle};
|
||||
|
||||
/// Maximum channel count accepted by [`extract`]. The C++ plane array is a
|
||||
/// fixed `OAKAUDIO_EXTRACT_MAX_CHANNELS` (64) stack buffer; the Rust
|
||||
@@ -625,32 +624,6 @@ impl RecipOrZero for f64 {
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Handle plumbing (mirrors processor.rs) --------------------------------
|
||||
|
||||
/// Create an empty waveform behind a refcounted handle (count 1).
|
||||
pub fn init() -> Result<CHandle> {
|
||||
Ok(make_owned(AudioVisualWaveform::new()))
|
||||
}
|
||||
|
||||
/// Release one reference to a waveform (NULL/empty no-op).
|
||||
pub fn free(self_: *mut CHandle) {
|
||||
unsafe { free_handle(self_) };
|
||||
}
|
||||
|
||||
/// Borrow the waveform behind a handle; `OAKAUDIO_E_INVALID` for empty.
|
||||
pub fn get(self_: &CHandle) -> Result<&AudioVisualWaveform> {
|
||||
// SAFETY: every non-empty handle returned by `init` boxes an
|
||||
// `AudioVisualWaveform`.
|
||||
unsafe { crate::handle::get::<AudioVisualWaveform>(self_) }.ok_or(Error::Invalid)
|
||||
}
|
||||
|
||||
/// Mutable variant of [`get`].
|
||||
pub fn get_mut(self_: &CHandle) -> Result<&mut AudioVisualWaveform> {
|
||||
// SAFETY: every non-empty handle returned by `init` boxes an
|
||||
// `AudioVisualWaveform`.
|
||||
unsafe { crate::handle::get_mut::<AudioVisualWaveform>(self_) }.ok_or(Error::Invalid)
|
||||
}
|
||||
|
||||
// ---- Whole-file extraction --------------------------------------------------
|
||||
|
||||
/// Result of [`extract`]: channel-interleaved min/max pairs.
|
||||
@@ -714,10 +687,34 @@ fn emit_points(
|
||||
}
|
||||
}
|
||||
|
||||
/// Probe a file with every registered decoder and return the first valid
|
||||
/// description (non-empty decoder id and at least one stream).
|
||||
///
|
||||
/// Replaces the former `oakcodec_decoder_probe` C ABI call (mirrors
|
||||
/// `probe_with_any_decoder` in oakcodec's ffi layer).
|
||||
fn probe_description(filename: &str) -> Option<FootageDescription> {
|
||||
for decoder in receive_list_of_all_decoders() {
|
||||
// `continue`, not `?`: an unimplemented/unsupported decoder must
|
||||
// fall through to the next one (the FFmpeg entry is the
|
||||
// format-agnostic fallback last in the registry).
|
||||
let Some(desc) = decoder.probe(filename, None) else {
|
||||
continue;
|
||||
};
|
||||
if !desc.decoder().is_empty()
|
||||
&& (desc.video_stream_count() > 0
|
||||
|| desc.audio_stream_count() > 0
|
||||
|| desc.subtitle_stream_count() > 0)
|
||||
{
|
||||
return Some(desc);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Decode a whole audio stream to a channel-interleaved min/max summary.
|
||||
///
|
||||
/// The stream is probed through the oakcodec decoder C ABI and decoded with
|
||||
/// oakcodec's in-process FFmpeg decoder (interleaved f32 at the native
|
||||
/// The stream is probed through oakcodec's in-process decoder registry and
|
||||
/// decoded with oakcodec's FFmpeg decoder (interleaved f32 at the native
|
||||
/// rate/layout), then reduced to one point per `samples_per_point` source
|
||||
/// samples.
|
||||
///
|
||||
@@ -728,34 +725,33 @@ pub fn extract(
|
||||
stream_index: i32,
|
||||
samples_per_point: i32,
|
||||
) -> Result<ExtractOutcome> {
|
||||
// Probe for the stream's native rate/layout (stateless).
|
||||
// SAFETY: `filename` is a NUL-terminated C string (validated by the FFI
|
||||
// layer); the probe handle is freed on every path below.
|
||||
let mut probe = unsafe { crate::bridge::codec::oakcodec_decoder_probe(filename.as_ptr()) };
|
||||
if probe.is_null() {
|
||||
return Err(Error::NotFound);
|
||||
// Probe for the stream's native rate/layout with the in-process decoder
|
||||
// registry (the Rust equivalent of the former oakcodec decoder probe
|
||||
// C ABI call).
|
||||
let filename_str = filename.to_string_lossy();
|
||||
let desc = probe_description(&filename_str).ok_or(Box::new(Error::NotFound))?;
|
||||
let ap = desc
|
||||
.get_audio_stream(stream_index as usize)
|
||||
.ok_or(Box::new(Error::NotFound))?;
|
||||
|
||||
// The probed stream metadata is a plain value type (oakcodec's
|
||||
// `AudioParams`); the fields map one-to-one onto the former
|
||||
// `oakcodec_audio_stream_info` POD.
|
||||
let sample_rate = ap.sample_rate;
|
||||
let channel_count = ap.channel_count();
|
||||
let channel_layout = ap.channel_layout;
|
||||
let container_stream_index = ap.stream_index;
|
||||
let duration_ts = ap.duration;
|
||||
let (time_base_num, time_base_den) = ap.time_base;
|
||||
|
||||
if sample_rate <= 0 || channel_count <= 0 {
|
||||
return Err(Box::new(Error::Failed("invalid audio stream".to_string())));
|
||||
}
|
||||
let mut info = unsafe { std::mem::zeroed::<AudioStreamInfo>() };
|
||||
let r = unsafe {
|
||||
crate::bridge::codec::oakcodec_decoder_probe_get_audio_stream(
|
||||
probe,
|
||||
stream_index,
|
||||
&mut info,
|
||||
)
|
||||
};
|
||||
// SAFETY: `probe` was created above and is no longer used.
|
||||
unsafe { crate::bridge::codec::oakcodec_decoder_free(&mut probe) };
|
||||
if r != 0 {
|
||||
return Err(Error::NotFound);
|
||||
}
|
||||
if info.sample_rate <= 0 || info.channel_count <= 0 {
|
||||
return Err(Error::Failed("invalid audio stream".to_string()));
|
||||
}
|
||||
let channels = info.channel_count;
|
||||
let channels = channel_count;
|
||||
if channels > EXTRACT_MAX_CHANNELS {
|
||||
return Err(Error::Failed(format!(
|
||||
return Err(Box::new(Error::Failed(format!(
|
||||
"stream has {channels} channels (max {EXTRACT_MAX_CHANNELS})"
|
||||
)));
|
||||
))));
|
||||
}
|
||||
|
||||
// Decode the whole stream through oakcodec's FFmpeg decoder
|
||||
@@ -764,23 +760,23 @@ pub fn extract(
|
||||
// fb_audio_graph to obtain planar f32).
|
||||
let decoder = FFmpegDecoder::new();
|
||||
let stream = CodecStream::with_block(
|
||||
filename.to_string_lossy().into_owned(),
|
||||
info.stream_index,
|
||||
filename_str.into_owned(),
|
||||
container_stream_index,
|
||||
None,
|
||||
);
|
||||
if let Err(e) = decoder.open(&stream) {
|
||||
return Err(Error::Failed(format!("failed to open decoder: {e:?}")));
|
||||
return Err(Box::new(Error::Failed(format!("failed to open decoder: {e:?}"))));
|
||||
}
|
||||
|
||||
if info.time_base_num <= 0 || info.time_base_den <= 0 || info.duration_ts <= 0 {
|
||||
if time_base_num <= 0 || time_base_den <= 0 || duration_ts <= 0 {
|
||||
let _ = decoder.close();
|
||||
return Err(Error::Failed("invalid audio stream duration".to_string()));
|
||||
return Err(Box::new(Error::Failed("invalid audio stream duration".to_string())));
|
||||
}
|
||||
let duration_sec =
|
||||
info.duration_ts as f64 * f64::from(info.time_base_num) / f64::from(info.time_base_den);
|
||||
let total_frames = (duration_sec * f64::from(info.sample_rate)).round() as i64;
|
||||
let layout_mask = if info.channel_layout != 0 {
|
||||
info.channel_layout
|
||||
duration_ts as f64 * f64::from(time_base_num) / f64::from(time_base_den);
|
||||
let total_frames = (duration_sec * f64::from(sample_rate)).round() as i64;
|
||||
let layout_mask = if channel_layout != 0 {
|
||||
channel_layout
|
||||
} else {
|
||||
ffmpeg_next::ChannelLayout::default(channels).bits()
|
||||
};
|
||||
@@ -796,11 +792,11 @@ pub fn extract(
|
||||
while offset < total_frames {
|
||||
let frames = (total_frames - offset).min(CHUNK_FRAMES);
|
||||
let range = TimeRange::new(
|
||||
Rational::new(offset, i64::from(info.sample_rate)),
|
||||
Rational::new(offset + frames, i64::from(info.sample_rate)),
|
||||
Rational::new(offset, i64::from(sample_rate)),
|
||||
Rational::new(offset + frames, i64::from(sample_rate)),
|
||||
);
|
||||
let mut buf = vec![0f32; frames as usize * channels as usize];
|
||||
match decoder.retrieve_audio(&mut buf, &range, info.sample_rate, layout_mask) {
|
||||
match decoder.retrieve_audio(&mut buf, &range, sample_rate, layout_mask) {
|
||||
Ok(RetrieveAudioStatus::Success) => {
|
||||
append_pending(&mut pending, &buf, channels);
|
||||
emit_points(
|
||||
@@ -812,11 +808,11 @@ pub fn extract(
|
||||
);
|
||||
}
|
||||
Ok(status) => {
|
||||
result = Err(Error::Failed(format!("audio retrieve failed: {status:?}")));
|
||||
result = Err(Box::new(Error::Failed(format!("audio retrieve failed: {status:?}"))));
|
||||
break;
|
||||
}
|
||||
Err(e) => {
|
||||
result = Err(Error::Failed(format!("audio retrieve failed: {e:?}")));
|
||||
result = Err(Box::new(Error::Failed(format!("audio retrieve failed: {e:?}"))));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,68 +14,43 @@
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Shared test helpers and bridge stubs for the oakaudio contract suite.
|
||||
//! Shared helpers for the oakaudio contract suite.
|
||||
//!
|
||||
//! The library imports the other oak modules (`oakcommon`, `oakcodec`)
|
||||
//! through the `bridge/` wrappers. A standalone `cargo test` run has no
|
||||
//! host dylibs to link, so [`mod stubs`] provides minimal definitions — a
|
||||
//! no-op config/encoder and a WAV-header probe (real decoding in
|
||||
//! `waveform::extract` goes through oakcodec's in-process FFmpeg decoder;
|
||||
//! the processor drives a real FFmpeg filter graph via ffmpeg-next). The
|
||||
//! exhaustive behavior matrix is pinned by the unchanged C++ gtest suite
|
||||
//! (`src/audio/tests`).
|
||||
//! The former bridge stubs are gone with the deleted C ABI: every test
|
||||
//! now calls the crate's public Rust API directly (manager singleton,
|
||||
//! processor, levelmeter, waveform, synchronizer). Decoding in
|
||||
//! `waveform::extract` goes through oakcodec's in-process FFmpeg
|
||||
//! decoder; the processor drives a real FFmpeg filter graph.
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// Serializes tests that mutate process-wide state (the manager singleton,
|
||||
/// the alive ledger) within one test binary.
|
||||
/// Serializes tests that mutate process-wide state (the manager singleton)
|
||||
/// within one test binary.
|
||||
pub static MANAGER_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// Lock the manager singleton for a test. The manager state persists across
|
||||
/// tests (the `OnceLock` cannot be reset), so a panicked test must not
|
||||
/// poison the lock for the rest of the binary.
|
||||
pub fn lock_manager() -> std::sync::MutexGuard<'static, ()> {
|
||||
MANAGER_LOCK.lock().unwrap_or_else(|p| p.into_inner())
|
||||
}
|
||||
|
||||
/// Build a planar f32 buffer with `channel_count` channels of `frame_count`
|
||||
/// frames from a single-channel `source` (replicated per channel).
|
||||
pub fn planar_from(source: &[f32], channel_count: usize) -> Vec<Vec<f32>> {
|
||||
(0..channel_count).map(|_| source.to_vec()).collect()
|
||||
}
|
||||
|
||||
/// A deterministic pseudo-random planar buffer (fixed seed) for stable
|
||||
/// golden vectors. Samples land in `[-1, 1)`.
|
||||
pub fn noisy_planar(channel_count: usize, frame_count: usize, seed: u64) -> Vec<Vec<f32>> {
|
||||
let mut state = seed | 1;
|
||||
let mut next = move || {
|
||||
state = state
|
||||
.wrapping_mul(6364136223846793005)
|
||||
.wrapping_add(1442695040888963407);
|
||||
((state >> 33) as u64 & 0xFFFF) as f32 / 65535.0 * 2.0 - 1.0
|
||||
};
|
||||
let mut data = Vec::with_capacity(channel_count);
|
||||
for _ in 0..channel_count {
|
||||
data.push((0..frame_count).map(|_| next()).collect());
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
/// A silence buffer: every sample is exactly `0.0`.
|
||||
pub fn silence_planar(channel_count: usize, frame_count: usize) -> Vec<Vec<f32>> {
|
||||
vec![vec![0.0; frame_count]; channel_count]
|
||||
}
|
||||
|
||||
/// Total number of `SamplePerChannel` entries in a channel-interleaved
|
||||
/// waveform sample for `points` points across `channels` channels.
|
||||
pub fn interleaved_len(points: usize, channels: usize) -> usize {
|
||||
points * channels
|
||||
}
|
||||
|
||||
/// Convert an `oakaudio`-style `min_max` pair layout into a plain tuple for
|
||||
/// comparison in tests.
|
||||
pub fn pair(min: f32, max: f32) -> (f32, f32) {
|
||||
(min, max)
|
||||
}
|
||||
|
||||
// ---- Minimal WAV fixture helpers -------------------------------------------
|
||||
|
||||
/// Write a 16-bit PCM WAV file (`fmt` chunk + `data` chunk, standard 44-byte
|
||||
/// header). The test stubs decode exactly this layout.
|
||||
/// header). Decoded by oakcodec's FFmpeg decoder in `waveform::extract`.
|
||||
pub fn write_wav(path: &Path, channels: u16, rate: u32, samples: &[i16]) -> std::io::Result<()> {
|
||||
let block_align = channels * 2;
|
||||
let byte_rate = rate * u32::from(block_align);
|
||||
@@ -124,286 +99,3 @@ pub fn write_wav_header_only(path: &Path, channels: u16, rate: u32) -> std::io::
|
||||
out.extend_from_slice(&0u32.to_le_bytes());
|
||||
std::fs::write(path, out)
|
||||
}
|
||||
|
||||
// ---- Bridge stubs -----------------------------------------------------------
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub mod stubs {
|
||||
use std::ffi::{c_char, c_int, c_void, CStr};
|
||||
use std::path::Path;
|
||||
|
||||
use oakaudio::bridge::codec::AudioStreamInfo;
|
||||
use oakaudio::handle::CHandle;
|
||||
|
||||
// ------------------------- oakcommon ---------------------------------
|
||||
|
||||
/// Not-found for every key: `config::device_name`'s two-stage query
|
||||
/// treats `size <= 1` as absent and returns the empty string, so the
|
||||
/// config-driven device lookup degrades to `paNoDevice` (the documented
|
||||
/// bridge degradation).
|
||||
#[no_mangle]
|
||||
pub extern "C" fn oakcommon_config_get(
|
||||
_group: *const c_char,
|
||||
_key: *const c_char,
|
||||
_buf: *mut c_char,
|
||||
_buf_size: c_int,
|
||||
) -> c_int {
|
||||
-1
|
||||
}
|
||||
|
||||
/// Every integer config reads its default.
|
||||
#[no_mangle]
|
||||
pub extern "C" fn oakcommon_config_get_int(
|
||||
_group: *const c_char,
|
||||
_key: *const c_char,
|
||||
default: c_int,
|
||||
) -> c_int {
|
||||
default
|
||||
}
|
||||
|
||||
/// Core `SampleFormat` (planar-first) → `FBSampleFormat` (AVSampleFormat
|
||||
/// order), mirroring `src/common/src/ffmpegutils.cpp:83`.
|
||||
///
|
||||
/// `// CPP-PARITY: src/common/src/ffmpegutils.cpp:83`
|
||||
/// (`FFmpegUtils::get_ffmpeg_sample_format`).
|
||||
#[no_mangle]
|
||||
pub extern "C" fn oakcommon_ffmpegutils_get_ffmpeg_sample_format(
|
||||
smp_fmt: c_int,
|
||||
out: *mut c_int,
|
||||
) -> c_int {
|
||||
let mapped = match smp_fmt {
|
||||
0 => 5, // u8_p -> fb_sample_fmt_u8_p
|
||||
1 => 6, // s16_p -> fb_sample_fmt_s16_p
|
||||
2 => 7, // s32_p -> fb_sample_fmt_s32_p
|
||||
3 => 11, // s64_p -> fb_sample_fmt_s64_p
|
||||
4 => 8, // f32_p -> fb_sample_fmt_fltp
|
||||
5 => 9, // f64_p -> fb_sample_fmt_dblp
|
||||
6 => 0, // u8 -> fb_sample_fmt_u8
|
||||
7 => 1, // s16 -> fb_sample_fmt_s16
|
||||
8 => 2, // s32 -> fb_sample_fmt_s32
|
||||
9 => 10, // s64 -> fb_sample_fmt_s64
|
||||
10 => 3, // f32 -> fb_sample_fmt_flt
|
||||
11 => 4, // f64 -> fb_sample_fmt_dbl
|
||||
_ => -1, // invalid/count -> fb_sample_fmt_none
|
||||
};
|
||||
if out.is_null() {
|
||||
return -1;
|
||||
}
|
||||
// SAFETY: the caller guarantees a writable int.
|
||||
unsafe { *out = mapped };
|
||||
0
|
||||
}
|
||||
|
||||
// ------------------------- oakcodec ----------------------------------
|
||||
|
||||
/// ffmpeg-style default channel layout mask for `nb_channels` (only the
|
||||
/// popcount is load-bearing for oakaudio). Masks above 63 channels
|
||||
/// cannot be represented in a u64 and yield 0 (the extract cap check
|
||||
/// rejects such streams before any layout use).
|
||||
fn layout_for(channels: i32) -> u64 {
|
||||
match channels {
|
||||
1 => 0x4,
|
||||
2 => 0x3,
|
||||
n if n > 0 && n < 64 => (1u64 << n) - 1,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// WAV header facts parsed by `parse_wav`.
|
||||
struct WavInfo {
|
||||
channels: i32,
|
||||
rate: i32,
|
||||
block_align: usize,
|
||||
frames: i64,
|
||||
}
|
||||
|
||||
/// Parse the standard 44-byte PCM WAV header the fixture writer emits.
|
||||
fn parse_wav(path: &Path) -> Option<WavInfo> {
|
||||
let bytes = std::fs::read(path).ok()?;
|
||||
if bytes.len() < 44 || &bytes[0..4] != b"RIFF" || &bytes[8..12] != b"WAVE" {
|
||||
return None;
|
||||
}
|
||||
if &bytes[12..16] != b"fmt " || &bytes[36..40] != b"data" {
|
||||
return None;
|
||||
}
|
||||
let fmt_size = u32::from_le_bytes(bytes[16..20].try_into().ok()?);
|
||||
if fmt_size < 16 {
|
||||
return None;
|
||||
}
|
||||
let audio_format = u16::from_le_bytes(bytes[20..22].try_into().ok()?);
|
||||
let channels = u16::from_le_bytes(bytes[22..24].try_into().ok()?);
|
||||
let rate = u32::from_le_bytes(bytes[24..28].try_into().ok()?);
|
||||
let block_align = u16::from_le_bytes(bytes[32..34].try_into().ok()?);
|
||||
let bits = u16::from_le_bytes(bytes[34..36].try_into().ok()?);
|
||||
let data_size = u32::from_le_bytes(bytes[40..44].try_into().ok()?);
|
||||
if audio_format != 1 || bits != 16 || channels == 0 || rate == 0 || block_align == 0 {
|
||||
return None;
|
||||
}
|
||||
let frames = (data_size as usize / block_align as usize) as i64;
|
||||
Some(WavInfo {
|
||||
channels: i32::from(channels),
|
||||
rate: rate as i32,
|
||||
block_align: block_align as usize,
|
||||
frames,
|
||||
})
|
||||
}
|
||||
|
||||
// All handles below use the shared `CHandle` ABI (single-lib
|
||||
// unification): oakaudio's `bridge::codec` wrappers call the oakcodec
|
||||
// crate's `#[no_mangle]` ffi functions directly, so these stubs must
|
||||
// match the real oakcodec ffi signatures exactly.
|
||||
|
||||
struct StubEncoder;
|
||||
|
||||
#[no_mangle]
|
||||
pub extern "C" fn oakcodec_encoder_init(params: *const c_void) -> CHandle {
|
||||
if params.is_null() {
|
||||
return CHandle::null();
|
||||
}
|
||||
CHandle {
|
||||
ctx: Box::into_raw(Box::new(StubEncoder)) as *mut c_void,
|
||||
addref: None,
|
||||
release: None,
|
||||
abi_version: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub extern "C" fn oakcodec_encoder_open(_encoder: CHandle) -> c_int {
|
||||
0
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub extern "C" fn oakcodec_encoder_write_audio(
|
||||
_encoder: CHandle,
|
||||
_samples: *const f32,
|
||||
_frame_count: c_int,
|
||||
) -> c_int {
|
||||
0
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub extern "C" fn oakcodec_encoder_flush(_encoder: CHandle) -> c_int {
|
||||
0
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub extern "C" fn oakcodec_encoder_last_error(
|
||||
_encoder: CHandle,
|
||||
_buf: *mut c_char,
|
||||
_buf_size: c_int,
|
||||
) -> c_int {
|
||||
0
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub extern "C" fn oakcodec_encoder_free(encoder: *mut CHandle) {
|
||||
if !encoder.is_null() {
|
||||
// SAFETY: the pointer was created by `oakcodec_encoder_init`;
|
||||
// the caller owns `encoder` and expects it cleared.
|
||||
let e = unsafe { &mut *encoder };
|
||||
if !e.ctx.is_null() {
|
||||
drop(unsafe { Box::from_raw(e.ctx as *mut StubEncoder) });
|
||||
e.ctx = std::ptr::null_mut();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Probe result for a decodable WAV file.
|
||||
struct StubProbe {
|
||||
channels: i32,
|
||||
sample_rate: i32,
|
||||
frames: i64,
|
||||
layout: u64,
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub extern "C" fn oakcodec_decoder_probe(filename: *const c_char) -> CHandle {
|
||||
if filename.is_null() {
|
||||
return CHandle::null();
|
||||
}
|
||||
// SAFETY: the C string is NUL-terminated (caller contract).
|
||||
let cname = unsafe { CStr::from_ptr(filename) };
|
||||
let path = Path::new(cname.to_str().unwrap_or(""));
|
||||
match parse_wav(path) {
|
||||
Some(info) => CHandle {
|
||||
ctx: Box::into_raw(Box::new(StubProbe {
|
||||
channels: info.channels,
|
||||
sample_rate: info.rate,
|
||||
frames: info.frames,
|
||||
layout: layout_for(info.channels),
|
||||
})) as *mut c_void,
|
||||
addref: None,
|
||||
release: None,
|
||||
abi_version: 0,
|
||||
},
|
||||
None => CHandle::null(),
|
||||
}
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub extern "C" fn oakcodec_decoder_free(probe: *mut CHandle) {
|
||||
if !probe.is_null() {
|
||||
// SAFETY: the pointer was created by `oakcodec_decoder_probe`;
|
||||
// the caller owns `probe` and expects it cleared.
|
||||
let p = unsafe { &mut *probe };
|
||||
if !p.ctx.is_null() {
|
||||
drop(unsafe { Box::from_raw(p.ctx as *mut StubProbe) });
|
||||
p.ctx = std::ptr::null_mut();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub extern "C" fn oakcodec_decoder_probe_audio_stream_count(_probe: CHandle) -> c_int {
|
||||
1
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub extern "C" fn oakcodec_decoder_probe_get_audio_stream(
|
||||
probe: CHandle,
|
||||
index: c_int,
|
||||
out: *mut AudioStreamInfo,
|
||||
) -> c_int {
|
||||
if probe.ctx.is_null() || out.is_null() || index != 0 {
|
||||
return -1;
|
||||
}
|
||||
// SAFETY: the probe ctx is a live `StubProbe`; `out` is a
|
||||
// caller-owned info struct.
|
||||
let p = unsafe { &*(probe.ctx as *const StubProbe) };
|
||||
unsafe {
|
||||
(*out).stream_index = 0;
|
||||
(*out).sample_rate = p.sample_rate;
|
||||
(*out).channel_layout = p.layout;
|
||||
(*out).channel_count = p.channels;
|
||||
(*out).duration_ts = p.frames;
|
||||
(*out).time_base_num = 1;
|
||||
(*out).time_base_den = p.sample_rate;
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub extern "C" fn oakcodec_decoder_open(
|
||||
_decoder: CHandle,
|
||||
_filename: *const c_char,
|
||||
_stream_index: c_int,
|
||||
) -> c_int {
|
||||
0
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub extern "C" fn oakcodec_decoder_decode_audio(
|
||||
_decoder: CHandle,
|
||||
_in_num: c_int,
|
||||
_in_den: c_int,
|
||||
_out_num: c_int,
|
||||
_out_den: c_int,
|
||||
_sample_rate: c_int,
|
||||
_channel_layout: u64,
|
||||
_buf: *mut f32,
|
||||
_buf_frames: c_int,
|
||||
) -> c_int {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,200 +0,0 @@
|
||||
// Oak Video Editor - Non-Linear Video Editor
|
||||
// Copyright (C) 2026 Oak Team
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! FFI-layer contract tests (ffi.rs). The exhaustive matrix runs against
|
||||
//! the unchanged C++ gtest suite (`src/audio/tests`); these tests pin
|
||||
//! Rust-side specifics (handle contracts, the singleton ledger, struct
|
||||
//! layout).
|
||||
|
||||
mod common;
|
||||
|
||||
use std::mem::{align_of, size_of};
|
||||
use std::sync::Mutex;
|
||||
|
||||
use oakaudio::error::{OAKAUDIO_E_INVALID, OAKAUDIO_OK};
|
||||
use oakaudio::ffi::levelmeter::oakaudio_levelmeter_analyze;
|
||||
use oakaudio::ffi::levelmeter::{ChannelStats, MeterStats};
|
||||
use oakaudio::ffi::manager::{
|
||||
oakaudio_debug_alive_count, oakaudio_manager_create_instance,
|
||||
oakaudio_manager_destroy_instance, oakaudio_manager_free, oakaudio_manager_instance,
|
||||
};
|
||||
use oakaudio::ffi::processor::{oakaudio_processor_free, oakaudio_processor_init};
|
||||
use oakaudio::ffi::sync::{OffsetResult, SourceClip};
|
||||
use oakaudio::ffi::waveform::{oakaudio_waveform_free, oakaudio_waveform_init};
|
||||
|
||||
/// Serializes tests that touch the process-wide singleton and the alive
|
||||
/// ledger.
|
||||
static LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// Every exported handle-returning function (processor_init, waveform_init)
|
||||
/// returns ctx==NULL on failure and a valid refcounted handle on success,
|
||||
/// with abi_version == OAKAUDIO_ABI_VERSION stamped.
|
||||
#[test]
|
||||
fn handle_contract_all_exports() {
|
||||
let _guard = LOCK.lock().unwrap();
|
||||
|
||||
let mut p = unsafe { oakaudio_processor_init() };
|
||||
assert!(!p.ctx.is_null());
|
||||
assert_eq!(p.abi_version, oakaudio::handle::OAKAUDIO_ABI_VERSION);
|
||||
|
||||
let mut w = unsafe { oakaudio_waveform_init() };
|
||||
assert!(!w.ctx.is_null());
|
||||
assert_eq!(w.abi_version, oakaudio::handle::OAKAUDIO_ABI_VERSION);
|
||||
|
||||
unsafe { oakaudio_processor_free(&mut p) };
|
||||
unsafe { oakaudio_waveform_free(&mut w) };
|
||||
}
|
||||
|
||||
/// free(NULL)/free(empty) are no-ops across every free export.
|
||||
#[test]
|
||||
fn free_null_noop_all_exports() {
|
||||
let _guard = LOCK.lock().unwrap();
|
||||
|
||||
let mut p = oakaudio::handle::CHandle::null();
|
||||
unsafe { oakaudio_processor_free(&mut p) };
|
||||
assert!(p.ctx.is_null());
|
||||
|
||||
let mut w = oakaudio::handle::CHandle::null();
|
||||
unsafe { oakaudio_waveform_free(&mut w) };
|
||||
assert!(w.ctx.is_null());
|
||||
|
||||
let mut m = oakaudio::handle::CHandle::null();
|
||||
unsafe { oakaudio_manager_free(&mut m) };
|
||||
assert!(m.ctx.is_null());
|
||||
|
||||
// NULL pointer itself is a no-op.
|
||||
unsafe { oakaudio_processor_free(std::ptr::null_mut()) };
|
||||
unsafe { oakaudio_waveform_free(std::ptr::null_mut()) };
|
||||
unsafe { oakaudio_manager_free(std::ptr::null_mut()) };
|
||||
}
|
||||
|
||||
/// The manager singleton: instance() is the same borrowed handle across
|
||||
/// calls; create/destroy flip validity; oakaudio_debug_alive_count moves
|
||||
/// predictably and returns to baseline.
|
||||
#[test]
|
||||
fn manager_singleton_and_alive_count() {
|
||||
let _guard = LOCK.lock().unwrap();
|
||||
|
||||
let before = unsafe { oakaudio_debug_alive_count() };
|
||||
|
||||
unsafe { oakaudio_manager_destroy_instance() };
|
||||
let none = unsafe { oakaudio_manager_instance() };
|
||||
assert!(none.ctx.is_null());
|
||||
// The empty instance handle is the shared `null()` (no ABI version).
|
||||
assert_eq!(none.abi_version, 0);
|
||||
|
||||
unsafe { oakaudio_manager_create_instance() };
|
||||
let m1 = unsafe { oakaudio_manager_instance() };
|
||||
let m2 = unsafe { oakaudio_manager_instance() };
|
||||
assert!(!m1.ctx.is_null());
|
||||
assert_eq!(
|
||||
m1.ctx, m2.ctx,
|
||||
"instance() must be the same borrowed handle"
|
||||
);
|
||||
|
||||
// A processor bumps the ledger; freeing it returns to baseline.
|
||||
assert_eq!(unsafe { oakaudio_debug_alive_count() }, before);
|
||||
let mut p = unsafe { oakaudio_processor_init() };
|
||||
assert_eq!(unsafe { oakaudio_debug_alive_count() }, before + 1);
|
||||
unsafe { oakaudio_processor_free(&mut p) };
|
||||
assert_eq!(unsafe { oakaudio_debug_alive_count() }, before);
|
||||
|
||||
// Destroy flips the singleton back to empty; create resurrects it.
|
||||
unsafe { oakaudio_manager_destroy_instance() };
|
||||
assert!(unsafe { oakaudio_manager_instance() }.ctx.is_null());
|
||||
unsafe { oakaudio_manager_create_instance() };
|
||||
assert!(!unsafe { oakaudio_manager_instance() }.ctx.is_null());
|
||||
}
|
||||
|
||||
/// oakaudio_levelmeter_analyze with NULL summary still computes per-channel
|
||||
/// stats, and a NULL channels array with capacity 0 is accepted when only
|
||||
/// the summary is wanted.
|
||||
#[test]
|
||||
fn levelmeter_partial_outputs() {
|
||||
let data = [0.5f32; 64];
|
||||
let planes = [data.as_ptr()];
|
||||
|
||||
// channels only (summary NULL)
|
||||
let mut channels = [ChannelStats {
|
||||
peak_linear: 0.0,
|
||||
peak_db: 0.0,
|
||||
rms_linear: 0.0,
|
||||
rms_db: 0.0,
|
||||
vu_db: 0.0,
|
||||
}];
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
oakaudio_levelmeter_analyze(
|
||||
planes.as_ptr(),
|
||||
1,
|
||||
64,
|
||||
channels.as_mut_ptr(),
|
||||
1,
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
},
|
||||
OAKAUDIO_OK
|
||||
);
|
||||
assert!((channels[0].peak_linear - 0.5).abs() < 1e-9);
|
||||
|
||||
// summary only (channels NULL, capacity 0)
|
||||
let mut summary = MeterStats {
|
||||
max_peak_linear: 0.0,
|
||||
integrated_lufs: 0.0,
|
||||
silence: 0,
|
||||
};
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
oakaudio_levelmeter_analyze(
|
||||
planes.as_ptr(),
|
||||
1,
|
||||
64,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
&mut summary,
|
||||
)
|
||||
},
|
||||
OAKAUDIO_OK
|
||||
);
|
||||
assert!((summary.max_peak_linear - 0.5).abs() < 1e-9);
|
||||
|
||||
// Both NULL is invalid.
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
oakaudio_levelmeter_analyze(
|
||||
planes.as_ptr(),
|
||||
1,
|
||||
64,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
},
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
}
|
||||
|
||||
/// sync value structs (offset_result/source_clip) are 24/40 bytes and
|
||||
/// repr(C)-aligned as the C headers dictate, so layout never drifts.
|
||||
#[test]
|
||||
fn sync_struct_layout() {
|
||||
assert_eq!(size_of::<OffsetResult>(), 24);
|
||||
assert_eq!(align_of::<OffsetResult>(), 8);
|
||||
assert_eq!(size_of::<SourceClip>(), 40);
|
||||
assert_eq!(align_of::<SourceClip>(), 8);
|
||||
// The stretch result (f64, i64, f64, i32) pads to 32 bytes.
|
||||
assert_eq!(size_of::<oakaudio::ffi::sync::StretchOffsetResult>(), 32);
|
||||
}
|
||||
@@ -19,15 +19,12 @@
|
||||
|
||||
mod common;
|
||||
|
||||
use std::ffi::CString;
|
||||
|
||||
use common::write_wav_header_only;
|
||||
use oakaudio::ffi::waveform::MinMax;
|
||||
use oakaudio::ffi::waveform::{
|
||||
oakaudio_waveform_extract, oakaudio_waveform_free, oakaudio_waveform_get_summary,
|
||||
oakaudio_waveform_init, oakaudio_waveform_overwrite_samples,
|
||||
oakaudio_waveform_set_channel_count,
|
||||
};
|
||||
use oakaudio::params::{frames_to_rational, rational_to_samples, SampleFormat};
|
||||
use oakcore_rs::Rational;
|
||||
use oakaudio::params::{frames_to_rational, rational_to_samples, AudioParams, SampleFormat};
|
||||
use oakaudio::waveform::{extract, AudioVisualWaveform};
|
||||
|
||||
/// SampleFormat planar-first ordering matches the authoritative C++ enum:
|
||||
/// f32_p == 4 == OAKAUDIO_PROCESSOR_OUTPUT_FORMAT. This guards the
|
||||
@@ -60,7 +57,7 @@ fn sample_time_conversion_roundtrip() {
|
||||
/// rational conversion edge cases (NaN / out-of-range / tiny -> null).
|
||||
#[test]
|
||||
fn params_value_types() {
|
||||
use oakaudio::params::{rational_from_double, AudioParams};
|
||||
use oakaudio::params::rational_from_double;
|
||||
|
||||
let p = AudioParams {
|
||||
sample_rate: 48000,
|
||||
@@ -89,23 +86,17 @@ fn waveform_mipmap_scale_parity() {
|
||||
// 1024 ramp samples @ 48000 Hz, two channels.
|
||||
let ch0: Vec<f32> = (0..1024).map(|i| i as f32 * 0.001).collect();
|
||||
let ch1: Vec<f32> = (0..1024).map(|i| -(i as f32) * 0.001).collect();
|
||||
let planes = [ch0.as_ptr(), ch1.as_ptr()];
|
||||
let planes = [ch0.as_slice(), ch1.as_slice()];
|
||||
|
||||
let mut w = unsafe { oakaudio_waveform_init() };
|
||||
assert!(!w.ctx.is_null());
|
||||
assert_eq!(unsafe { oakaudio_waveform_set_channel_count(w, 2) }, 0);
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_waveform_overwrite_samples(w, planes.as_ptr(), 1024, 48000, 0, 1) },
|
||||
0
|
||||
);
|
||||
let mut w = AudioVisualWaveform::new();
|
||||
w.set_channel_count(2);
|
||||
w.overwrite_samples(&planes, 48000, Rational::new(0, 1));
|
||||
|
||||
// One summary point is produced for any queried window; a 1/1024 s
|
||||
// window (one 1024-rate mipmap point ~ 46.875 source samples) must
|
||||
// bracket a narrower range than a 1/64 s window (~750 samples).
|
||||
let mut fine = [MinMax { min: 0.0, max: 0.0 }; 2];
|
||||
let fine_points =
|
||||
unsafe { oakaudio_waveform_get_summary(w, 0, 1, 1, 1024, fine.as_mut_ptr(), 2) };
|
||||
assert_eq!(fine_points, 1);
|
||||
let fine = w.get_summary_from_time(Rational::new(0, 1), Rational::new(1, 1024));
|
||||
assert_eq!(fine.len(), 2);
|
||||
assert_eq!(fine[0].min, 0.0);
|
||||
assert!(
|
||||
(fine[0].max - 0.046).abs() < 1e-5,
|
||||
@@ -119,10 +110,8 @@ fn waveform_mipmap_scale_parity() {
|
||||
);
|
||||
assert_eq!(fine[1].max, 0.0);
|
||||
|
||||
let mut coarse = [MinMax { min: 0.0, max: 0.0 }; 2];
|
||||
let coarse_points =
|
||||
unsafe { oakaudio_waveform_get_summary(w, 0, 1, 1, 64, coarse.as_mut_ptr(), 2) };
|
||||
assert_eq!(coarse_points, 1);
|
||||
let coarse = w.get_summary_from_time(Rational::new(0, 1), Rational::new(1, 64));
|
||||
assert_eq!(coarse.len(), 2);
|
||||
assert_eq!(coarse[0].min, 0.0);
|
||||
assert!(
|
||||
(coarse[0].max - 0.749).abs() < 1e-5,
|
||||
@@ -139,8 +128,6 @@ fn waveform_mipmap_scale_parity() {
|
||||
// Coarser windows necessarily cover more source samples.
|
||||
assert!(coarse[0].max > fine[0].max);
|
||||
assert!(coarse[1].min < fine[1].min);
|
||||
|
||||
unsafe { oakaudio_waveform_free(&mut w) };
|
||||
}
|
||||
|
||||
/// levelmeter dB conversion: peak_db == 20*log10(peak_linear) and the
|
||||
@@ -164,57 +151,30 @@ fn levelmeter_db_golden() {
|
||||
|
||||
/// waveformsync envelope offset golden: a reference ramp delayed by two
|
||||
/// windows in the candidate is recovered as +2 windows with full
|
||||
/// confidence through the C ABI.
|
||||
/// confidence.
|
||||
#[test]
|
||||
fn waveform_sync_offset_golden() {
|
||||
use oakaudio::ffi::sync::{oakaudio_sync_estimate_envelope_offset, OffsetResult};
|
||||
let reference: Vec<f64> = (0..10).map(|i| i as f64 * 0.1 + 0.1).collect();
|
||||
let mut candidate = vec![0.0f64; 10];
|
||||
candidate[2..].copy_from_slice(&reference[..8]);
|
||||
let mut out = OffsetResult {
|
||||
offset_samples: 0,
|
||||
confidence: 0.0,
|
||||
valid: 0,
|
||||
};
|
||||
let r = unsafe {
|
||||
oakaudio_sync_estimate_envelope_offset(
|
||||
reference.as_ptr(),
|
||||
reference.len() as i32,
|
||||
candidate.as_ptr(),
|
||||
candidate.len() as i32,
|
||||
std::ptr::null(),
|
||||
std::ptr::null(),
|
||||
100,
|
||||
10,
|
||||
&mut out,
|
||||
)
|
||||
};
|
||||
assert_eq!(r, 0);
|
||||
assert_eq!(out.valid, 1);
|
||||
let out = oakaudio::waveformsync::estimate_envelope_offset(&reference, &candidate, 100, 10);
|
||||
assert!(out.valid);
|
||||
assert_eq!(out.offset_samples, 200);
|
||||
assert!((out.confidence - 1.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
/// oakaudio_waveform_extract channel cap: a stream claiming more than
|
||||
/// OAKAUDIO_EXTRACT_MAX_CHANNELS (64) channels is rejected rather than
|
||||
/// overflowing the internal plane array.
|
||||
/// waveform::extract channel cap: a stream claiming more than
|
||||
/// EXTRACT_MAX_CHANNELS (64) channels is rejected rather than overflowing
|
||||
/// the internal plane array.
|
||||
#[test]
|
||||
fn extract_channel_cap() {
|
||||
let path = std::env::temp_dir().join(format!("oakaudio_cap_{}.wav", std::process::id()));
|
||||
write_wav_header_only(&path, 65, 48000).unwrap();
|
||||
|
||||
let mut out_channels = 0i32;
|
||||
let cpath = std::ffi::CString::new(path.to_str().unwrap()).unwrap();
|
||||
let r = unsafe {
|
||||
oakaudio_waveform_extract(
|
||||
cpath.as_ptr(),
|
||||
0,
|
||||
4,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
&mut out_channels,
|
||||
)
|
||||
};
|
||||
assert!(r < 0, "oversized stream must be rejected, got {r}");
|
||||
let cpath = CString::new(path.to_str().unwrap()).unwrap();
|
||||
assert!(
|
||||
extract(&cpath, 0, 4).is_err(),
|
||||
"oversized stream must be rejected"
|
||||
);
|
||||
std::fs::remove_file(&path).ok();
|
||||
}
|
||||
|
||||
@@ -1,126 +0,0 @@
|
||||
// Oak Video Editor - Non-Linear Video Editor
|
||||
// Copyright (C) 2026 Oak Team
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Handle plumbing contract tests (handle.rs).
|
||||
|
||||
use oakaudio::error::{OAKAUDIO_E_FAILED, OAKAUDIO_E_INVALID, OAKAUDIO_OK};
|
||||
use std::sync::{Mutex, MutexGuard};
|
||||
|
||||
use oakaudio::handle::{alive_count, get, guard, guard_handle, make_borrowed, make_owned, CHandle};
|
||||
|
||||
/// Serializes the tests: the crate's live-object ledger is process-global,
|
||||
/// so parallel tests in this file would race the count assertions.
|
||||
fn ledger_lock() -> MutexGuard<'static, ()> {
|
||||
static LOCK: Mutex<()> = Mutex::new(());
|
||||
LOCK.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// make_owned starts at refcount 1; get returns a typed view; dropping the
|
||||
/// handle decrements to 0.
|
||||
#[test]
|
||||
fn owned_lifecycle() {
|
||||
let _l = ledger_lock();
|
||||
let before = alive_count();
|
||||
let mut h = make_owned(42u32);
|
||||
assert!(!h.is_null());
|
||||
assert_eq!(alive_count(), before + 1);
|
||||
|
||||
// SAFETY: `h` boxes a u32 created above.
|
||||
let v = unsafe { get::<u32>(&h) }.unwrap();
|
||||
assert_eq!(*v, 42);
|
||||
|
||||
// addref/release round-trip through the function pointers.
|
||||
let addref = h.addref.unwrap();
|
||||
let release = h.release.unwrap();
|
||||
// SAFETY: the ctx was created by make_owned.
|
||||
unsafe { addref(h.ctx) };
|
||||
assert_eq!(alive_count(), before + 1); // count unchanged, still 1 box
|
||||
unsafe { release(h.ctx) };
|
||||
|
||||
// Dropping the box (release to zero) decrements the ledger.
|
||||
let release = h.release.unwrap();
|
||||
// SAFETY: h.ctx is the box created above; refcount is 1.
|
||||
unsafe { release(h.ctx) };
|
||||
h.ctx = std::ptr::null_mut();
|
||||
assert_eq!(alive_count(), before);
|
||||
}
|
||||
|
||||
/// make_borrowed creates a borrow-only handle whose release frees only the
|
||||
/// box, never the underlying object.
|
||||
#[test]
|
||||
fn borrowed_release() {
|
||||
let mut value = Box::new(7i32);
|
||||
// SAFETY: `value` outlives the handle; the ctx points directly at the
|
||||
// box (not a RefBox), so it is read through the raw pointer.
|
||||
let mut h = unsafe { make_borrowed(&mut *value) };
|
||||
assert!(!h.is_null());
|
||||
|
||||
// SAFETY: `h.ctx` points at the box created above.
|
||||
let v = unsafe { &*(h.ctx as *const i32) };
|
||||
assert_eq!(*v, 7);
|
||||
|
||||
// release is a no-op: the box still lives.
|
||||
let release = h.release.unwrap();
|
||||
// SAFETY: noop_ref for borrowed handles.
|
||||
unsafe { release(h.ctx) };
|
||||
assert_eq!(*value, 7);
|
||||
|
||||
h.ctx = std::ptr::null_mut();
|
||||
}
|
||||
|
||||
/// CHandle::null() yields an empty handle; guard over an Ok(()) returns
|
||||
/// OAKAUDIO_OK (0) and guard_handle over Ok returns a valid handle.
|
||||
#[test]
|
||||
fn null_and_guard_ok() {
|
||||
let null = CHandle::null();
|
||||
assert!(null.is_null());
|
||||
// The shared `null()` stamps no ABI version (single-lib unification).
|
||||
assert_eq!(null.abi_version, 0);
|
||||
|
||||
assert_eq!(guard(|| Ok(())), OAKAUDIO_OK);
|
||||
|
||||
let h = guard_handle(|| Ok(make_owned(1u32)));
|
||||
assert!(!h.is_null());
|
||||
// Release it so the alive ledger returns to baseline (tests share the
|
||||
// process-wide ledger and run in parallel).
|
||||
// SAFETY: `h.ctx` is the box created above; refcount is 1.
|
||||
unsafe { (h.release.unwrap())(h.ctx) };
|
||||
}
|
||||
|
||||
/// guard maps an Err to the negative error code without panicking; a
|
||||
/// panicking body is caught and returns a failure code rather than
|
||||
/// unwinding across the FFI boundary.
|
||||
#[test]
|
||||
fn guard_error_and_panic() {
|
||||
assert_eq!(
|
||||
guard(|| Err(oakaudio::error::Error::Invalid)),
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
assert_eq!(guard(|| Err(oakaudio::error::Error::State)), -60002);
|
||||
assert_eq!(
|
||||
guard(|| Err(oakaudio::error::Error::Failed("x".to_string()))),
|
||||
-60003
|
||||
);
|
||||
assert_eq!(guard(|| Err(oakaudio::error::Error::NotFound)), -60004);
|
||||
assert_eq!(guard(|| Err(oakaudio::error::Error::NoMem)), -60005);
|
||||
|
||||
assert_eq!(guard(|| panic!("boom")), OAKAUDIO_E_FAILED);
|
||||
|
||||
let h = guard_handle(|| Err(oakaudio::error::Error::Invalid));
|
||||
assert!(h.is_null());
|
||||
let h2 = guard_handle(|| panic!("boom"));
|
||||
assert!(h2.is_null());
|
||||
}
|
||||
@@ -14,53 +14,28 @@
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! AudioLevelMeter contract tests (levelmeter.rs), through the C ABI.
|
||||
//! AudioLevelMeter contract tests (levelmeter.rs), calling the public
|
||||
//! `analyze_sample_buffer` API.
|
||||
|
||||
mod common;
|
||||
|
||||
use oakaudio::error::{OAKAUDIO_E_INVALID, OAKAUDIO_OK};
|
||||
use oakaudio::ffi::levelmeter::{oakaudio_levelmeter_analyze, ChannelStats, MeterStats};
|
||||
use oakaudio::levelmeter::{analyze_sample_buffer, Stats};
|
||||
|
||||
fn analyze(planes: &[Vec<f32>]) -> (Vec<ChannelStats>, MeterStats) {
|
||||
let ptrs: Vec<*const f32> = planes.iter().map(|p| p.as_ptr()).collect();
|
||||
let mut channels: Vec<ChannelStats> = (0..planes.len())
|
||||
.map(|_| ChannelStats {
|
||||
peak_linear: 0.0,
|
||||
peak_db: 0.0,
|
||||
rms_linear: 0.0,
|
||||
rms_db: 0.0,
|
||||
vu_db: 0.0,
|
||||
})
|
||||
.collect();
|
||||
let mut summary = MeterStats {
|
||||
max_peak_linear: 0.0,
|
||||
integrated_lufs: 0.0,
|
||||
silence: 0,
|
||||
};
|
||||
let r = unsafe {
|
||||
oakaudio_levelmeter_analyze(
|
||||
ptrs.as_ptr(),
|
||||
planes.len() as i32,
|
||||
planes.first().map_or(0, |p| p.len()) as i32,
|
||||
channels.as_mut_ptr(),
|
||||
channels.len() as i32,
|
||||
&mut summary,
|
||||
)
|
||||
};
|
||||
assert_eq!(r, OAKAUDIO_OK);
|
||||
(channels, summary)
|
||||
fn analyze(planes: &[Vec<f32>]) -> Stats {
|
||||
let refs: Vec<&[f32]> = planes.iter().map(Vec::as_slice).collect();
|
||||
analyze_sample_buffer(&refs)
|
||||
}
|
||||
|
||||
/// A silence buffer reports silence=1, all-zero linear fields, and dB
|
||||
/// A silence buffer reports silence=true, all-zero linear fields, and dB
|
||||
/// fields floored at -200.
|
||||
#[test]
|
||||
fn silence_analysis() {
|
||||
let planes = common::silence_planar(2, 64);
|
||||
let (channels, summary) = analyze(&planes);
|
||||
assert_eq!(summary.silence, 1);
|
||||
assert_eq!(summary.max_peak_linear, 0.0);
|
||||
assert_eq!(summary.integrated_lufs, -200.0);
|
||||
for ch in &channels {
|
||||
let stats = analyze(&planes);
|
||||
assert!(stats.silence);
|
||||
assert_eq!(stats.max_peak_linear, 0.0);
|
||||
assert_eq!(stats.integrated_lufs, -200.0);
|
||||
for ch in &stats.channels {
|
||||
assert_eq!(ch.peak_linear, 0.0);
|
||||
assert_eq!(ch.rms_linear, 0.0);
|
||||
assert_eq!(ch.peak_db, -200.0);
|
||||
@@ -70,21 +45,22 @@ fn silence_analysis() {
|
||||
}
|
||||
|
||||
/// A constant-amplitude tone reports peak_linear == rms_linear == that
|
||||
/// amplitude (power terms), peak_db matches 20*log10(amp), and silence=0.
|
||||
/// amplitude (power terms), peak_db matches 20*log10(amp), and silence is
|
||||
/// false.
|
||||
#[test]
|
||||
fn constant_tone_stats() {
|
||||
let planes = common::planar_from(&[0.5f32; 64], 1);
|
||||
let (channels, summary) = analyze(&planes);
|
||||
assert_eq!(summary.silence, 0);
|
||||
assert!((channels[0].peak_linear - 0.5).abs() < 1e-9);
|
||||
assert!((channels[0].rms_linear - 0.5).abs() < 1e-9);
|
||||
let stats = analyze(&planes);
|
||||
assert!(!stats.silence);
|
||||
assert!((stats.channels[0].peak_linear - 0.5).abs() < 1e-9);
|
||||
assert!((stats.channels[0].rms_linear - 0.5).abs() < 1e-9);
|
||||
let expected_db = 20.0 * 0.5f64.log10();
|
||||
assert!((channels[0].peak_db - expected_db).abs() < 1e-9);
|
||||
assert!((channels[0].rms_db - expected_db).abs() < 1e-9);
|
||||
assert!((stats.channels[0].peak_db - expected_db).abs() < 1e-9);
|
||||
assert!((stats.channels[0].rms_db - expected_db).abs() < 1e-9);
|
||||
}
|
||||
|
||||
/// A full-scale square wave yields max_peak_linear == 1.0 and a peak_db
|
||||
/// near 0 dB; per-channel channels array is filled for each channel.
|
||||
/// near 0 dB; per-channel stats are filled for each channel.
|
||||
#[test]
|
||||
fn full_scale_peak() {
|
||||
let ch0: Vec<f32> = (0..64)
|
||||
@@ -93,13 +69,13 @@ fn full_scale_peak() {
|
||||
let ch1: Vec<f32> = (0..64)
|
||||
.map(|i| if i % 2 == 0 { -1.0 } else { 1.0 })
|
||||
.collect();
|
||||
let (channels, summary) = analyze(&[ch0, ch1]);
|
||||
assert_eq!(summary.max_peak_linear, 1.0);
|
||||
assert_eq!(summary.silence, 0);
|
||||
assert!((channels[0].peak_db - 0.0).abs() < 1e-9);
|
||||
assert!((channels[1].peak_db - 0.0).abs() < 1e-9);
|
||||
assert!((channels[0].rms_linear - 1.0).abs() < 1e-9);
|
||||
assert!((channels[1].rms_linear - 1.0).abs() < 1e-9);
|
||||
let stats = analyze(&[ch0, ch1]);
|
||||
assert_eq!(stats.max_peak_linear, 1.0);
|
||||
assert!(!stats.silence);
|
||||
assert!((stats.channels[0].peak_db - 0.0).abs() < 1e-9);
|
||||
assert!((stats.channels[1].peak_db - 0.0).abs() < 1e-9);
|
||||
assert!((stats.channels[0].rms_linear - 1.0).abs() < 1e-9);
|
||||
assert!((stats.channels[1].rms_linear - 1.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
/// integrated_lufs stays -200 for silence and matches the BS.1770
|
||||
@@ -107,57 +83,27 @@ fn full_scale_peak() {
|
||||
#[test]
|
||||
fn integrated_lufs_silence_vs_tone() {
|
||||
let silence = common::silence_planar(2, 64);
|
||||
let (_, summary) = analyze(&silence);
|
||||
assert_eq!(summary.integrated_lufs, -200.0);
|
||||
let stats = analyze(&silence);
|
||||
assert_eq!(stats.integrated_lufs, -200.0);
|
||||
|
||||
let tone = common::planar_from(&[0.5f32; 64], 2);
|
||||
let (_, summary) = analyze(&tone);
|
||||
let stats = analyze(&tone);
|
||||
// mean square over all channels = 0.25; -0.691 + 10*log10(0.25)
|
||||
let expected = -0.691 + 10.0 * 0.25f64.log10();
|
||||
assert!((summary.integrated_lufs - expected).abs() < 1e-9);
|
||||
assert!((stats.integrated_lufs - expected).abs() < 1e-9);
|
||||
}
|
||||
|
||||
/// channel_count of 0, a NULL planar pointer, or NULL for both outputs
|
||||
/// returns OAKAUDIO_E_INVALID.
|
||||
/// Empty or zero-length inputs yield a default stats struct (no channels,
|
||||
/// silence).
|
||||
#[test]
|
||||
fn invalid_input() {
|
||||
let planes = common::planar_from(&[0.5f32; 8], 1);
|
||||
let ptr = planes[0].as_ptr();
|
||||
let mut summary = MeterStats {
|
||||
max_peak_linear: 0.0,
|
||||
integrated_lufs: 0.0,
|
||||
silence: 0,
|
||||
};
|
||||
fn empty_input() {
|
||||
let stats = analyze_sample_buffer(&[]);
|
||||
assert!(stats.channels.is_empty());
|
||||
assert!(stats.silence);
|
||||
|
||||
// channel_count 0.
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_levelmeter_analyze(&ptr, 0, 8, std::ptr::null_mut(), 0, &mut summary) },
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
// NULL planar.
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
oakaudio_levelmeter_analyze(
|
||||
std::ptr::null(),
|
||||
1,
|
||||
8,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
&mut summary,
|
||||
)
|
||||
},
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
// Both outputs NULL.
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
oakaudio_levelmeter_analyze(&ptr, 1, 8, std::ptr::null_mut(), 0, std::ptr::null_mut())
|
||||
},
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
// Negative frame count.
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_levelmeter_analyze(&ptr, 1, -1, std::ptr::null_mut(), 0, &mut summary) },
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
let silence = common::silence_planar(1, 0);
|
||||
let refs: Vec<&[f32]> = silence.iter().map(Vec::as_slice).collect();
|
||||
let stats = analyze_sample_buffer(&refs);
|
||||
assert!(stats.silence);
|
||||
assert_eq!(stats.max_peak_linear, 0.0);
|
||||
}
|
||||
|
||||
@@ -14,171 +14,96 @@
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! AudioManager contract tests (manager.rs), through the C ABI. The
|
||||
//! manager is a process-wide singleton, so every test holds the shared
|
||||
//! AudioManager contract tests (manager.rs), calling the public Rust API.
|
||||
//! The manager is a process-wide singleton, so every test holds the shared
|
||||
//! `MANAGER_LOCK`.
|
||||
|
||||
mod common;
|
||||
|
||||
use std::ffi::c_char;
|
||||
use common::lock_manager;
|
||||
use oakcodec::encodingparams::EncodingParams;
|
||||
use oakaudio::error::{Error, OAKAUDIO_E_INVALID};
|
||||
use oakaudio::manager::instance;
|
||||
use oakaudio::params::{AudioParams, SampleFormat};
|
||||
|
||||
use common::MANAGER_LOCK;
|
||||
use oakaudio::bridge::codec::EncodingParams;
|
||||
use oakaudio::error::{OAKAUDIO_E_FAILED, OAKAUDIO_E_INVALID, OAKAUDIO_OK};
|
||||
use oakaudio::ffi::manager::{
|
||||
oakaudio_debug_alive_count, oakaudio_manager_clear_buffered_output,
|
||||
oakaudio_manager_create_instance, oakaudio_manager_destroy_instance,
|
||||
oakaudio_manager_find_config_device_by_name_s, oakaudio_manager_find_device_by_name_s,
|
||||
oakaudio_manager_free, oakaudio_manager_get_input_device, oakaudio_manager_get_output_device,
|
||||
oakaudio_manager_hard_reset, oakaudio_manager_instance, oakaudio_manager_push_to_output,
|
||||
oakaudio_manager_reset_output_clock, oakaudio_manager_seconds,
|
||||
oakaudio_manager_set_input_device, oakaudio_manager_set_output_device,
|
||||
oakaudio_manager_output_levels, oakaudio_manager_set_output_notify_interval,
|
||||
oakaudio_manager_start_recording,
|
||||
oakaudio_manager_stop_output, oakaudio_manager_stop_recording,
|
||||
};
|
||||
|
||||
fn instance() -> oakaudio::handle::CHandle {
|
||||
unsafe { oakaudio_manager_instance() }
|
||||
}
|
||||
|
||||
/// Lock the manager singleton for a test. The manager state persists across
|
||||
/// tests (the `OnceLock` cannot be reset), so a panicked test must not
|
||||
/// poison the lock for the rest of the binary.
|
||||
fn lock() -> std::sync::MutexGuard<'static, ()> {
|
||||
MANAGER_LOCK.lock().unwrap_or_else(|p| p.into_inner())
|
||||
}
|
||||
|
||||
fn encoding_params() -> EncodingParams {
|
||||
let mut filename = [0u8; 1024];
|
||||
for (i, b) in b"oakaudio_test.wav\0".iter().enumerate() {
|
||||
filename[i] = *b;
|
||||
}
|
||||
EncodingParams {
|
||||
filename,
|
||||
format: 0,
|
||||
video_enabled: 0,
|
||||
video_codec: 0,
|
||||
video_width: 0,
|
||||
video_height: 0,
|
||||
video_time_base_num: 0,
|
||||
video_time_base_den: 0,
|
||||
video_pixel_format: 0,
|
||||
video_interlacing: 0,
|
||||
video_pixel_aspect_num: 0,
|
||||
video_pixel_aspect_den: 0,
|
||||
video_bit_rate: 0,
|
||||
video_min_bit_rate: 0,
|
||||
video_max_bit_rate: 0,
|
||||
video_buffer_size: 0,
|
||||
video_threads: 0,
|
||||
video_pix_fmt: [0u8; 64],
|
||||
video_is_image_sequence: 0,
|
||||
video_scaling_method: 0,
|
||||
audio_enabled: 1,
|
||||
audio_codec: 13, // PCM_S16LE (the .wav recording codec)
|
||||
audio_sample_rate: 48000,
|
||||
audio_channel_layout: 3,
|
||||
audio_sample_format: 8,
|
||||
audio_bit_rate: 128000,
|
||||
subtitles_enabled: 0,
|
||||
subtitles_codec: 0,
|
||||
subtitles_are_sidecar: 0,
|
||||
subtitles_sidecar_format: 0,
|
||||
color_transform_output: [0u8; 256],
|
||||
export_length_num: 0,
|
||||
export_length_den: 0,
|
||||
has_custom_range: 0,
|
||||
custom_range_in_num: 0,
|
||||
custom_range_in_den: 0,
|
||||
custom_range_out_num: 0,
|
||||
custom_range_out_den: 0,
|
||||
/// Audio params for the tests: stereo f32 at 48 kHz.
|
||||
fn stereo() -> AudioParams {
|
||||
AudioParams {
|
||||
sample_rate: 48000,
|
||||
channel_layout: 0x3,
|
||||
format: SampleFormat::F32,
|
||||
}
|
||||
}
|
||||
|
||||
/// create_instance/destroy_instance toggle the singleton; instance() returns
|
||||
/// a valid borrowed handle between them and NULL after destroy.
|
||||
/// A WAV recording config (format 7 = WAV).
|
||||
fn wav_params(filename: &str) -> EncodingParams {
|
||||
let mut params = EncodingParams::default();
|
||||
params.format = 7;
|
||||
params.audio_enabled = 1;
|
||||
params.audio_codec = 13; // PCM_S16LE
|
||||
params.audio_sample_rate = 48000;
|
||||
params.audio_channel_layout = 0x3;
|
||||
params.audio_sample_format = SampleFormat::S16;
|
||||
params.audio_bit_rate = 128000;
|
||||
let bytes = filename.as_bytes();
|
||||
params.filename[..bytes.len()].copy_from_slice(bytes);
|
||||
params
|
||||
}
|
||||
|
||||
/// create_instance/destroy_instance toggle the singleton; instance()
|
||||
/// returns a live guard between them and None after destroy.
|
||||
#[test]
|
||||
fn singleton_lifecycle() {
|
||||
let _guard = lock();
|
||||
unsafe { oakaudio_manager_destroy_instance() };
|
||||
assert!(instance().ctx.is_null());
|
||||
let _guard = lock_manager();
|
||||
oakaudio::manager::ManagerInner::destroy_instance();
|
||||
assert!(instance().is_none());
|
||||
|
||||
unsafe { oakaudio_manager_create_instance() };
|
||||
let m = instance();
|
||||
assert!(!m.ctx.is_null());
|
||||
unsafe { oakaudio_manager_free(&mut m.clone()) };
|
||||
oakaudio::manager::ManagerInner::create_instance().unwrap();
|
||||
assert!(instance().is_some());
|
||||
|
||||
unsafe { oakaudio_manager_destroy_instance() };
|
||||
assert!(instance().ctx.is_null());
|
||||
unsafe { oakaudio_manager_create_instance() };
|
||||
assert!(!instance().ctx.is_null());
|
||||
oakaudio::manager::ManagerInner::destroy_instance();
|
||||
assert!(instance().is_none());
|
||||
oakaudio::manager::ManagerInner::create_instance().unwrap();
|
||||
assert!(instance().is_some());
|
||||
}
|
||||
|
||||
/// A fresh singleton for a test: destroy resets the playback state
|
||||
/// (`output_started`, buffered params) that earlier tests in this binary
|
||||
/// may have left behind.
|
||||
fn fresh_instance() {
|
||||
oakaudio::manager::ManagerInner::destroy_instance();
|
||||
oakaudio::manager::ManagerInner::create_instance().unwrap();
|
||||
}
|
||||
|
||||
/// push_to_output accepts raw interleaved bytes and starts the virtual
|
||||
/// playback clock; without a device it fails with a message in error_buf.
|
||||
/// playback clock; without a device the push still succeeds and keeps the
|
||||
/// samples buffered (unavailable devices play silence instead of failing).
|
||||
///
|
||||
/// The virtual device never consumes frames (PortAudio is not bridged), so
|
||||
/// the clock reads 0.0 rather than advancing.
|
||||
/// The clock reads 0.0 after the push starts; a real audio device may have
|
||||
/// consumed a few frames by the time the assertion runs, so the bound is
|
||||
/// `>= 0` rather than exact (the callback-advances-clock behavior is pinned
|
||||
/// by manager.rs' own unit test).
|
||||
#[test]
|
||||
fn push_output_advances_clock() {
|
||||
let _guard = lock();
|
||||
unsafe { oakaudio_manager_create_instance() };
|
||||
let m = instance();
|
||||
fn push_output_starts_clock() {
|
||||
let _guard = lock_manager();
|
||||
fresh_instance();
|
||||
let mut m = instance().unwrap();
|
||||
|
||||
// No stream yet: seconds() reports -1.
|
||||
let mut secs = 0.0f64;
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_manager_seconds(m, &mut secs) },
|
||||
OAKAUDIO_OK
|
||||
);
|
||||
m.seconds(&mut secs).unwrap();
|
||||
assert_eq!(secs, -1.0);
|
||||
|
||||
// M12 P1: with no explicit device the push still succeeds — the
|
||||
// samples buffer for the default output device (unavailable devices
|
||||
// keep playback silent instead of failing the push).
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_manager_set_output_device(m, -1) },
|
||||
OAKAUDIO_OK
|
||||
);
|
||||
// With no explicit device the push still succeeds (M12 P1).
|
||||
m.set_output_device(-1).unwrap();
|
||||
let samples = vec![0u8; 480 * 2 * 4];
|
||||
let r = unsafe {
|
||||
oakaudio_manager_push_to_output(
|
||||
m,
|
||||
48000,
|
||||
3,
|
||||
4,
|
||||
samples.as_ptr() as *const c_char,
|
||||
samples.len() as i64,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
)
|
||||
};
|
||||
assert_eq!(r, OAKAUDIO_OK);
|
||||
m.push_to_output(stereo(), &samples, &mut vec![0u8; 64]).unwrap();
|
||||
|
||||
// After selecting a device the push succeeds and the clock starts at 0.
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_manager_set_output_device(m, 0) },
|
||||
OAKAUDIO_OK
|
||||
);
|
||||
let mut err = [0 as c_char; 64];
|
||||
let r = unsafe {
|
||||
oakaudio_manager_push_to_output(
|
||||
m,
|
||||
48000,
|
||||
3,
|
||||
4,
|
||||
samples.as_ptr() as *const c_char,
|
||||
samples.len() as i64,
|
||||
err.as_mut_ptr(),
|
||||
err.len() as i32,
|
||||
)
|
||||
};
|
||||
assert_eq!(r, OAKAUDIO_OK);
|
||||
unsafe { oakaudio_manager_seconds(m, &mut secs) };
|
||||
assert_eq!(secs, 0.0);
|
||||
|
||||
unsafe { oakaudio_manager_destroy_instance() };
|
||||
m.set_output_device(0).unwrap();
|
||||
m.push_to_output(stereo(), &samples, &mut vec![0u8; 64]).unwrap();
|
||||
m.seconds(&mut secs).unwrap();
|
||||
assert!(secs >= 0.0, "clock started (got {secs})");
|
||||
}
|
||||
|
||||
/// set/get output & input device: getters report a device, setters persist
|
||||
@@ -186,183 +111,102 @@ fn push_output_advances_clock() {
|
||||
/// clears buffers).
|
||||
#[test]
|
||||
fn device_selection_roundtrip() {
|
||||
let _guard = lock();
|
||||
unsafe { oakaudio_manager_create_instance() };
|
||||
let m = instance();
|
||||
let _guard = lock_manager();
|
||||
fresh_instance();
|
||||
let mut m = instance().unwrap();
|
||||
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_manager_set_output_device(m, 42) },
|
||||
OAKAUDIO_OK
|
||||
);
|
||||
assert_eq!(unsafe { oakaudio_manager_get_output_device(m) }, 42);
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_manager_set_input_device(m, 7) },
|
||||
OAKAUDIO_OK
|
||||
);
|
||||
assert_eq!(unsafe { oakaudio_manager_get_input_device(m) }, 7);
|
||||
m.set_output_device(42).unwrap();
|
||||
assert_eq!(m.get_output_device().unwrap(), 42);
|
||||
m.set_input_device(7).unwrap();
|
||||
assert_eq!(m.get_input_device().unwrap(), 7);
|
||||
|
||||
assert_eq!(unsafe { oakaudio_manager_hard_reset(m) }, OAKAUDIO_OK);
|
||||
assert_eq!(unsafe { oakaudio_manager_get_output_device(m) }, 42);
|
||||
assert_eq!(unsafe { oakaudio_manager_get_input_device(m) }, 7);
|
||||
m.hard_reset().unwrap();
|
||||
assert_eq!(m.get_output_device().unwrap(), 42);
|
||||
assert_eq!(m.get_input_device().unwrap(), 7);
|
||||
|
||||
// The stream stopped, so the clock is back at -1.
|
||||
let mut secs = 0.0f64;
|
||||
unsafe { oakaudio_manager_seconds(m, &mut secs) };
|
||||
m.seconds(&mut secs).unwrap();
|
||||
assert_eq!(secs, -1.0);
|
||||
|
||||
unsafe { oakaudio_manager_destroy_instance() };
|
||||
}
|
||||
|
||||
/// set_output_notify_interval stores the interval; clear_buffered_output
|
||||
/// drops queued bytes, stop_output halts the stream, and reset_output_clock
|
||||
/// restarts the counter.
|
||||
/// set_output_notify_interval stores the interval (negative is rejected);
|
||||
/// clear_buffered_output drops queued bytes, stop_output halts the stream,
|
||||
/// and reset_output_clock restarts the counter.
|
||||
#[test]
|
||||
fn output_control_flags() {
|
||||
let _guard = lock();
|
||||
unsafe { oakaudio_manager_create_instance() };
|
||||
let m = instance();
|
||||
let _guard = lock_manager();
|
||||
fresh_instance();
|
||||
let mut m = instance().unwrap();
|
||||
|
||||
m.set_output_notify_interval(1024).unwrap();
|
||||
let err = m.set_output_notify_interval(-1).unwrap_err();
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_manager_set_output_notify_interval(m, 1024) },
|
||||
OAKAUDIO_OK
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_manager_set_output_notify_interval(m, -1) },
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_manager_clear_buffered_output(m) },
|
||||
OAKAUDIO_OK
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_manager_reset_output_clock(m) },
|
||||
OAKAUDIO_OK
|
||||
err.downcast_ref::<oakaudio::error::Error>().map(|e| e.code()),
|
||||
Some(OAKAUDIO_E_INVALID)
|
||||
);
|
||||
m.clear_buffered_output().unwrap();
|
||||
m.reset_output_clock().unwrap();
|
||||
|
||||
// Push starts the stream, then stop_output halts it (clock -> -1).
|
||||
unsafe { oakaudio_manager_set_output_device(m, 0) };
|
||||
m.set_output_device(0).unwrap();
|
||||
let samples = vec![0u8; 480 * 2 * 4];
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
oakaudio_manager_push_to_output(
|
||||
m,
|
||||
48000,
|
||||
3,
|
||||
4,
|
||||
samples.as_ptr() as *const c_char,
|
||||
samples.len() as i64,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
)
|
||||
},
|
||||
OAKAUDIO_OK
|
||||
);
|
||||
assert_eq!(unsafe { oakaudio_manager_stop_output(m) }, OAKAUDIO_OK);
|
||||
m.push_to_output(stereo(), &samples, &mut vec![0u8; 64]).unwrap();
|
||||
m.stop_output().unwrap();
|
||||
let mut secs = 1.0f64;
|
||||
unsafe { oakaudio_manager_seconds(m, &mut secs) };
|
||||
m.seconds(&mut secs).unwrap();
|
||||
assert_eq!(secs, -1.0);
|
||||
|
||||
unsafe { oakaudio_manager_destroy_instance() };
|
||||
}
|
||||
|
||||
/// start_recording validates its parameters: NULL params or a disabled
|
||||
/// audio track return OAKAUDIO_E_INVALID with an error string. The full
|
||||
/// encoder-open success path (oakcodec writes a real file via ffmpeg) is
|
||||
/// an end-to-end concern covered by the codec crate's own tests; with the
|
||||
/// real oakcodec linked, `start_recording` either opens the encoder
|
||||
/// (OAKAUDIO_OK, environment-dependent) or reports the encoder's
|
||||
/// last-error string — both are correct manager behavior, so this test
|
||||
/// pins the manager's own validation only.
|
||||
/// start_recording validates its state: with no input device it fails with
|
||||
/// a reason; with a device the encoder open either succeeds (OAKAUDIO_OK,
|
||||
/// environment-dependent) or reports the encoder's diagnostic — both are
|
||||
/// correct manager behavior, so the test pins the manager's own handling
|
||||
/// only.
|
||||
#[test]
|
||||
fn recording_start_stop() {
|
||||
let _guard = lock();
|
||||
unsafe { oakaudio_manager_create_instance() };
|
||||
let m = instance();
|
||||
unsafe { oakaudio_manager_set_input_device(m, 0) };
|
||||
let _guard = lock_manager();
|
||||
fresh_instance();
|
||||
let mut m = instance().unwrap();
|
||||
|
||||
let mut err = [0 as c_char; 64];
|
||||
let params = encoding_params();
|
||||
// With a real encoder, the attempt must at least reach the encoder
|
||||
// (a failure must surface a diagnostic in error_buf, not crash).
|
||||
let r =
|
||||
unsafe { oakaudio_manager_start_recording(m, ¶ms, err.as_mut_ptr(), err.len() as i32) };
|
||||
if r != 0 {
|
||||
assert!(
|
||||
err.iter().any(|&b| b != 0),
|
||||
"failed start_recording must report a reason"
|
||||
);
|
||||
let _ = std::fs::remove_file("oakaudio_test.wav");
|
||||
} else {
|
||||
assert_eq!(unsafe { oakaudio_manager_stop_recording(m) }, OAKAUDIO_OK);
|
||||
// The real encoder writes the output file during open; clean it up.
|
||||
let _ = std::fs::remove_file("oakaudio_test.wav");
|
||||
// No input device -> explainable failure, no crash.
|
||||
m.set_input_device(-1).unwrap();
|
||||
assert!(m.start_recording(&wav_params("unused.wav"), &mut vec![0u8; 64]).is_err());
|
||||
|
||||
m.set_input_device(0).unwrap();
|
||||
let path = std::env::temp_dir().join(format!("oakaudio_rec_{}.wav", std::process::id()));
|
||||
let filename = path.to_str().unwrap();
|
||||
let mut err = vec![0u8; 256];
|
||||
match m.start_recording(&wav_params(filename), &mut err) {
|
||||
Ok(()) => {
|
||||
assert!(m.stop_recording().is_ok());
|
||||
}
|
||||
Err(e) => {
|
||||
assert!(!e.to_string().is_empty(), "failure must carry a reason");
|
||||
}
|
||||
}
|
||||
|
||||
// NULL params is invalid and reports the reason in error_buf.
|
||||
let mut err = [0 as c_char; 64];
|
||||
let r = unsafe {
|
||||
oakaudio_manager_start_recording(m, std::ptr::null(), err.as_mut_ptr(), err.len() as i32)
|
||||
};
|
||||
assert_eq!(r, OAKAUDIO_E_INVALID);
|
||||
assert!(err.iter().any(|&b| b != 0));
|
||||
|
||||
// A disabled audio track is likewise invalid.
|
||||
let mut disabled = encoding_params();
|
||||
disabled.audio_enabled = 0;
|
||||
let mut err = [0 as c_char; 64];
|
||||
let r = unsafe {
|
||||
oakaudio_manager_start_recording(m, &disabled, err.as_mut_ptr(), err.len() as i32)
|
||||
};
|
||||
assert_eq!(r, OAKAUDIO_E_INVALID);
|
||||
assert!(err.iter().any(|&b| b != 0));
|
||||
|
||||
unsafe { oakaudio_manager_destroy_instance() };
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
|
||||
/// Device enumeration is not bridged: every name/config lookup falls back to
|
||||
/// paNoDevice (-1); a NULL name is OAKAUDIO_E_INVALID. The config-backed
|
||||
/// buffer size/name helpers degrade to their defaults.
|
||||
/// Config defaults are read from the (empty) oakcommon store: buffer size
|
||||
/// falls back to 0 and device names are absent.
|
||||
#[test]
|
||||
fn device_name_lookup() {
|
||||
let _guard = lock();
|
||||
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_manager_find_device_by_name_s(std::ptr::null(), 1) },
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
let name = c"anything";
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_manager_find_device_by_name_s(name.as_ptr(), 1) },
|
||||
-1
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_manager_find_config_device_by_name_s(1) },
|
||||
-1
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_manager_find_config_device_by_name_s(0) },
|
||||
-1
|
||||
);
|
||||
|
||||
// config::output_buffer_size() reads its default (0) from the stub;
|
||||
// device_name degrades to the empty string.
|
||||
fn config_defaults() {
|
||||
assert_eq!(oakaudio::config::output_buffer_size(), 0);
|
||||
assert!(oakaudio::config::device_name(true).as_c_str().is_empty());
|
||||
assert!(oakaudio::config::device_name(false).as_c_str().is_empty());
|
||||
assert!(oakaudio::config::device_name(true).is_err(), "no configured output device");
|
||||
assert!(oakaudio::config::device_name(false).is_err(), "no configured input device");
|
||||
}
|
||||
|
||||
/// PreviewAudioDevice pull-side plumbing (read/notify callback/clock) that
|
||||
/// the manager path only touches indirectly.
|
||||
/// PreviewAudioDevice pull-side plumbing (read/notify callback/clock).
|
||||
#[test]
|
||||
fn preview_device_pull_side() {
|
||||
use oakaudio::params::AudioParams;
|
||||
use oakaudio::previewdevice::PreviewAudioDevice;
|
||||
|
||||
let mut dev = PreviewAudioDevice::new();
|
||||
dev.set_params(AudioParams {
|
||||
sample_rate: 48000,
|
||||
channel_layout: 3,
|
||||
format: oakaudio::params::SampleFormat::F32,
|
||||
format: SampleFormat::F32,
|
||||
});
|
||||
assert_eq!(dev.bytes_per_frame(), 8);
|
||||
|
||||
@@ -389,85 +233,65 @@ fn preview_device_pull_side() {
|
||||
assert_eq!(dev.output_frames_consumed(), 0);
|
||||
}
|
||||
|
||||
/// free(NULL)/free(empty) are no-ops on the manager handle.
|
||||
#[test]
|
||||
fn free_null_noop() {
|
||||
let _guard = lock();
|
||||
unsafe { oakaudio_manager_create_instance() };
|
||||
let before = unsafe { oakaudio_debug_alive_count() };
|
||||
|
||||
let mut empty = oakaudio::handle::CHandle::null();
|
||||
unsafe { oakaudio_manager_free(&mut empty) };
|
||||
unsafe { oakaudio_manager_free(std::ptr::null_mut()) };
|
||||
assert_eq!(unsafe { oakaudio_debug_alive_count() }, before);
|
||||
|
||||
unsafe { oakaudio_manager_destroy_instance() };
|
||||
}
|
||||
|
||||
/// output_levels: validation, the no-output case, and a real peak
|
||||
/// readback over pushed packed-F32 stereo samples (left ramps to 0.25,
|
||||
/// right to ~1.0 — the per-channel linear peaks).
|
||||
/// output_levels: the no-output case, and a real peak readback over pushed
|
||||
/// packed-F32 stereo samples (left ramps to 0.05, right to ~0.2 — the
|
||||
/// per-channel linear peaks).
|
||||
///
|
||||
/// The push can open a real cpal stream whose callback consumes queued
|
||||
/// samples concurrently, so a long ramp is pushed and the peaks are
|
||||
/// asserted with a tolerance that absorbs partial consumption (the
|
||||
/// analysis window is the most recent 8192 frames of the queue).
|
||||
#[test]
|
||||
fn output_levels_reports_buffered_peaks() {
|
||||
let _guard = lock();
|
||||
unsafe { oakaudio_manager_destroy_instance() };
|
||||
assert_eq!(unsafe { oakaudio_manager_create_instance() }, OAKAUDIO_OK);
|
||||
let m = instance();
|
||||
let _guard = lock_manager();
|
||||
fresh_instance();
|
||||
let mut m = instance().unwrap();
|
||||
|
||||
// Nothing configured yet: no channels.
|
||||
assert_eq!(m.output_levels(&mut [0.0f32; 4]).unwrap(), 0);
|
||||
|
||||
m.set_output_device(42).unwrap();
|
||||
m.clear_buffered_output().unwrap();
|
||||
|
||||
// Push 2 seconds of packed F32 stereo ramp (format 10), stereo layout
|
||||
// 0x3. Left ramps 0 -> 0.05, right 0 -> 0.2.
|
||||
let frames = 96000usize;
|
||||
let mut packed = Vec::with_capacity(frames * 2 * 4);
|
||||
for i in 0..frames {
|
||||
let t = i as f32 / frames as f32;
|
||||
packed.extend_from_slice(&(0.05f32 * t).to_le_bytes());
|
||||
packed.extend_from_slice(&(0.2f32 * t).to_le_bytes());
|
||||
}
|
||||
m.push_to_output(stereo(), &packed, &mut vec![0u8; 64]).unwrap();
|
||||
|
||||
// Invalid out args.
|
||||
let mut peaks = [0.0f32; 4];
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_manager_output_levels(m, std::ptr::null_mut(), 4) },
|
||||
OAKAUDIO_E_INVALID
|
||||
let n = m.output_levels(&mut peaks).unwrap();
|
||||
assert_eq!(n, 2);
|
||||
assert!(
|
||||
(peaks[0] - 0.05).abs() < 1e-3 && peaks[0] > 0.04,
|
||||
"left peak: {}",
|
||||
peaks[0]
|
||||
);
|
||||
assert!(
|
||||
(peaks[1] - 0.2).abs() < 1e-3 && peaks[1] > 0.19,
|
||||
"right peak: {}",
|
||||
peaks[1]
|
||||
);
|
||||
assert_eq!(unsafe { oakaudio_manager_output_levels(m, peaks.as_mut_ptr(), 0) }, OAKAUDIO_E_INVALID);
|
||||
|
||||
// The manager singleton retains output params across tests in this
|
||||
// binary, so the "no output" case is not reachable here; instead
|
||||
// verify a cleared buffer reports zeroed peaks (channel count from
|
||||
// the configured layout, 0 only when nothing was ever configured).
|
||||
assert_eq!(unsafe { oakaudio_manager_set_output_device(m, 42) }, OAKAUDIO_OK);
|
||||
assert_eq!(unsafe { oakaudio_manager_clear_buffered_output(m) }, OAKAUDIO_OK);
|
||||
let cleared = unsafe { oakaudio_manager_output_levels(m, peaks.as_mut_ptr(), 4) };
|
||||
assert!(cleared >= 0);
|
||||
for p in &peaks[..cleared as usize] {
|
||||
// A cleared buffer reports zeroed peaks over the configured channels.
|
||||
m.clear_buffered_output().unwrap();
|
||||
let mut cleared = [0.0f32; 4];
|
||||
assert_eq!(m.output_levels(&mut cleared).unwrap(), 2);
|
||||
for p in &cleared[..2] {
|
||||
assert_eq!(*p, 0.0, "cleared buffer must have silent peaks");
|
||||
}
|
||||
|
||||
// Push 480 frames of packed F32 stereo (format 10), stereo layout 0x3.
|
||||
let frames = 480usize;
|
||||
let mut samples = Vec::with_capacity(frames * 2);
|
||||
for i in 0..frames {
|
||||
let t = i as f32 / frames as f32;
|
||||
samples.push(0.25f32 * t);
|
||||
samples.push(t);
|
||||
}
|
||||
let rc = unsafe {
|
||||
oakaudio_manager_push_to_output(
|
||||
m,
|
||||
48000,
|
||||
0x3,
|
||||
10,
|
||||
samples.as_ptr() as *const c_char,
|
||||
(samples.len() * 4) as i64,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
)
|
||||
};
|
||||
assert_eq!(rc, OAKAUDIO_OK);
|
||||
|
||||
let n = unsafe { oakaudio_manager_output_levels(m, peaks.as_mut_ptr(), 4) };
|
||||
assert_eq!(n, 2);
|
||||
let last = (frames - 1) as f32 / frames as f32;
|
||||
assert!((peaks[0] - 0.25 * last).abs() < 1e-6, "left peak: {}", peaks[0]);
|
||||
assert!((peaks[1] - last).abs() < 1e-6, "right peak: {}", peaks[1]);
|
||||
|
||||
// Undersized buffer truncates the write, not the reported count.
|
||||
let mut one = [0.0f32; 1];
|
||||
assert_eq!(unsafe { oakaudio_manager_output_levels(m, one.as_mut_ptr(), 1) }, 2);
|
||||
// The error mapping is intact.
|
||||
assert_eq!(Error::Invalid.code(), OAKAUDIO_E_INVALID);
|
||||
assert_eq!(Error::Failed("x".to_string()).code(), oakaudio::error::OAKAUDIO_E_FAILED);
|
||||
|
||||
// Leave the singleton as we found it: the push flipped
|
||||
// `output_started`, which other tests' seconds() assertions depend on.
|
||||
assert_eq!(unsafe { oakaudio_manager_stop_output(m) }, OAKAUDIO_OK);
|
||||
assert_eq!(unsafe { oakaudio_manager_clear_buffered_output(m) }, OAKAUDIO_OK);
|
||||
m.stop_output().unwrap();
|
||||
m.clear_buffered_output().unwrap();
|
||||
}
|
||||
|
||||
@@ -14,20 +14,15 @@
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! AudioProcessor contract tests (processor.rs), through the C ABI. The
|
||||
//! conversion runs a real FFmpeg filter graph (aresample/aformat/atempo),
|
||||
//! so resampling and time-stretch have filter latency: the exact frame
|
||||
//! counts are drained after `flush`, while identity conversion is an
|
||||
//! immediate passthrough.
|
||||
//! AudioProcessor contract tests (processor.rs), calling the public Rust
|
||||
//! API. The conversion runs a real FFmpeg filter graph
|
||||
//! (aresample/aformat/atempo), so resampling and time-stretch have filter
|
||||
//! latency: the exact frame counts are drained after `flush`, while
|
||||
//! identity conversion is an immediate passthrough.
|
||||
|
||||
mod common;
|
||||
|
||||
use oakaudio::error::{OAKAUDIO_E_INVALID, OAKAUDIO_E_STATE, OAKAUDIO_OK};
|
||||
use oakaudio::ffi::processor::{
|
||||
oakaudio_processor_close, oakaudio_processor_convert, oakaudio_processor_flush,
|
||||
oakaudio_processor_free, oakaudio_processor_init, oakaudio_processor_is_open,
|
||||
oakaudio_processor_open,
|
||||
};
|
||||
use oakaudio::error::{Error, OAKAUDIO_E_INVALID, OAKAUDIO_E_STATE, OAKAUDIO_OK};
|
||||
use oakaudio::params::{AudioParams, SampleFormat};
|
||||
use oakaudio::processor::Processor;
|
||||
|
||||
/// Stereo f32_p planes of `frames` ramp samples.
|
||||
fn ramp_planes(frames: usize) -> Vec<Vec<f32>> {
|
||||
@@ -37,37 +32,61 @@ fn ramp_planes(frames: usize) -> Vec<Vec<f32>> {
|
||||
]
|
||||
}
|
||||
|
||||
fn open_identity(h: oakaudio::handle::CHandle) -> i32 {
|
||||
unsafe { oakaudio_processor_open(h, 48000, 3, 4, 48000, 3, 4, 1.0) }
|
||||
/// Stereo planar-f32 params at `rate`.
|
||||
fn params(rate: i32) -> AudioParams {
|
||||
AudioParams {
|
||||
sample_rate: rate,
|
||||
channel_layout: 0x3,
|
||||
format: SampleFormat::F32Planar,
|
||||
}
|
||||
}
|
||||
|
||||
/// init yields a valid handle; is_open is false before open and true after;
|
||||
/// close returns it to closed without error.
|
||||
fn open_identity(p: &Processor) -> Result<(), Box<dyn std::error::Error>> {
|
||||
p.open(params(48000), params(48000), 1.0)
|
||||
}
|
||||
|
||||
/// Pointer arrays for the convert call.
|
||||
fn plane_ptrs(planes: &[Vec<f32>]) -> Vec<*const f32> {
|
||||
planes.iter().map(|p| p.as_ptr()).collect()
|
||||
}
|
||||
|
||||
fn plane_mut_ptrs(planes: &mut [Vec<f32>]) -> Vec<*mut f32> {
|
||||
planes.iter_mut().map(|p| p.as_mut_ptr()).collect()
|
||||
}
|
||||
|
||||
/// The crate error code of a failed call (the API surfaces
|
||||
/// `Box<dyn std::error::Error>`).
|
||||
fn code(err: Box<dyn std::error::Error>) -> i32 {
|
||||
err.downcast_ref::<oakaudio::error::Error>()
|
||||
.map(|e| e.code())
|
||||
.unwrap_or(-1)
|
||||
}
|
||||
|
||||
/// init yields a closed processor; is_open is false before open and true
|
||||
/// after; close returns it to closed without error.
|
||||
#[test]
|
||||
fn processor_open_isopen_close() {
|
||||
let mut h = unsafe { oakaudio_processor_init() };
|
||||
assert!(!h.ctx.is_null());
|
||||
assert_eq!(unsafe { oakaudio_processor_is_open(h) }, 0);
|
||||
assert_eq!(open_identity(h), OAKAUDIO_OK);
|
||||
assert_eq!(unsafe { oakaudio_processor_is_open(h) }, 1);
|
||||
assert_eq!(unsafe { oakaudio_processor_close(h) }, OAKAUDIO_OK);
|
||||
assert_eq!(unsafe { oakaudio_processor_is_open(h) }, 0);
|
||||
unsafe { oakaudio_processor_free(&mut h) };
|
||||
let p = Processor::init();
|
||||
assert_eq!(p.is_open().unwrap(), false);
|
||||
open_identity(&p).unwrap();
|
||||
assert_eq!(p.is_open().unwrap(), true);
|
||||
p.close().unwrap();
|
||||
assert_eq!(p.is_open().unwrap(), false);
|
||||
}
|
||||
|
||||
/// open with matching in/out rate and format is an identity passthrough:
|
||||
/// convert returns the same frame count and samples within 1e-6.
|
||||
#[test]
|
||||
fn identity_convert_passthrough() {
|
||||
let mut h = unsafe { oakaudio_processor_init() };
|
||||
assert_eq!(open_identity(h), OAKAUDIO_OK);
|
||||
let p = Processor::init();
|
||||
open_identity(&p).unwrap();
|
||||
|
||||
let planes = ramp_planes(32);
|
||||
let in_ptrs: Vec<*const f32> = planes.iter().map(|p| p.as_ptr()).collect();
|
||||
let in_ptrs = plane_ptrs(&planes);
|
||||
let mut out = vec![vec![0f32; 32]; 2];
|
||||
let mut out_ptrs: Vec<*mut f32> = out.iter_mut().map(|p| p.as_mut_ptr()).collect();
|
||||
let mut out_ptrs = plane_mut_ptrs(&mut out);
|
||||
|
||||
let n = unsafe { oakaudio_processor_convert(h, in_ptrs.as_ptr(), 32, out_ptrs.as_ptr(), 32) };
|
||||
let n = p.convert(in_ptrs.as_ptr(), 32, out_ptrs.as_ptr(), 32).unwrap();
|
||||
assert_eq!(n, 32);
|
||||
for ch in 0..2 {
|
||||
for i in 0..32 {
|
||||
@@ -79,22 +98,21 @@ fn identity_convert_passthrough() {
|
||||
);
|
||||
}
|
||||
}
|
||||
unsafe { oakaudio_processor_free(&mut h) };
|
||||
}
|
||||
|
||||
/// convert with an output capacity smaller than the produced frames returns
|
||||
/// the produced count clamped to capacity and fills up to capacity.
|
||||
#[test]
|
||||
fn convert_capacity_truncation() {
|
||||
let mut h = unsafe { oakaudio_processor_init() };
|
||||
assert_eq!(open_identity(h), OAKAUDIO_OK);
|
||||
let p = Processor::init();
|
||||
open_identity(&p).unwrap();
|
||||
|
||||
let planes = ramp_planes(32);
|
||||
let in_ptrs: Vec<*const f32> = planes.iter().map(|p| p.as_ptr()).collect();
|
||||
let in_ptrs = plane_ptrs(&planes);
|
||||
let mut out = vec![vec![9.9f32; 10]; 2];
|
||||
let mut out_ptrs: Vec<*mut f32> = out.iter_mut().map(|p| p.as_mut_ptr()).collect();
|
||||
let mut out_ptrs = plane_mut_ptrs(&mut out);
|
||||
|
||||
let n = unsafe { oakaudio_processor_convert(h, in_ptrs.as_ptr(), 32, out_ptrs.as_ptr(), 10) };
|
||||
let n = p.convert(in_ptrs.as_ptr(), 32, out_ptrs.as_ptr(), 10).unwrap();
|
||||
assert_eq!(n, 10);
|
||||
for ch in 0..2 {
|
||||
for i in 0..10 {
|
||||
@@ -104,56 +122,40 @@ fn convert_capacity_truncation() {
|
||||
|
||||
// The graph has already drained; nothing further to pull.
|
||||
let mut out2 = vec![vec![0f32; 32]; 2];
|
||||
let mut out2_ptrs: Vec<*mut f32> = out2.iter_mut().map(|p| p.as_mut_ptr()).collect();
|
||||
let n = unsafe { oakaudio_processor_convert(h, in_ptrs.as_ptr(), 0, out2_ptrs.as_ptr(), 32) };
|
||||
let mut out2_ptrs = plane_mut_ptrs(&mut out2);
|
||||
let n = p.convert(in_ptrs.as_ptr(), 0, out2_ptrs.as_ptr(), 32).unwrap();
|
||||
assert_eq!(n, 0);
|
||||
|
||||
unsafe { oakaudio_processor_free(&mut h) };
|
||||
}
|
||||
|
||||
/// open with a zero/negative rate or a wrong output format returns
|
||||
/// OAKAUDIO_E_INVALID and leaves the processor closed; an empty handle is
|
||||
/// OAKAUDIO_E_INVALID everywhere.
|
||||
/// open with a zero/negative rate or a wrong output format is rejected and
|
||||
/// leaves the processor closed; convert before open is a state error.
|
||||
#[test]
|
||||
fn open_invalid_params() {
|
||||
let mut h = unsafe { oakaudio_processor_init() };
|
||||
let p = Processor::init();
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_processor_open(h, 0, 3, 4, 48000, 3, 4, 1.0) },
|
||||
code(p.open(params(0), params(48000), 1.0).unwrap_err()),
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
assert_eq!(unsafe { oakaudio_processor_is_open(h) }, 0);
|
||||
assert_eq!(p.is_open().unwrap(), false);
|
||||
// The output format is forced to planar f32 by the processor contract.
|
||||
let mut wrong_out = params(48000);
|
||||
wrong_out.format = SampleFormat::F32;
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_processor_open(h, 48000, 3, 4, 48000, 3, 0, 1.0) },
|
||||
code(p.open(params(48000), wrong_out, 1.0).unwrap_err()),
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
assert_eq!(unsafe { oakaudio_processor_is_open(h) }, 0);
|
||||
assert_eq!(p.is_open().unwrap(), false);
|
||||
|
||||
let empty = oakaudio::handle::CHandle::null();
|
||||
assert_eq!(open_identity(empty), OAKAUDIO_E_INVALID);
|
||||
// convert before open is a state error; a non-positive speed is
|
||||
// rejected on open.
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_processor_is_open(empty) },
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_processor_close(empty) },
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_processor_flush(empty) },
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
let mut out_ptrs: Vec<*mut f32> = Vec::new();
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_processor_convert(empty, std::ptr::null(), 0, out_ptrs.as_ptr(), 0) },
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
|
||||
// convert before open is a state error.
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_processor_convert(h, std::ptr::null(), 0, out_ptrs.as_ptr(), 0) },
|
||||
code(p.convert(std::ptr::null(), 0, std::ptr::null(), 0).unwrap_err()),
|
||||
OAKAUDIO_E_STATE
|
||||
);
|
||||
unsafe { oakaudio_processor_free(&mut h) };
|
||||
assert_eq!(
|
||||
code(p.open(params(48000), params(48000), 0.0).unwrap_err()),
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
}
|
||||
|
||||
/// Resampling to half rate halves the frame count (44100 -> 22050). The
|
||||
@@ -161,34 +163,23 @@ fn open_invalid_params() {
|
||||
/// drained after `flush`; flush then keeps the processor open.
|
||||
#[test]
|
||||
fn resample_and_flush() {
|
||||
let mut h = unsafe { oakaudio_processor_init() };
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_processor_open(h, 44100, 3, 4, 22050, 3, 4, 1.0) },
|
||||
OAKAUDIO_OK
|
||||
);
|
||||
let p = Processor::init();
|
||||
p.open(params(44100), params(22050), 1.0).unwrap();
|
||||
|
||||
// 1 second of input keeps the resampler delay well below the signal.
|
||||
let frames = 44100;
|
||||
let planes = ramp_planes(frames);
|
||||
let in_ptrs: Vec<*const f32> = planes.iter().map(|p| p.as_ptr()).collect();
|
||||
let in_ptrs = plane_ptrs(&planes);
|
||||
let mut out = vec![vec![0f32; frames]; 2];
|
||||
let mut out_ptrs: Vec<*mut f32> = out.iter_mut().map(|p| p.as_mut_ptr()).collect();
|
||||
let mut out_ptrs = plane_mut_ptrs(&mut out);
|
||||
|
||||
let mut total = unsafe {
|
||||
oakaudio_processor_convert(
|
||||
h,
|
||||
in_ptrs.as_ptr(),
|
||||
frames as i32,
|
||||
out_ptrs.as_ptr(),
|
||||
frames as i32,
|
||||
)
|
||||
};
|
||||
assert_eq!(unsafe { oakaudio_processor_flush(h) }, OAKAUDIO_OK);
|
||||
let mut total = p
|
||||
.convert(in_ptrs.as_ptr(), frames as i32, out_ptrs.as_ptr(), frames as i32)
|
||||
.unwrap();
|
||||
p.flush().unwrap();
|
||||
// Drain the resampler delay after end-of-input.
|
||||
while total < frames as i32 {
|
||||
let n = unsafe {
|
||||
oakaudio_processor_convert(h, std::ptr::null(), 0, out_ptrs.as_ptr(), frames as i32)
|
||||
};
|
||||
let n = p.convert(std::ptr::null(), 0, out_ptrs.as_ptr(), frames as i32).unwrap();
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
@@ -198,8 +189,7 @@ fn resample_and_flush() {
|
||||
(total - 22050).abs() <= 2,
|
||||
"half-rate output must halve the frame count (got {total})"
|
||||
);
|
||||
assert_eq!(unsafe { oakaudio_processor_is_open(h) }, 1);
|
||||
unsafe { oakaudio_processor_free(&mut h) };
|
||||
assert_eq!(p.is_open().unwrap(), true);
|
||||
}
|
||||
|
||||
/// A tempo factor != 1.0 time-stretches: tempo 2.0 halves the frame count
|
||||
@@ -207,33 +197,22 @@ fn resample_and_flush() {
|
||||
/// produces output) and the processor stays open.
|
||||
#[test]
|
||||
fn tempo_stretch() {
|
||||
let mut h = unsafe { oakaudio_processor_init() };
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_processor_open(h, 48000, 3, 4, 48000, 3, 4, 2.0) },
|
||||
OAKAUDIO_OK
|
||||
);
|
||||
let p = Processor::init();
|
||||
p.open(params(48000), params(48000), 2.0).unwrap();
|
||||
|
||||
// 1 second of input: many atempo windows (1024 samples at 48 kHz).
|
||||
let frames = 48000;
|
||||
let planes = ramp_planes(frames);
|
||||
let in_ptrs: Vec<*const f32> = planes.iter().map(|p| p.as_ptr()).collect();
|
||||
let in_ptrs = plane_ptrs(&planes);
|
||||
let mut out = vec![vec![0f32; frames]; 2];
|
||||
let mut out_ptrs: Vec<*mut f32> = out.iter_mut().map(|p| p.as_mut_ptr()).collect();
|
||||
let mut out_ptrs = plane_mut_ptrs(&mut out);
|
||||
|
||||
let mut total = unsafe {
|
||||
oakaudio_processor_convert(
|
||||
h,
|
||||
in_ptrs.as_ptr(),
|
||||
frames as i32,
|
||||
out_ptrs.as_ptr(),
|
||||
frames as i32,
|
||||
)
|
||||
};
|
||||
assert_eq!(unsafe { oakaudio_processor_flush(h) }, OAKAUDIO_OK);
|
||||
let mut total = p
|
||||
.convert(in_ptrs.as_ptr(), frames as i32, out_ptrs.as_ptr(), frames as i32)
|
||||
.unwrap();
|
||||
p.flush().unwrap();
|
||||
while total < frames as i32 {
|
||||
let n = unsafe {
|
||||
oakaudio_processor_convert(h, std::ptr::null(), 0, out_ptrs.as_ptr(), frames as i32)
|
||||
};
|
||||
let n = p.convert(std::ptr::null(), 0, out_ptrs.as_ptr(), frames as i32).unwrap();
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
@@ -243,24 +222,20 @@ fn tempo_stretch() {
|
||||
(total - 24000).abs() <= 2400,
|
||||
"tempo 2.0 must halve the frame count (got {total})"
|
||||
);
|
||||
assert_eq!(unsafe { oakaudio_processor_is_open(h) }, 1);
|
||||
unsafe { oakaudio_processor_close(h) };
|
||||
assert_eq!(p.is_open().unwrap(), true);
|
||||
p.close().unwrap();
|
||||
|
||||
// A non-positive speed is rejected (on a closed processor).
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_processor_open(h, 48000, 3, 4, 48000, 3, 4, 0.0) },
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
assert_eq!(open_identity(h), OAKAUDIO_OK);
|
||||
// Already open -> state error.
|
||||
assert_eq!(open_identity(h), OAKAUDIO_E_STATE);
|
||||
unsafe { oakaudio_processor_free(&mut h) };
|
||||
// Re-opening a closed processor works; opening an open one is a state
|
||||
// error.
|
||||
open_identity(&p).unwrap();
|
||||
assert_eq!(code(open_identity(&p).unwrap_err()), OAKAUDIO_E_STATE);
|
||||
}
|
||||
|
||||
/// free(NULL)/free(empty) are no-ops.
|
||||
/// The error mapping is intact.
|
||||
#[test]
|
||||
fn free_null_noop() {
|
||||
let mut h = oakaudio::handle::CHandle::null();
|
||||
unsafe { oakaudio_processor_free(&mut h) };
|
||||
unsafe { oakaudio_processor_free(std::ptr::null_mut()) };
|
||||
fn error_codes() {
|
||||
assert_eq!(Error::Invalid.code(), OAKAUDIO_E_INVALID);
|
||||
assert_eq!(Error::State.code(), OAKAUDIO_E_STATE);
|
||||
assert_eq!(Error::Failed("x".to_string()).code(), -60003);
|
||||
assert_eq!(oakaudio::error::OAKAUDIO_OK, OAKAUDIO_OK);
|
||||
}
|
||||
|
||||
@@ -15,24 +15,22 @@
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! AudioSynchronizer + AudioWaveformSync contract tests
|
||||
//! (synchronizer.rs, waveformsync.rs), through the C ABI.
|
||||
//! (synchronizer.rs, waveformsync.rs), calling the public Rust API.
|
||||
|
||||
mod common;
|
||||
|
||||
use oakaudio::error::OAKAUDIO_E_INVALID;
|
||||
use oakaudio::ffi::sync::{
|
||||
oakaudio_sync_estimate_envelope_offset, oakaudio_sync_estimate_stretch_and_offset,
|
||||
oakaudio_sync_extract_rms_envelope, oakaudio_sync_place_by_source_time,
|
||||
oakaudio_sync_place_by_waveform_offset, OffsetResult, SourceClip, StretchOffsetResult,
|
||||
use oakcore_rs::Rational;
|
||||
use oakaudio::synchronizer::{place_by_source_time, place_by_waveform_offset, SourceClip};
|
||||
use oakaudio::waveformsync::{
|
||||
estimate_envelope_offset, estimate_envelope_offset_valid, estimate_stretch_and_offset,
|
||||
extract_rms_envelope,
|
||||
};
|
||||
|
||||
fn clip(source: i64, media_in: i64, has_source: bool) -> SourceClip {
|
||||
SourceClip {
|
||||
source_start_time_num: source,
|
||||
source_start_time_den: 1,
|
||||
media_in_num: media_in,
|
||||
media_in_den: 1,
|
||||
has_source_start_time: has_source as i32,
|
||||
source_start_time: Rational::new(source, 1),
|
||||
media_in: Rational::new(media_in, 1),
|
||||
has_source_start_time: has_source,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,28 +41,15 @@ fn clip(source: i64, media_in: i64, has_source: bool) -> SourceClip {
|
||||
fn place_by_source_time_matching() {
|
||||
let reference = clip(0, 0, true);
|
||||
let candidate = clip(0, 0, true);
|
||||
let (mut num, mut den, mut valid) = (0i64, 0i64, 0i32);
|
||||
let r = unsafe {
|
||||
oakaudio_sync_place_by_source_time(
|
||||
&reference, &candidate, 5, 1, &mut num, &mut den, &mut valid,
|
||||
)
|
||||
};
|
||||
assert_eq!(r, 0);
|
||||
assert_eq!(num, 5);
|
||||
assert_eq!(den, 1);
|
||||
assert_eq!(valid, 1);
|
||||
let placement = place_by_source_time(&reference, &candidate, Rational::new(5, 1));
|
||||
assert!(placement.valid);
|
||||
assert_eq!(placement.timeline_in, Rational::new(5, 1));
|
||||
|
||||
// A source-less candidate is invalid: valid=0, null rational.
|
||||
// A source-less candidate is invalid: valid=false, null rational.
|
||||
let candidate = clip(0, 0, false);
|
||||
let r = unsafe {
|
||||
oakaudio_sync_place_by_source_time(
|
||||
&reference, &candidate, 5, 1, &mut num, &mut den, &mut valid,
|
||||
)
|
||||
};
|
||||
assert_eq!(r, 0);
|
||||
assert_eq!(valid, 0);
|
||||
assert_eq!(num, 0);
|
||||
assert_eq!(den, 0);
|
||||
let placement = place_by_source_time(&reference, &candidate, Rational::new(5, 1));
|
||||
assert!(!placement.valid);
|
||||
assert!(placement.timeline_in.is_null());
|
||||
}
|
||||
|
||||
/// place_by_source_time: when source times disagree by a known delta, the
|
||||
@@ -73,62 +58,28 @@ fn place_by_source_time_matching() {
|
||||
fn place_by_source_time_delta() {
|
||||
let reference = clip(5, 0, true);
|
||||
let candidate = clip(12, 0, true);
|
||||
let (mut num, mut den, mut valid) = (0i64, 0i64, 0i32);
|
||||
let r = unsafe {
|
||||
oakaudio_sync_place_by_source_time(
|
||||
&reference, &candidate, 0, 1, &mut num, &mut den, &mut valid,
|
||||
)
|
||||
};
|
||||
assert_eq!(r, 0);
|
||||
let placement = place_by_source_time(&reference, &candidate, Rational::new(0, 1));
|
||||
// 0 + (12 + 0) - (5 + 0) = 7
|
||||
assert_eq!(num, 7);
|
||||
assert_eq!(den, 1);
|
||||
assert_eq!(valid, 1);
|
||||
|
||||
// A zero denominator is rejected up front.
|
||||
let r = unsafe {
|
||||
oakaudio_sync_place_by_source_time(
|
||||
&reference, &candidate, 0, 0, &mut num, &mut den, &mut valid,
|
||||
)
|
||||
};
|
||||
assert_eq!(r, OAKAUDIO_E_INVALID);
|
||||
assert!(placement.valid);
|
||||
assert_eq!(placement.timeline_in, Rational::new(7, 1));
|
||||
}
|
||||
|
||||
/// place_by_waveform_offset converts a sample offset at a sample rate into
|
||||
/// a timeline-in shift; out_valid is 1 on success and 0 for a null rate.
|
||||
/// a timeline-in shift; out_valid is false for a null rate.
|
||||
#[test]
|
||||
fn place_by_waveform_offset_conversion() {
|
||||
let (mut num, mut den, mut valid) = (0i64, 0i64, 0i32);
|
||||
let r = unsafe {
|
||||
oakaudio_sync_place_by_waveform_offset(0, 1, 48000, 48000, &mut num, &mut den, &mut valid)
|
||||
};
|
||||
assert_eq!(r, 0);
|
||||
assert_eq!(num, 1);
|
||||
assert_eq!(den, 1);
|
||||
assert_eq!(valid, 1);
|
||||
let placement = place_by_waveform_offset(Rational::new(0, 1), 48000, 48000);
|
||||
assert!(placement.valid);
|
||||
assert_eq!(placement.timeline_in, Rational::new(1, 1));
|
||||
|
||||
let r = unsafe {
|
||||
oakaudio_sync_place_by_waveform_offset(1, 2, 48000, 48000, &mut num, &mut den, &mut valid)
|
||||
};
|
||||
assert_eq!(r, 0);
|
||||
assert_eq!(num, 3);
|
||||
assert_eq!(den, 2);
|
||||
assert_eq!(valid, 1);
|
||||
let placement = place_by_waveform_offset(Rational::new(1, 2), 48000, 48000);
|
||||
assert!(placement.valid);
|
||||
assert_eq!(placement.timeline_in, Rational::new(3, 2));
|
||||
|
||||
// A null rate is invalid (valid=0, null rational), and the FFI rejects
|
||||
// a zero timeline denominator.
|
||||
let r = unsafe {
|
||||
oakaudio_sync_place_by_waveform_offset(1, 2, 48000, 0, &mut num, &mut den, &mut valid)
|
||||
};
|
||||
assert_eq!(r, 0);
|
||||
assert_eq!(valid, 0);
|
||||
assert_eq!(num, 0);
|
||||
assert_eq!(den, 0);
|
||||
|
||||
let r = unsafe {
|
||||
oakaudio_sync_place_by_waveform_offset(1, 0, 48000, 48000, &mut num, &mut den, &mut valid)
|
||||
};
|
||||
assert_eq!(r, OAKAUDIO_E_INVALID);
|
||||
// A null rate is invalid (valid=false, null rational).
|
||||
let placement = place_by_waveform_offset(Rational::new(1, 2), 48000, 0);
|
||||
assert!(!placement.valid);
|
||||
assert!(placement.timeline_in.is_null());
|
||||
}
|
||||
|
||||
/// extract_rms_envelope produces one value per window; a window larger than
|
||||
@@ -137,85 +88,31 @@ fn place_by_waveform_offset_conversion() {
|
||||
fn extract_rms_envelope_shape() {
|
||||
let data: Vec<f32> = (0..100).map(|i| i as f32).collect();
|
||||
let planes = common::planar_from(&data, 2);
|
||||
let ptrs: Vec<*const f32> = planes.iter().map(|p| p.as_ptr()).collect();
|
||||
let refs: Vec<&[f32]> = planes.iter().map(Vec::as_slice).collect();
|
||||
|
||||
let mut out = vec![0.0f64; 16];
|
||||
let n = unsafe {
|
||||
oakaudio_sync_extract_rms_envelope(ptrs.as_ptr(), 2, 100, 10, out.as_mut_ptr(), 16)
|
||||
};
|
||||
assert_eq!(n, 10);
|
||||
assert!(out.iter().take(10).all(|&v| v > 0.0));
|
||||
let env = extract_rms_envelope(&refs, 10);
|
||||
assert_eq!(env.len(), 10);
|
||||
assert!(env.iter().all(|&v| v > 0.0));
|
||||
|
||||
let n = unsafe {
|
||||
oakaudio_sync_extract_rms_envelope(ptrs.as_ptr(), 2, 100, 200, out.as_mut_ptr(), 16)
|
||||
};
|
||||
assert_eq!(n, 1);
|
||||
|
||||
// Invalid inputs.
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
oakaudio_sync_extract_rms_envelope(std::ptr::null(), 2, 100, 10, out.as_mut_ptr(), 16)
|
||||
},
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
oakaudio_sync_extract_rms_envelope(ptrs.as_ptr(), 0, 100, 10, out.as_mut_ptr(), 16)
|
||||
},
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
oakaudio_sync_extract_rms_envelope(ptrs.as_ptr(), 2, 100, 0, out.as_mut_ptr(), 16)
|
||||
},
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
oakaudio_sync_extract_rms_envelope(ptrs.as_ptr(), 2, 100, 10, out.as_mut_ptr(), -1)
|
||||
},
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
// Two-stage: NULL out returns the required count.
|
||||
let n = unsafe {
|
||||
oakaudio_sync_extract_rms_envelope(ptrs.as_ptr(), 2, 100, 10, std::ptr::null_mut(), 0)
|
||||
};
|
||||
assert_eq!(n, 10);
|
||||
let env = extract_rms_envelope(&refs, 200);
|
||||
assert_eq!(env.len(), 1);
|
||||
}
|
||||
|
||||
/// estimate_envelope_offset: for a candidate delayed by N windows relative
|
||||
/// to the reference, the returned offset is +N windows and valid=1.
|
||||
/// to the reference, the returned offset is +N windows and valid=true.
|
||||
#[test]
|
||||
fn envelope_offset_recovers_delay() {
|
||||
let reference: Vec<f64> = (0..10).map(|i| i as f64).collect();
|
||||
let mut candidate = vec![0.0f64; 10];
|
||||
candidate[2..].copy_from_slice(&reference[..8]);
|
||||
let mut out = OffsetResult {
|
||||
offset_samples: 0,
|
||||
confidence: 0.0,
|
||||
valid: 0,
|
||||
};
|
||||
let r = unsafe {
|
||||
oakaudio_sync_estimate_envelope_offset(
|
||||
reference.as_ptr(),
|
||||
10,
|
||||
candidate.as_ptr(),
|
||||
10,
|
||||
std::ptr::null(),
|
||||
std::ptr::null(),
|
||||
100,
|
||||
10,
|
||||
&mut out,
|
||||
)
|
||||
};
|
||||
assert_eq!(r, 0);
|
||||
assert_eq!(out.valid, 1);
|
||||
let out = estimate_envelope_offset(&reference, &candidate, 100, 10);
|
||||
assert!(out.valid);
|
||||
assert_eq!(out.offset_samples, 200);
|
||||
assert!((out.confidence - 1.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
/// estimate_envelope_offset: windows masked invalid on either side are
|
||||
/// excluded from correlation; empty masks are treated as all-valid.
|
||||
/// estimate_envelope_offset_valid: windows masked invalid on either side
|
||||
/// are excluded from correlation; empty masks are treated as all-valid.
|
||||
#[test]
|
||||
fn envelope_offset_respects_valid_masks() {
|
||||
let reference: Vec<f64> = (0..10).map(|i| i as f64).collect();
|
||||
@@ -224,68 +121,35 @@ fn envelope_offset_respects_valid_masks() {
|
||||
|
||||
// Only the last reference window is valid -> no lag has >= 2 valid
|
||||
// overlap windows, so the estimate is invalid.
|
||||
let mut ref_valid = [1u8; 10];
|
||||
ref_valid[..9].fill(0);
|
||||
let mut out = OffsetResult {
|
||||
offset_samples: 0,
|
||||
confidence: 0.0,
|
||||
valid: 0,
|
||||
};
|
||||
let r = unsafe {
|
||||
oakaudio_sync_estimate_envelope_offset(
|
||||
reference.as_ptr(),
|
||||
10,
|
||||
candidate.as_ptr(),
|
||||
10,
|
||||
ref_valid.as_ptr(),
|
||||
std::ptr::null(),
|
||||
100,
|
||||
10,
|
||||
&mut out,
|
||||
)
|
||||
};
|
||||
assert_eq!(r, 0);
|
||||
assert_eq!(out.valid, 0);
|
||||
let mut ref_valid = vec![false; 10];
|
||||
ref_valid[9] = true;
|
||||
let out = estimate_envelope_offset_valid(
|
||||
&reference,
|
||||
&candidate,
|
||||
&ref_valid,
|
||||
&[],
|
||||
100,
|
||||
10,
|
||||
);
|
||||
assert!(!out.valid);
|
||||
assert_eq!(out.confidence, 0.0);
|
||||
|
||||
// Fully-valid masks behave like the unmasked call.
|
||||
let mut valid = [1u8; 10];
|
||||
let r = unsafe {
|
||||
oakaudio_sync_estimate_envelope_offset(
|
||||
reference.as_ptr(),
|
||||
10,
|
||||
candidate.as_ptr(),
|
||||
10,
|
||||
valid.as_ptr(),
|
||||
valid.as_ptr(),
|
||||
100,
|
||||
10,
|
||||
&mut out,
|
||||
)
|
||||
};
|
||||
assert_eq!(r, 0);
|
||||
assert_eq!(out.valid, 1);
|
||||
let valid = vec![true; 10];
|
||||
let out = estimate_envelope_offset_valid(
|
||||
&reference,
|
||||
&candidate,
|
||||
&valid,
|
||||
&valid,
|
||||
100,
|
||||
10,
|
||||
);
|
||||
assert!(out.valid);
|
||||
assert_eq!(out.offset_samples, 200);
|
||||
|
||||
// NULL arrays / non-positive lengths are invalid.
|
||||
let r = unsafe {
|
||||
oakaudio_sync_estimate_envelope_offset(
|
||||
std::ptr::null(),
|
||||
10,
|
||||
candidate.as_ptr(),
|
||||
10,
|
||||
std::ptr::null(),
|
||||
std::ptr::null(),
|
||||
100,
|
||||
10,
|
||||
&mut out,
|
||||
)
|
||||
};
|
||||
assert_eq!(r, OAKAUDIO_E_INVALID);
|
||||
}
|
||||
|
||||
/// estimate_stretch_and_offset: a candidate sampled at 2x the reference
|
||||
/// rate reports rate ~2.0 (>1 = speed up) with a valid=1 result. A
|
||||
/// rate reports rate ~2.0 (>1 = speed up) with a valid=true result. A
|
||||
/// non-linear (sine) reference is used — normalized correlation of linear
|
||||
/// ramps is degenerate (any rate correlates 1.0), but only the true rate
|
||||
/// resamples the sine back onto the reference exactly.
|
||||
@@ -302,78 +166,43 @@ fn stretch_offset_recovers_rate() {
|
||||
candidate.push((reference[k] + reference[k + 1]) / 2.0);
|
||||
}
|
||||
}
|
||||
let mut out = StretchOffsetResult {
|
||||
rate: 0.0,
|
||||
offset_samples: 0,
|
||||
confidence: 0.0,
|
||||
valid: 0,
|
||||
};
|
||||
let r = unsafe {
|
||||
oakaudio_sync_estimate_stretch_and_offset(
|
||||
reference.as_ptr(),
|
||||
10,
|
||||
candidate.as_ptr(),
|
||||
candidate.len() as i32,
|
||||
std::ptr::null(),
|
||||
std::ptr::null(),
|
||||
100,
|
||||
10,
|
||||
0.5,
|
||||
3.0,
|
||||
0.1,
|
||||
&mut out,
|
||||
)
|
||||
};
|
||||
assert_eq!(r, 0);
|
||||
assert_eq!(out.valid, 1);
|
||||
let out = estimate_stretch_and_offset(
|
||||
&reference,
|
||||
&candidate,
|
||||
&[],
|
||||
&[],
|
||||
100,
|
||||
10,
|
||||
0.5,
|
||||
3.0,
|
||||
0.1,
|
||||
);
|
||||
assert!(out.valid);
|
||||
assert!((out.rate - 2.0).abs() < 0.15, "rate = {}", out.rate);
|
||||
assert!(out.confidence > 0.99, "confidence = {}", out.confidence);
|
||||
|
||||
// Invalid rate parameters are rejected.
|
||||
let r = unsafe {
|
||||
oakaudio_sync_estimate_stretch_and_offset(
|
||||
reference.as_ptr(),
|
||||
10,
|
||||
candidate.as_ptr(),
|
||||
candidate.len() as i32,
|
||||
std::ptr::null(),
|
||||
std::ptr::null(),
|
||||
100,
|
||||
10,
|
||||
0.0,
|
||||
3.0,
|
||||
0.1,
|
||||
&mut out,
|
||||
)
|
||||
};
|
||||
assert_eq!(r, OAKAUDIO_E_INVALID);
|
||||
// Invalid rate parameters are rejected (invalid result, defaults).
|
||||
let out = estimate_stretch_and_offset(
|
||||
&reference,
|
||||
&candidate,
|
||||
&[],
|
||||
&[],
|
||||
100,
|
||||
10,
|
||||
0.0,
|
||||
3.0,
|
||||
0.1,
|
||||
);
|
||||
assert!(!out.valid);
|
||||
}
|
||||
|
||||
/// estimate_* on identical silent envelopes yields low/no confidence and
|
||||
/// valid=0 (no correlation peak).
|
||||
/// valid=false (no correlation peak).
|
||||
#[test]
|
||||
fn silent_inputs_invalid() {
|
||||
let silence = vec![0.0f64; 10];
|
||||
let mut out = OffsetResult {
|
||||
offset_samples: 0,
|
||||
confidence: 0.0,
|
||||
valid: 0,
|
||||
};
|
||||
let r = unsafe {
|
||||
oakaudio_sync_estimate_envelope_offset(
|
||||
silence.as_ptr(),
|
||||
10,
|
||||
silence.as_ptr(),
|
||||
10,
|
||||
std::ptr::null(),
|
||||
std::ptr::null(),
|
||||
100,
|
||||
10,
|
||||
&mut out,
|
||||
)
|
||||
};
|
||||
assert_eq!(r, 0);
|
||||
assert_eq!(out.valid, 0);
|
||||
let out = estimate_envelope_offset(&silence, &silence, 100, 10);
|
||||
assert!(!out.valid);
|
||||
assert_eq!(out.confidence, 0.0);
|
||||
}
|
||||
|
||||
|
||||
@@ -14,56 +14,29 @@
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! AudioVisualWaveform contract tests (waveform.rs), through the C ABI.
|
||||
//! AudioVisualWaveform contract tests (waveform.rs), calling the public
|
||||
//! Rust API.
|
||||
|
||||
mod common;
|
||||
|
||||
use std::ffi::CString;
|
||||
|
||||
use common::{pair, write_wav};
|
||||
use oakaudio::error::{OAKAUDIO_E_INVALID, OAKAUDIO_E_STATE};
|
||||
use oakaudio::ffi::waveform::{
|
||||
oakaudio_waveform_extract, oakaudio_waveform_free, oakaudio_waveform_get_channel_count,
|
||||
oakaudio_waveform_get_summary, oakaudio_waveform_init, oakaudio_waveform_length,
|
||||
oakaudio_waveform_overwrite_samples, oakaudio_waveform_overwrite_silence,
|
||||
oakaudio_waveform_overwrite_sums, oakaudio_waveform_re_sum_s, oakaudio_waveform_resize,
|
||||
oakaudio_waveform_set_channel_count, oakaudio_waveform_sum_samples_s,
|
||||
oakaudio_waveform_trim_in, oakaudio_waveform_trim_range, MinMax,
|
||||
};
|
||||
use common::write_wav;
|
||||
use oakcore_rs::Rational;
|
||||
use oakaudio::waveform::{extract, AudioVisualWaveform, SamplePerChannel};
|
||||
|
||||
/// Fill `w` with 100 samples/channel of a 0..0.99 ramp at 100 Hz (1 s).
|
||||
fn fill_ramp(w: oakaudio::handle::CHandle) {
|
||||
fn fill_ramp(w: &mut AudioVisualWaveform) {
|
||||
let ch0: Vec<f32> = (0..100).map(|i| i as f32 * 0.01).collect();
|
||||
let ch1: Vec<f32> = (0..100).map(|i| -(i as f32) * 0.01).collect();
|
||||
let planes = [ch0.as_ptr(), ch1.as_ptr()];
|
||||
assert_eq!(unsafe { oakaudio_waveform_set_channel_count(w, 2) }, 0);
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_waveform_overwrite_samples(w, planes.as_ptr(), 100, 100, 0, 1) },
|
||||
0
|
||||
);
|
||||
let planes = [ch0.as_slice(), ch1.as_slice()];
|
||||
w.set_channel_count(2);
|
||||
w.overwrite_samples(&planes, 100, Rational::new(0, 1));
|
||||
}
|
||||
|
||||
fn summary(
|
||||
w: oakaudio::handle::CHandle,
|
||||
start: (i64, i64),
|
||||
length: (i64, i64),
|
||||
cap: i32,
|
||||
) -> Vec<MinMax> {
|
||||
let mut out = vec![MinMax { min: 0.0, max: 0.0 }; cap as usize * 2];
|
||||
let n = unsafe {
|
||||
oakaudio_waveform_get_summary(
|
||||
w,
|
||||
start.0,
|
||||
start.1,
|
||||
length.0,
|
||||
length.1,
|
||||
out.as_mut_ptr(),
|
||||
cap,
|
||||
)
|
||||
};
|
||||
assert_eq!(n, cap);
|
||||
out.truncate(cap as usize * 2);
|
||||
out
|
||||
/// A one-point-per-channel summary over `start..start+length`.
|
||||
fn summary(w: &AudioVisualWaveform, start: Rational, length: Rational) -> Vec<SamplePerChannel> {
|
||||
w.get_summary_from_time(start, length)
|
||||
}
|
||||
|
||||
/// set_channel_count then overwrite_samples writes planar data at the given
|
||||
@@ -71,110 +44,52 @@ fn summary(
|
||||
/// channel-interleaved min/max pairs.
|
||||
#[test]
|
||||
fn overwrite_samples_and_length() {
|
||||
let mut w = unsafe { oakaudio_waveform_init() };
|
||||
fill_ramp(w);
|
||||
let mut w = AudioVisualWaveform::new();
|
||||
fill_ramp(&mut w);
|
||||
|
||||
let (mut num, mut den) = (0i64, 0i64);
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_waveform_length(w, &mut num, &mut den) },
|
||||
0
|
||||
);
|
||||
assert_eq!(num, 1);
|
||||
assert_eq!(den, 1);
|
||||
assert_eq!(w.length(), Rational::new(1, 1));
|
||||
|
||||
let out = summary(w, (0, 1), (1, 1), 1);
|
||||
let out = summary(&w, Rational::new(0, 1), Rational::new(1, 1));
|
||||
assert_eq!(out.len(), 2);
|
||||
assert_eq!(out[0].min, 0.0);
|
||||
assert!((out[0].max - 0.99).abs() < 1e-5, "max = {}", out[0].max);
|
||||
assert!((out[1].min + 0.99).abs() < 1e-5, "min = {}", out[1].min);
|
||||
assert_eq!(out[1].max, 0.0);
|
||||
unsafe { oakaudio_waveform_free(&mut w) };
|
||||
}
|
||||
|
||||
/// get_summary with out_pairs NULL returns the required point count without
|
||||
/// writing; a too-small capacity returns the same count and leaves the
|
||||
/// buffer untouched (two-stage contract).
|
||||
#[test]
|
||||
fn summary_two_stage_query() {
|
||||
let mut w = unsafe { oakaudio_waveform_init() };
|
||||
fill_ramp(w);
|
||||
|
||||
// NULL out: required count only.
|
||||
let n = unsafe { oakaudio_waveform_get_summary(w, 0, 1, 1, 1, std::ptr::null_mut(), 0) };
|
||||
assert_eq!(n, 1);
|
||||
|
||||
// Too-small capacity: same count, buffer untouched.
|
||||
let mut out = [MinMax {
|
||||
min: -1.0,
|
||||
max: -1.0,
|
||||
}; 2];
|
||||
let n = unsafe { oakaudio_waveform_get_summary(w, 0, 1, 1, 1, out.as_mut_ptr(), 0) };
|
||||
assert_eq!(n, 1);
|
||||
assert_eq!(out[0].min, -1.0);
|
||||
assert_eq!(out[0].max, -1.0);
|
||||
|
||||
// A zero/negative length is invalid.
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_waveform_get_summary(w, 0, 1, 0, 1, std::ptr::null_mut(), 0) },
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_waveform_get_summary(w, 0, 1, 1, 0, std::ptr::null_mut(), 0) },
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
unsafe { oakaudio_waveform_free(&mut w) };
|
||||
}
|
||||
|
||||
/// overwrite_sums copies channel-interleaved pairs from another waveform
|
||||
/// into a dest range; a 0/1 length copies all of src.
|
||||
/// into a dest range; a null length copies all of src.
|
||||
#[test]
|
||||
fn overwrite_sums_range_copy() {
|
||||
let mut src = unsafe { oakaudio_waveform_init() };
|
||||
fill_ramp(src);
|
||||
let mut src = AudioVisualWaveform::new();
|
||||
fill_ramp(&mut src);
|
||||
|
||||
let mut dst = unsafe { oakaudio_waveform_init() };
|
||||
assert_eq!(unsafe { oakaudio_waveform_set_channel_count(dst, 2) }, 0);
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_waveform_overwrite_sums(dst, src, 0, 1, 0, 1, 0, 1) },
|
||||
0
|
||||
);
|
||||
// A 0/1 length means "copy everything": dst matches src exactly.
|
||||
let out = summary(dst, (0, 1), (1, 1), 1);
|
||||
let mut dst = AudioVisualWaveform::new();
|
||||
dst.set_channel_count(2);
|
||||
dst.overwrite_sums(&src, Rational::new(0, 1), Rational::new(0, 1), Rational::NULL);
|
||||
// A null length means "copy everything": dst matches src exactly.
|
||||
let out = summary(&dst, Rational::new(0, 1), Rational::new(1, 1));
|
||||
assert_eq!(out.len(), 2);
|
||||
assert_eq!(out[0].min, 0.0);
|
||||
assert!((out[0].max - 0.99).abs() < 1e-5, "max = {}", out[0].max);
|
||||
assert!((out[1].min + 0.99).abs() < 1e-5, "min = {}", out[1].min);
|
||||
assert_eq!(out[1].max, 0.0);
|
||||
|
||||
let (mut num, mut den) = (0i64, 0i64);
|
||||
unsafe { oakaudio_waveform_length(dst, &mut num, &mut den) };
|
||||
assert_eq!(num, 1);
|
||||
|
||||
// Empty src handle is invalid.
|
||||
let empty = oakaudio::handle::CHandle::null();
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_waveform_overwrite_sums(dst, empty, 0, 1, 0, 1, 0, 1) },
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
|
||||
unsafe { oakaudio_waveform_free(&mut dst) };
|
||||
unsafe { oakaudio_waveform_free(&mut src) };
|
||||
assert_eq!(dst.length(), Rational::new(1, 1));
|
||||
}
|
||||
|
||||
/// overwrite_silence zeroes min/max over a range without changing length.
|
||||
#[test]
|
||||
fn overwrite_silence() {
|
||||
let mut w = unsafe { oakaudio_waveform_init() };
|
||||
fill_ramp(w);
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_waveform_overwrite_silence(w, 0, 1, 1, 2) },
|
||||
0
|
||||
);
|
||||
let mut w = AudioVisualWaveform::new();
|
||||
fill_ramp(&mut w);
|
||||
w.overwrite_silence(Rational::new(0, 1), Rational::new(1, 2));
|
||||
|
||||
// First half is silenced; second half retains the ramp data.
|
||||
let out = summary(w, (0, 1), (1, 2), 1);
|
||||
assert_eq!(pair(out[0].min, out[0].max), pair(0.0, 0.0));
|
||||
assert_eq!(pair(out[1].min, out[1].max), pair(0.0, 0.0));
|
||||
let out = summary(&w, Rational::new(0, 1), Rational::new(1, 2));
|
||||
assert_eq!((out[0].min, out[0].max), (0.0, 0.0));
|
||||
assert_eq!((out[1].min, out[1].max), (0.0, 0.0));
|
||||
|
||||
let out = summary(w, (1, 2), (1, 2), 1);
|
||||
let out = summary(&w, Rational::new(1, 2), Rational::new(1, 2));
|
||||
assert!(
|
||||
out[0].max > 0.5,
|
||||
"second half must keep ramp data, got {:?}",
|
||||
@@ -182,94 +97,61 @@ fn overwrite_silence() {
|
||||
);
|
||||
assert!(out[1].min < -0.5);
|
||||
|
||||
let (mut num, mut den) = (0i64, 0i64);
|
||||
unsafe { oakaudio_waveform_length(w, &mut num, &mut den) };
|
||||
assert_eq!(
|
||||
(num, den),
|
||||
(1, 1),
|
||||
w.length(),
|
||||
Rational::new(1, 1),
|
||||
"overwrite_silence must not change length"
|
||||
);
|
||||
unsafe { oakaudio_waveform_free(&mut w) };
|
||||
}
|
||||
|
||||
/// trim_in/trim_range/resize adjust length and drop or pad data; a negative
|
||||
/// trim_in prepends silence (C++ semantics).
|
||||
#[test]
|
||||
fn trim_and_resize() {
|
||||
let mut w = unsafe { oakaudio_waveform_init() };
|
||||
fill_ramp(w);
|
||||
let mut w = AudioVisualWaveform::new();
|
||||
fill_ramp(&mut w);
|
||||
|
||||
// Negative trim_in prepends silence: absolute end (length) unchanged.
|
||||
assert_eq!(unsafe { oakaudio_waveform_trim_in(w, -1, 2) }, 0);
|
||||
let (mut num, mut den) = (0i64, 0i64);
|
||||
unsafe { oakaudio_waveform_length(w, &mut num, &mut den) };
|
||||
assert_eq!((num, den), (1, 1));
|
||||
w.trim_in(Rational::new(-1, 2));
|
||||
assert_eq!(w.length(), Rational::new(1, 1));
|
||||
|
||||
// Resize extends to 2 s.
|
||||
assert_eq!(unsafe { oakaudio_waveform_resize(w, 2, 1) }, 0);
|
||||
unsafe { oakaudio_waveform_length(w, &mut num, &mut den) };
|
||||
assert_eq!((num, den), (2, 1));
|
||||
w.resize(Rational::new(2, 1));
|
||||
assert_eq!(w.length(), Rational::new(2, 1));
|
||||
|
||||
// trim_range keeps 0.5 s from the (prepended) start.
|
||||
assert_eq!(unsafe { oakaudio_waveform_trim_range(w, 0, 1, 1, 2) }, 0);
|
||||
unsafe { oakaudio_waveform_length(w, &mut num, &mut den) };
|
||||
assert_eq!((num, den), (1, 2));
|
||||
|
||||
// A negative resize target or a zero denominator is invalid.
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_waveform_resize(w, -1, 2) },
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_waveform_resize(w, 1, 0) },
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
unsafe { oakaudio_waveform_free(&mut w) };
|
||||
w.trim_range(Rational::new(0, 1), Rational::new(1, 2));
|
||||
assert_eq!(w.length(), Rational::new(1, 2));
|
||||
}
|
||||
|
||||
/// sum_samples_s reduces planar samples into one min/max pair per channel;
|
||||
/// re_sum_s merges channel-interleaved entries into one pair per channel.
|
||||
/// Both match golden vectors from the C++ implementation.
|
||||
/// sum_samples reduces planar samples into one min/max pair per channel;
|
||||
/// re_sum_samples merges channel-interleaved entries into one pair per
|
||||
/// channel. Both match golden vectors from the C++ implementation.
|
||||
#[test]
|
||||
fn sum_and_resum_golden() {
|
||||
let ch0 = [1.0f32, -2.0, 3.0];
|
||||
let ch1 = [4.0f32, -5.0, 6.0];
|
||||
let planes = [ch0.as_ptr(), ch1.as_ptr()];
|
||||
let mut out = [MinMax { min: 0.0, max: 0.0 }; 2];
|
||||
let r = unsafe { oakaudio_waveform_sum_samples_s(planes.as_ptr(), 2, 0, 3, out.as_mut_ptr()) };
|
||||
assert_eq!(r, 0);
|
||||
assert_eq!(pair(out[0].min, out[0].max), pair(-2.0, 3.0));
|
||||
assert_eq!(pair(out[1].min, out[1].max), pair(-5.0, 6.0));
|
||||
let planes = [ch0.as_slice(), ch1.as_slice()];
|
||||
let out = AudioVisualWaveform::sum_samples(&planes, 0, 3);
|
||||
assert_eq!((out[0].min, out[0].max), (-2.0, 3.0));
|
||||
assert_eq!((out[1].min, out[1].max), (-5.0, 6.0));
|
||||
|
||||
// re_sum_s over 4 interleaved entries, 2 channels -> one pair per
|
||||
// re_sum_samples over 4 interleaved entries, 2 channels -> one pair per
|
||||
// channel merging both points.
|
||||
let input = [
|
||||
MinMax { min: 1.0, max: 2.0 },
|
||||
MinMax { min: 3.0, max: 4.0 },
|
||||
MinMax { min: 5.0, max: 6.0 },
|
||||
MinMax { min: 7.0, max: 8.0 },
|
||||
SamplePerChannel { min: 1.0, max: 2.0 },
|
||||
SamplePerChannel { min: 3.0, max: 4.0 },
|
||||
SamplePerChannel { min: 5.0, max: 6.0 },
|
||||
SamplePerChannel { min: 7.0, max: 8.0 },
|
||||
];
|
||||
let mut out = [MinMax { min: 0.0, max: 0.0 }; 2];
|
||||
let r = unsafe { oakaudio_waveform_re_sum_s(input.as_ptr(), 4, 2, out.as_mut_ptr()) };
|
||||
assert_eq!(r, 0);
|
||||
assert_eq!(pair(out[0].min, out[0].max), pair(1.0, 6.0));
|
||||
assert_eq!(pair(out[1].min, out[1].max), pair(3.0, 8.0));
|
||||
|
||||
// Invalid arguments.
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_waveform_sum_samples_s(planes.as_ptr(), 2, 0, 0, out.as_mut_ptr()) },
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_waveform_re_sum_s(input.as_ptr(), 0, 2, out.as_mut_ptr()) },
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
let out = AudioVisualWaveform::re_sum_samples(&input, 4, 2);
|
||||
assert_eq!((out[0].min, out[0].max), (1.0, 6.0));
|
||||
assert_eq!((out[1].min, out[1].max), (3.0, 8.0));
|
||||
}
|
||||
|
||||
/// extract probes through the oakcodec decoder C ABI; a missing file
|
||||
/// returns OAKAUDIO_E_NOT_FOUND. The valid-file path decodes the fixture
|
||||
/// WAV with oakcodec's in-process FFmpeg decoder and reduces it to min/max
|
||||
/// points.
|
||||
/// extract probes through oakcodec's decoder registry; a missing file
|
||||
/// returns NotFound. The valid-file path decodes the fixture WAV with
|
||||
/// oakcodec's in-process FFmpeg decoder and reduces it to min/max points.
|
||||
#[test]
|
||||
fn extract_file_and_notfound() {
|
||||
let path = std::env::temp_dir().join(format!("oakaudio_extract_{}.wav", std::process::id()));
|
||||
@@ -281,55 +163,19 @@ fn extract_file_and_notfound() {
|
||||
}
|
||||
write_wav(&path, 2, 48000, &samples).unwrap();
|
||||
|
||||
// Missing file -> NOT_FOUND.
|
||||
let missing = CString::new(
|
||||
std::env::temp_dir()
|
||||
.join(format!("oakaudio_missing_{}.wav", std::process::id()))
|
||||
.to_str()
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let _ = std::fs::remove_file(std::path::Path::new(missing.to_str().unwrap()));
|
||||
let r = unsafe {
|
||||
oakaudio_waveform_extract(
|
||||
missing.as_ptr(),
|
||||
0,
|
||||
4,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
assert_eq!(r, -60004);
|
||||
// Missing file -> NotFound.
|
||||
let missing = std::env::temp_dir().join(format!("oakaudio_missing_{}.wav", std::process::id()));
|
||||
let _ = std::fs::remove_file(&missing);
|
||||
let missing_c = CString::new(missing.to_str().unwrap()).unwrap();
|
||||
assert!(extract(&missing_c, 0, 4).is_err());
|
||||
|
||||
// Real decode: 8 frames at 4 samples/point -> 2 points, 2 channels.
|
||||
let c_path = CString::new(path.to_str().unwrap()).unwrap();
|
||||
let mut channel_count = 0i32;
|
||||
let n = unsafe {
|
||||
oakaudio_waveform_extract(
|
||||
c_path.as_ptr(),
|
||||
0,
|
||||
4,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
&mut channel_count,
|
||||
)
|
||||
};
|
||||
assert_eq!(channel_count, 2);
|
||||
assert_eq!(n, 2, "8 frames at 4 samples/point must yield 2 points");
|
||||
let outcome = extract(&c_path, 0, 4).unwrap();
|
||||
assert_eq!(outcome.channels, 2);
|
||||
assert_eq!(outcome.points.len(), 4, "2 points x 2 channels");
|
||||
let out = &outcome.points;
|
||||
|
||||
let mut out = vec![MinMax { min: 0.0, max: 0.0 }; 4];
|
||||
let n = unsafe {
|
||||
oakaudio_waveform_extract(
|
||||
c_path.as_ptr(),
|
||||
0,
|
||||
4,
|
||||
out.as_mut_ptr(),
|
||||
2,
|
||||
&mut channel_count,
|
||||
)
|
||||
};
|
||||
assert_eq!(n, 2);
|
||||
// s16 -> f32 is /32768; the ramp is exact in both formats.
|
||||
let eps = 1e-6;
|
||||
// Point 0 covers frames 0..4: left 0..3000, right 0..-3000.
|
||||
@@ -346,60 +192,18 @@ fn extract_file_and_notfound() {
|
||||
std::fs::remove_file(&path).ok();
|
||||
}
|
||||
|
||||
/// FFI validation and empty-handle error paths.
|
||||
/// Overwriting with channel count 0 is a logged no-op (the C ABI's state
|
||||
/// error was FFI-level validation; the Rust API keeps the C++ semantics of
|
||||
/// returning without touching the data).
|
||||
#[test]
|
||||
fn ffi_error_paths() {
|
||||
let empty = oakaudio::handle::CHandle::null();
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_waveform_get_channel_count(empty) },
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_waveform_set_channel_count(empty, 2) },
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
let (mut num, mut den) = (0i64, 0i64);
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_waveform_length(empty, &mut num, &mut den) },
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
|
||||
// Negative channel count is invalid.
|
||||
let mut w = unsafe { oakaudio_waveform_init() };
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_waveform_set_channel_count(w, -1) },
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
|
||||
// overwrite_samples before set_channel_count is a state error.
|
||||
fn no_channel_count_is_noop() {
|
||||
let mut w = AudioVisualWaveform::new();
|
||||
let data = [0.5f32; 8];
|
||||
let planes = [data.as_ptr()];
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_waveform_overwrite_samples(w, planes.as_ptr(), 8, 48000, 0, 1) },
|
||||
OAKAUDIO_E_STATE
|
||||
);
|
||||
// A zero denominator is rejected.
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_waveform_overwrite_samples(w, planes.as_ptr(), 8, 48000, 0, 0) },
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
// A non-positive frame count is invalid.
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_waveform_overwrite_samples(w, planes.as_ptr(), 0, 48000, 0, 1) },
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
// NULL planes are invalid.
|
||||
assert_eq!(
|
||||
unsafe { oakaudio_waveform_overwrite_samples(w, std::ptr::null(), 8, 48000, 0, 1) },
|
||||
OAKAUDIO_E_INVALID
|
||||
);
|
||||
unsafe { oakaudio_waveform_free(&mut w) };
|
||||
}
|
||||
let planes = [data.as_slice()];
|
||||
w.overwrite_samples(&planes, 48000, Rational::new(0, 1));
|
||||
assert!(w.length().is_null());
|
||||
assert_eq!(w.channel_count(), 0);
|
||||
|
||||
/// free(NULL)/free(empty) are no-ops.
|
||||
#[test]
|
||||
fn free_null_noop() {
|
||||
let mut w = oakaudio::handle::CHandle::null();
|
||||
unsafe { oakaudio_waveform_free(&mut w) };
|
||||
unsafe { oakaudio_waveform_free(std::ptr::null_mut()) };
|
||||
w.set_channel_count(2);
|
||||
assert_eq!(w.channel_count(), 2);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user