Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

29 changes: 24 additions & 5 deletions crates/vendor/libxaac-sys/examples/sample.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,40 @@ use std::alloc::{Layout, alloc_zeroed, dealloc};
use std::ffi::{CStr, c_void};
use std::mem::{align_of, size_of, zeroed};
use std::ptr;
use std::sync::atomic::{AtomicBool, Ordering};

use libxaac_sys::{
AOT_AAC_LC, DEFAULT_MEM_ALIGN_8, IA_API_CMD_GET_API_SIZE, IA_MEMTYPE_INPUT, IA_MEMTYPE_OUTPUT,
ia_lib_info_struct, ixheaacd_dec_api, ixheaacd_get_lib_id_strings, ixheaace_delete,
ixheaace_get_lib_id_strings, ixheaace_process, ixheaace_user_config_struct, ixheaace_version,
};

static POISON_ALLOC: AtomicBool = AtomicBool::new(false);

fn main() {
print_library_versions();
print_decoder_api_size();

let (mut config, pcm_input_size) = build_encoder_config();

let create_status = unsafe {
libxaac_sys::ixheaace_create(
(&mut config.input_config as *mut _) as *mut c_void,
(&mut config.output_config as *mut _) as *mut c_void,
)
// Both paths use this example's zeroed allocator. Run once normally and
// once with `--zeroed-alloc` to compare peak RSS without changing input.
// The ordinary entry point must also work with an allocator that returns
// nonzero bytes; `--poison-alloc` verifies that separate contract.
let args: Vec<_> = std::env::args().collect();
let zeroed_alloc = args.iter().any(|arg| arg == "--zeroed-alloc");
let poison_alloc = args.iter().any(|arg| arg == "--poison-alloc");
assert!(
!(zeroed_alloc && poison_alloc),
"zeroed entry point needs zeroed memory"
);
POISON_ALLOC.store(poison_alloc, Ordering::Relaxed);
let input = (&mut config.input_config as *mut _) as *mut c_void;
let output = (&mut config.output_config as *mut _) as *mut c_void;
let create_status = if zeroed_alloc {
unsafe { libxaac_sys::ixheaace_create_zeroed(input, output) }
} else {
unsafe { libxaac_sys::ixheaace_create(input, output) }
};
assert_eq!(create_status, 0, "ixheaace_create failed: {create_status}");

Expand Down Expand Up @@ -156,6 +172,9 @@ unsafe extern "C" fn xaac_alloc(size: u32, alignment: u32) -> *mut c_void {
if base.is_null() {
return ptr::null_mut();
}
if POISON_ALLOC.load(Ordering::Relaxed) {
unsafe { ptr::write_bytes(base, 0xa5, total_size) };
}

let aligned_addr =
(base as usize + header_words + requested_align - 1) & !(requested_align - 1);
Expand Down
45 changes: 34 additions & 11 deletions crates/vendor/libxaac-sys/libxaac/encoder/ixheaace_api.c
Original file line number Diff line number Diff line change
Expand Up @@ -1554,7 +1554,8 @@ static WORD32 get_drc_config_size(ixheaace_api_struct *pstr_api_struct,

static IA_ERRORCODE ixheaace_alloc_and_assign_mem(ixheaace_api_struct *pstr_api_struct,
ixheaace_output_config *ptr_out_cfg,
ixheaace_input_config *ptr_in_cfg) {
ixheaace_input_config *ptr_in_cfg,
WORD32 zeroed_alloc) {
IA_ERRORCODE err_code = IA_NO_ERROR;
UWORD32 i_idx;
pVOID pv_value;
Expand All @@ -1581,8 +1582,10 @@ static IA_ERRORCODE ixheaace_alloc_and_assign_mem(ixheaace_api_struct *pstr_api_
if (NULL == ptr_out_cfg->arr_alloc_memory[ptr_out_cfg->malloc_count]) {
return IA_EXHEAACE_API_FATAL_MEM_ALLOC;
}
memset(ptr_out_cfg->arr_alloc_memory[ptr_out_cfg->malloc_count], 0,
ptr_out_cfg->mem_info_table[i_idx].ui_size);
if (!zeroed_alloc) {
memset(ptr_out_cfg->arr_alloc_memory[ptr_out_cfg->malloc_count], 0,
ptr_out_cfg->mem_info_table[i_idx].ui_size);
}
if ((i_idx == IA_ENHAACPLUSENC_PERSIST_IDX) || (i_idx == IA_ENHAACPLUSENC_SCRATCH_IDX)) {
ptr_out_cfg->ui_rem =
(SIZE_T)((SIZE_T)ptr_out_cfg->arr_alloc_memory[ptr_out_cfg->malloc_count] %
Expand All @@ -1597,7 +1600,9 @@ static IA_ERRORCODE ixheaace_alloc_and_assign_mem(ixheaace_api_struct *pstr_api_
}

pstr_api_struct->pp_mem[i_idx] = ptr_out_cfg->mem_info_table[i_idx].mem_ptr;
memset(pstr_api_struct->pp_mem[i_idx], 0, pstr_api_struct->pstr_mem_info[i_idx].ui_size);
if (!zeroed_alloc) {
memset(pstr_api_struct->pp_mem[i_idx], 0, pstr_api_struct->pstr_mem_info[i_idx].ui_size);
}

pstr_api_struct->pp_mem[i_idx] = pv_value;

Expand Down Expand Up @@ -1749,7 +1754,9 @@ static IA_ERRORCODE ixheaace_alloc_and_assign_mem(ixheaace_api_struct *pstr_api_
} else {
WORD32 num_aac_chan;
ixheaace_state_struct *pstr_state = pstr_api_struct->pstr_state;
memset(pstr_api_struct->pstr_state, 0, sizeof(*(pstr_api_struct->pstr_state)));
if (!zeroed_alloc) {
memset(pstr_api_struct->pstr_state, 0, sizeof(*(pstr_api_struct->pstr_state)));
}

pstr_api_struct->pstr_state->inp_delay = (FLOAT32 *)((WORD8 *)pstr_state + offset_size);
offset_size = ia_enhaacplus_enc_sizeof_delay_buffer(
Expand Down Expand Up @@ -3549,7 +3556,7 @@ static void ixheaace_get_measured_loudness_info(ixheaace_api_struct *pstr_api_st
}
}

IA_ERRORCODE ixheaace_allocate(pVOID pv_input, pVOID pv_output) {
static IA_ERRORCODE ixheaace_allocate(pVOID pv_input, pVOID pv_output, WORD32 zeroed_alloc) {
IA_ERRORCODE err_code = IA_NO_ERROR;
WORD32 ui_api_size;
pVOID pv_value;
Expand All @@ -3570,7 +3577,9 @@ IA_ERRORCODE ixheaace_allocate(pVOID pv_input, pVOID pv_output) {
if (NULL == pstr_output_config->arr_alloc_memory[pstr_output_config->malloc_count]) {
return IA_EXHEAACE_API_FATAL_MEM_ALLOC;
}
memset(pstr_output_config->arr_alloc_memory[pstr_output_config->malloc_count], 0, ui_api_size);
if (!zeroed_alloc) {
memset(pstr_output_config->arr_alloc_memory[pstr_output_config->malloc_count], 0, ui_api_size);
}

pstr_output_config->ui_rem =
(SIZE_T)((SIZE_T)pstr_output_config->arr_alloc_memory[pstr_output_config->malloc_count] %
Expand All @@ -3582,7 +3591,9 @@ IA_ERRORCODE ixheaace_allocate(pVOID pv_input, pVOID pv_output) {
pstr_output_config->malloc_count++;

pstr_api_struct = (ixheaace_api_struct *)pstr_output_config->pv_ia_process_api_obj;
memset(pstr_api_struct, 0, sizeof(*pstr_api_struct));
if (!zeroed_alloc) {
memset(pstr_api_struct, 0, sizeof(*pstr_api_struct));
}

ixheaace_set_default_config(pstr_api_struct, pstr_input_config);

Expand Down Expand Up @@ -3630,7 +3641,8 @@ IA_ERRORCODE ixheaace_allocate(pVOID pv_input, pVOID pv_output) {
ixheaace_fill_mem_tabs(pstr_api_struct, pstr_input_config->aot);

err_code =
ixheaace_alloc_and_assign_mem(pstr_api_struct, pstr_output_config, pstr_input_config);
ixheaace_alloc_and_assign_mem(pstr_api_struct, pstr_output_config, pstr_input_config,
zeroed_alloc);
if (err_code) {
return err_code;
}
Expand Down Expand Up @@ -3837,10 +3849,11 @@ IA_ERRORCODE ixheaace_init(pVOID pstr_obj_ixheaace, pVOID pv_input, pVOID pv_out
return error;
}

IA_ERRORCODE ixheaace_create(pVOID pv_input, pVOID pv_output) {
static IA_ERRORCODE ixheaace_create_impl(pVOID pv_input, pVOID pv_output,
WORD32 zeroed_alloc) {
IA_ERRORCODE err_code = IA_NO_ERROR;
ixheaace_output_config *pstr_out_cfg = (ixheaace_output_config *)pv_output;
err_code = ixheaace_allocate(pv_input, pv_output);
err_code = ixheaace_allocate(pv_input, pv_output, zeroed_alloc);
if (!err_code) {
err_code = ixheaace_init(pstr_out_cfg->pv_ia_process_api_obj, pv_input, pv_output);
}
Expand All @@ -3850,6 +3863,16 @@ IA_ERRORCODE ixheaace_create(pVOID pv_input, pVOID pv_output) {
return err_code;
}

IA_ERRORCODE ixheaace_create(pVOID pv_input, pVOID pv_output) {
return ixheaace_create_impl(pv_input, pv_output, 0);
}

IA_ERRORCODE ixheaace_create_zeroed(pVOID pv_input, pVOID pv_output) {
/* The caller promises every malloc_xheaace result is already zero-filled.
* Skipping the redundant clears leaves AAC-LC's unused USAC pages untouched. */
return ixheaace_create_impl(pv_input, pv_output, 1);
}

IA_ERRORCODE ixheaace_process(pVOID pstr_obj_ixheaace, pVOID pv_input, pVOID pv_output) {
IA_ERRORCODE error = IA_NO_ERROR;
WORD32 ele_idx;
Expand Down
4 changes: 4 additions & 0 deletions crates/vendor/libxaac-sys/libxaac/encoder/ixheaace_api.h
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,10 @@ IA_ERRORCODE ixheaace_get_lib_id_strings(pVOID pv_output);
/* handles memory requirements and initialization*/
IA_ERRORCODE ixheaace_create(pVOID pv_input, pVOID pv_output);

/* As above, but every malloc_xheaace callback result must be zero-filled for
* the full requested size. This avoids touching unused encoder state pages. */
IA_ERRORCODE ixheaace_create_zeroed(pVOID pv_input, pVOID pv_output);

/* encodes the input frame data */
IA_ERRORCODE ixheaace_process(pVOID pv_ia_process_api_obj, pVOID pstr_in_cfg, pVOID pstr_out_cfg);

Expand Down
5 changes: 5 additions & 0 deletions crates/vendor/libxaac-sys/src/bindings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -672,6 +672,11 @@ unsafe extern "C" {
unsafe extern "C" {
pub fn ixheaace_create(pv_input: pVOID, pv_output: pVOID) -> IA_ERRORCODE;
}
#[cfg(feature = "bundled")]
unsafe extern "C" {
/// Requires `malloc_xheaace` to return a fully zeroed block on every call.
pub fn ixheaace_create_zeroed(pv_input: pVOID, pv_output: pVOID) -> IA_ERRORCODE;
}
unsafe extern "C" {
pub fn ixheaace_process(
pv_ia_process_api_obj: pVOID,
Expand Down
5 changes: 5 additions & 0 deletions crates/vendor/xaac-rs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,11 @@ path = "tests/codec.rs"
version = "0.1.0"
path = "../libxaac-sys"

# Maps the encoder's two large blocks directly, so its untouched pages stay
# unallocated. See `MAP_THRESHOLD` in src/util.rs.
[target.'cfg(unix)'.dependencies.libc]
version = "0.2"

[dependencies.pyo3]
version = "0.29"
features = ["extension-module"]
Expand Down
5 changes: 4 additions & 1 deletion crates/vendor/xaac-rs/src/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,10 @@ impl Encoder {
i32::from(config.output_format == OutputFormat::Adts);

let create_status = unsafe {
libxaac_sys::ixheaace_create(
// `encoder_alloc` returns zeroed memory, including the untouched
// pages of large anonymous mappings. Only this explicit entry
// point may skip libxaac's redundant full-block clears.
libxaac_sys::ixheaace_create_zeroed(
(&mut ffi.input_config as *mut _) as *mut c_void,
(&mut ffi.output_config as *mut _) as *mut c_void,
)
Expand Down
62 changes: 54 additions & 8 deletions crates/vendor/xaac-rs/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,15 +64,65 @@ impl Drop for AlignedBuffer {
}
}

/// Blocks at least this large are mapped from the system directly rather than
/// taken from the heap.
///
/// The encoder asks for two blocks, of 12 MB and 44 MB, sized for a USAC
/// encoder whatever the profile; AAC-LC writes well under a megabyte of them.
/// libxaac-sys builds the encoder to trust that its memory arrives zeroed, and
/// untouched zero pages cost nothing — but only while they are fresh. The heap
/// keeps freed blocks this size for reuse, and to hand one back zeroed it has to
/// clear it, which writes every page: the first encoder cost under a megabyte
/// and every one after it the full 55 MB again. Mapping the blocks directly
/// keeps each encoder's untouched pages unallocated and returns the rest to the
/// system when it is dropped.
#[cfg(unix)]
const MAP_THRESHOLD: usize = 1 << 20;

/// Zeroed memory for the encoder. See `MAP_THRESHOLD`.
unsafe fn zeroed_block(total_size: usize) -> *mut u8 {
#[cfg(unix)]
if total_size >= MAP_THRESHOLD {
let mapped = unsafe {
libc::mmap(
std::ptr::null_mut(),
total_size,
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_PRIVATE | libc::MAP_ANON,
-1,
0,
)
};
return if mapped == libc::MAP_FAILED {
std::ptr::null_mut()
} else {
mapped.cast()
};
}
let layout =
Layout::from_size_align(total_size, std::mem::align_of::<usize>()).expect("valid layout");
unsafe { alloc_zeroed(layout) }
}

/// Release a block from [`zeroed_block`] of the same `total_size`.
unsafe fn release_block(base: *mut u8, total_size: usize) {
#[cfg(unix)]
if total_size >= MAP_THRESHOLD {
unsafe { libc::munmap(base.cast(), total_size) };
return;
}
let layout =
Layout::from_size_align(total_size, std::mem::align_of::<usize>()).expect("valid layout");
unsafe { dealloc(base, layout) };
}

unsafe extern "C" fn xaac_alloc(size: u32, alignment: u32) -> *mut std::ffi::c_void {
let requested_align = alignment
.max(libxaac_sys::DEFAULT_MEM_ALIGN_8)
.next_power_of_two() as usize;
let header_words = 2 * std::mem::size_of::<usize>();
let total_size = size as usize + requested_align + header_words;
let layout =
Layout::from_size_align(total_size, std::mem::align_of::<usize>()).expect("valid layout");
let base = unsafe { alloc_zeroed(layout) };
let base = unsafe { zeroed_block(total_size) };
if base.is_null() {
return std::ptr::null_mut();
}
Expand All @@ -96,11 +146,7 @@ unsafe extern "C" fn xaac_free(ptr: *mut std::ffi::c_void) {
let meta = unsafe { (ptr as *mut usize).sub(2) };
let base = unsafe { meta.read() } as *mut u8;
let total_size = unsafe { meta.add(1).read() };
let layout =
Layout::from_size_align(total_size, std::mem::align_of::<usize>()).expect("valid layout");
unsafe {
dealloc(base, layout);
}
unsafe { release_block(base, total_size) };
}

pub(crate) fn encoder_alloc() -> Option<unsafe extern "C" fn(u32, u32) -> *mut std::ffi::c_void> {
Expand Down
20 changes: 19 additions & 1 deletion crates/vuio-cast/src/client/request_tracker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,11 @@ impl RequestTracker {
id = self.counter.fetch_add(1, Ordering::Relaxed).wrapping_add(1);
}
let (tx, rx) = oneshot::channel();
self.pending.lock().await.insert(id, tx);
let mut pending = self.pending.lock().await;
// A caller can be dropped while sending or awaiting its request. Its
// wait_for cleanup will never run, but its receiver is now closed.
pending.retain(|_, sender| !sender.is_closed());
pending.insert(id, tx);
(id, rx)
}

Expand Down Expand Up @@ -102,6 +106,20 @@ mod tests {
assert_eq!(value["type"], "RECEIVER_STATUS");
}

#[tokio::test]
async fn abandoned_requests_do_not_accumulate() {
let tracker = RequestTracker::new(Duration::from_secs(5));
let (live_id, live) = tracker.register().await;
for _ in 0..1000 {
let (_, abandoned) = tracker.register().await;
drop(abandoned);
}
let (_id, _receiver) = tracker.register().await;
assert_eq!(tracker.pending.lock().await.len(), 2);
assert!(tracker.resolve(live_id, json!("alive")).await);
assert_eq!(live.await.unwrap(), json!("alive"));
}

#[tokio::test]
async fn test_unmatched_resolve() {
let tracker = RequestTracker::new(Duration::from_secs(5));
Expand Down
7 changes: 4 additions & 3 deletions crates/vuio-core/src/casting/airplay/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -503,8 +503,9 @@ impl AirplayProvider {
b"Events-Write-Encryption-Key",
)?,
});
let (event_sender, _event_replies) = tokio::sync::mpsc::unbounded_channel();
let (command_sender, mut commands) = tokio::sync::mpsc::unbounded_channel();
let (event_sender, event_replies) = tokio::sync::mpsc::channel(16);
drop(event_replies); // Audio mode has no data-stream reply consumer.
let (command_sender, mut commands) = tokio::sync::mpsc::channel(16);
let mut event_task = AbortOnDrop(Some(tokio::spawn(async move {
if let Err(error) = event_connection
.serve_events_with_commands(event_sender, Some(command_sender))
Expand Down Expand Up @@ -770,7 +771,7 @@ impl AirplayProvider {
});
// Serve events and timing before RECORD/play. Leaving the reverse event
// TCP idle during session setup can stall third-party receivers.
let (event_reply_sender, mut event_replies) = tokio::sync::mpsc::unbounded_channel();
let (event_reply_sender, mut event_replies) = tokio::sync::mpsc::channel(16);
let mut event_task = AbortOnDrop(Some(tokio::spawn(async move {
if let Err(error) = event_connection.serve_events(event_reply_sender).await {
tracing::debug!(%error, "AirPlay event channel closed");
Expand Down
Loading
Loading