From 8d25401df816ea8f177720b2fe92123ed672afa2 Mon Sep 17 00:00:00 2001 From: vyrti Date: Wed, 23 Sep 2026 15:21:39 +0300 Subject: [PATCH 01/12] Keep a library scan's peak memory from following the whole tree MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit jwalk's parallel mode reads directories on the rayon pool as fast as it can and holds each one's entries until the iterator reaches them. The bounded channel only ever held back the thread feeding it, so on a 100,000-file library about 25 MB of directory entries — nearly the whole tree — were in memory at the scan's peak. Walking serially keeps one directory at a time; the stat stage behind it is already concurrent, so the scan is no slower (warm 0.8 s either way, cold 14 s before and 9 s after, now that tag reading no longer competes with eight walkers). The fingerprint map is the other allocation that grows with the library. Its values now hold whole seconds, which is all the index stores, rather than two 16-byte SystemTimes, and its keys are boxed paths relative to the root being scanned. The table at 100,000 files goes from 10.1 MB to 7.1 MB and each key is shorter by the root. The two batch vectors are no longer reserved up front, which held 1.3 MB through every scan of an unchanged library. Measured with a counting allocator on a 100,000-file library: cold scan peak heap 36.3 MB -> 11.3 MB warm scan peak heap 58-61 MB -> 41 MB max RSS (warm) 107 MB -> 81 MB idle footprint after 65 MB -> 39-40 MB (malloc fragmentation left by the peak: 35 MB -> 13 MB) threads at idle 22 -> 14 (no rayon pool until a transcode) --- crates/vuio-core/src/media/scanner.rs | 124 +++++++++++++++++++++----- 1 file changed, 100 insertions(+), 24 deletions(-) diff --git a/crates/vuio-core/src/media/scanner.rs b/crates/vuio-core/src/media/scanner.rs index 88cb2ef..09a7802 100644 --- a/crates/vuio-core/src/media/scanner.rs +++ b/crates/vuio-core/src/media/scanner.rs @@ -26,11 +26,19 @@ const READ_WINDOW: usize = BATCH_SIZE; /// Deliberately not [`FileFingerprint`]: that carries the path, and this lives /// in a map keyed by the path, so storing it again doubled the largest /// allocation a scan makes. +/// +/// The map holds one of these for every file under the root, so it is the one +/// allocation a scan makes that grows with the library, and it is packed to +/// match. Times are whole seconds since the epoch because that is all the index +/// stores — a `SystemTime` spent sixteen bytes carrying nanoseconds that were +/// always zero — and the key is a boxed path below the root rather than an +/// owned path from it (see [`RootRelative`]). At 100,000 files that took the +/// table from 10.1 MB to 7.1 MB, and every key is shorter by the root. struct IndexedFile { id: i64, size: u64, - modified: SystemTime, - created_at: SystemTime, + modified_secs: u64, + created_at_secs: u64, tags_version: u32, /// Set when the walk produced this path. What is left unset is what has been /// deleted from disk — which is why the scan needs no second collection of @@ -38,10 +46,47 @@ struct IndexedFile { seen: bool, } +/// A path as the scan's map keys it: relative to the root being scanned. +/// +/// Every file under one root repeats that root's prefix, and there is one key +/// per file. Stripping it is free — the walk only ever produces paths under the +/// root, and a deletion puts it back with a `join`. A record that somehow lies +/// outside the root keeps its absolute path, which cannot collide with a +/// relative one. +struct RootRelative<'a> { + root: &'a Path, +} + +impl<'a> RootRelative<'a> { + fn of<'p>(&self, path: &'p Path) -> &'p Path { + path.strip_prefix(self.root).unwrap_or(path) + } + + fn owned(&self, path: PathBuf) -> Box { + match path.strip_prefix(self.root) { + Ok(relative) => relative.into(), + Err(_) => path.into_boxed_path(), + } + } + + fn absolute(&self, key: &Path) -> PathBuf { + self.root.join(key) + } +} + +fn epoch_secs(time: SystemTime) -> u64 { + time.duration_since(std::time::UNIX_EPOCH) + .map_or(0, |elapsed| elapsed.as_secs()) +} + +fn from_epoch_secs(secs: u64) -> SystemTime { + std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs) +} + impl IndexedFile { /// Split a loaded record into the map's key and value, moving the path /// rather than copying it into both halves. - fn split(fingerprint: FileFingerprint) -> (PathBuf, Self) { + fn split(fingerprint: FileFingerprint, key: &RootRelative<'_>) -> (Box, Self) { let FileFingerprint { id, path, @@ -51,17 +96,25 @@ impl IndexedFile { tags_version, } = fingerprint; ( - path, + key.owned(path), Self { id, size, - modified, - created_at, + modified_secs: epoch_secs(modified), + created_at_secs: epoch_secs(created_at), tags_version, seen: false, }, ) } + + fn modified(&self) -> SystemTime { + from_epoch_secs(self.modified_secs) + } + + fn created_at(&self) -> SystemTime { + from_epoch_secs(self.created_at_secs) + } } impl MediaScanner { @@ -74,7 +127,8 @@ impl MediaScanner { async fn read_window( &self, paths: &mut Vec, - existing_files_map: &HashMap, + existing_files_map: &HashMap, IndexedFile>, + key: &RootRelative<'_>, files_to_insert: &mut Vec, files_to_update: &mut Vec, result: &mut ScanResult, @@ -98,12 +152,12 @@ impl MediaScanner { }; result.files_read += 1; - match existing_files_map.get(&path) { + match existing_files_map.get(key.of(&path)) { Some(existing) => { if self.fingerprint_needs_update(existing, ¤t_file) { let mut updated = current_file; updated.id = Some(existing.id); - updated.created_at = existing.created_at; + updated.created_at = existing.created_at(); updated.updated_at = SystemTime::now(); files_to_update.push(updated); } else { @@ -391,10 +445,11 @@ impl MediaScanner { let Ok(modified) = metadata.modified() else { return true; }; - let difference = if existing.modified > modified { - existing.modified.duration_since(modified) + let indexed = existing.modified(); + let difference = if indexed > modified { + indexed.duration_since(modified) } else { - modified.duration_since(existing.modified) + modified.duration_since(indexed) }; difference.map_or(true, |difference| difference.as_secs() > 10) } @@ -409,10 +464,11 @@ impl MediaScanner { if existing.tags_version < current.tags_version { return true; } - let time_diff = if existing.modified > current.modified { - existing.modified.duration_since(current.modified) + let indexed = existing.modified(); + let time_diff = if indexed > current.modified { + indexed.duration_since(current.modified) } else { - current.modified.duration_since(existing.modified) + current.modified.duration_since(indexed) }; time_diff.map_or(true, |difference| difference.as_secs() > 10) } @@ -458,12 +514,15 @@ impl MediaScanner { // watcher event that rescans a single folder used to load every row. debug!("Loading existing files from database..."); let canonical_root_str = canonical_root.to_string_lossy().into_owned(); - let mut existing_files_map: HashMap = self + let key = RootRelative { + root: &canonical_root, + }; + let mut existing_files_map: HashMap, IndexedFile> = self .database_manager .load_file_fingerprints_under(&canonical_root_str) .await? .into_iter() - .map(IndexedFile::split) + .map(|fingerprint| IndexedFile::split(fingerprint, &key)) .collect(); let existing_in_root = existing_files_map.len(); debug!("Loaded {existing_in_root} existing files from database"); @@ -471,6 +530,15 @@ impl MediaScanner { // Walk on a blocking thread, handing paths over as they are found rather // than collecting the library into a `Vec` first. The channel is bounded, // so a slow consumer backs the walker up instead of buffering. + // + // Serially, because the channel is the only bound there is. jwalk's + // parallel mode reads directories on the rayon pool as fast as it can + // and holds each one's entries until the iterator reaches it, so a + // walker blocked on a full channel stopped nothing: at 100,000 files it + // was 25 MB of entries read ahead — nearly the whole tree — at the scan's + // peak, and that peak is what the allocator keeps afterwards. One + // directory at a time costs no measurable time, because every path it + // yields is then `stat`ed, and that stage is already concurrent. let root_clone = canonical_root.clone(); let mut traversal_policy = policy.clone(); traversal_policy.root = canonical_root.clone(); @@ -482,7 +550,10 @@ impl MediaScanner { errors: Vec::new(), root_complete: true, }; - for entry in WalkDir::new(&root_clone).skip_hidden(false) { + for entry in WalkDir::new(&root_clone) + .skip_hidden(false) + .parallelism(jwalk::Parallelism::Serial) + { match entry { Ok(entry) if entry.file_type().is_file() => { let path = entry.path(); @@ -512,8 +583,11 @@ impl MediaScanner { }); let mut result = ScanResult::new(); - let mut files_to_insert: Vec = Vec::with_capacity(BATCH_SIZE); - let mut files_to_update: Vec = Vec::with_capacity(BATCH_SIZE); + // Empty until something changes: a `MediaFile` is over six hundred + // bytes, so reserving a batch of each up front held 1.3 MB through + // every scan of a library that turned out not to have changed. + let mut files_to_insert: Vec = Vec::new(); + let mut files_to_update: Vec = Vec::new(); let mut processed = 0_usize; // Classify each path with a single `stat`, several at a time. @@ -542,7 +616,7 @@ impl MediaScanner { // jwalk descendants inherit the already-canonical root. It does // not follow file symlinks, so no syscall is needed here. - let unchanged = match (existing_files_map.get_mut(&path), metadata) { + let unchanged = match (existing_files_map.get_mut(key.of(&path)), metadata) { (Some(existing), Some(metadata)) => { // Marking the record is what replaces a second set of every // path on disk: whatever is left unmarked is what is gone. @@ -567,6 +641,7 @@ impl MediaScanner { self.read_window( &mut pending_reads, &existing_files_map, + &key, &mut files_to_insert, &mut files_to_update, &mut result, @@ -592,6 +667,7 @@ impl MediaScanner { self.read_window( &mut pending_reads, &existing_files_map, + &key, &mut files_to_insert, &mut files_to_update, &mut result, @@ -617,7 +693,7 @@ impl MediaScanner { existing_files_map .iter() .filter(|(_, indexed)| !indexed.seen) - .map(|(path, _)| path.clone()) + .map(|(relative, _)| key.absolute(relative)) .collect() } else { // A partial walk cannot tell "absent" from "unreadable". Where only @@ -627,13 +703,13 @@ impl MediaScanner { .iter() .filter(|(_, indexed)| !indexed.seen) .filter(|_| traversal.root_complete) - .filter(|(path, _)| { + .map(|(relative, _)| key.absolute(relative)) + .filter(|path| { !traversal .uncertain_prefixes .iter() .any(|prefix| path.starts_with(prefix)) }) - .map(|(path, _)| path.clone()) .collect() }; From 0329410a45af46d0d7211ddd0f300552f7826d17 Mon Sep 17 00:00:00 2001 From: vyrti Date: Wed, 23 Sep 2026 15:41:41 +0300 Subject: [PATCH 02/12] Stop every AAC encoder from pinning 55 MB it never uses MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit libxaac sizes an encoder for USAC whatever the profile: its state carries a complete USAC encoder by value and its API struct a USAC configuration per element, 44 MB and 12 MB. An AAC-LC encoder touches well under a megabyte of that, but the library clears every block it is handed, so all 55 MB became resident for as long as the encoder lived — for each browser fMP4 or HLS stream, each audio.aac request, whatever the channel count. xaac-rs already hands the encoder zeroed memory, so the clears are redundant. libxaac-sys now builds the encoder with IXHEAACE_ZEROED_ALLOC (through a LIBXAAC_ZEROED_ALLOC cmake option, as LIBXAAC_ARM_FLOAT_ABI is passed), which skips the five that cover freshly allocated blocks. That alone only helped the first encoder: the heap keeps freed blocks this size and clears a reused one to honour alloc_zeroed, which writes every page again. So on Unix xaac-rs maps blocks of a megabyte or more directly and unmaps them on drop; smaller blocks and other platforms keep the heap. Output is byte-identical to the unpatched encoder (20 s of stereo and of 5.1, compared with cmp). Measured: one encoder, RSS after create +55 MB -> +0 MB create/encode/drop, repeated +60 MB each -> ~1 MB server footprint after one audio.aac transcode 75 MB -> 19 MB DTS film as browser fMP4 86 MB -> 32 MB 6 concurrent AAC encodes 388 MB -> 48 MB (max RSS 413 -> 65) --- Cargo.lock | 1 + crates/vendor/libxaac-sys/build.rs | 9 +++ .../libxaac-sys/libxaac/cmake/utils.cmake | 6 ++ .../libxaac/encoder/ixheaace_api.c | 16 +++++ crates/vendor/xaac-rs/Cargo.toml | 5 ++ crates/vendor/xaac-rs/src/util.rs | 62 ++++++++++++++++--- 6 files changed, 91 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e080fb1..ea9fa69 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3865,6 +3865,7 @@ dependencies = [ name = "xaac-rs" version = "0.2.0" dependencies = [ + "libc", "libxaac-sys", "pyo3", ] diff --git a/crates/vendor/libxaac-sys/build.rs b/crates/vendor/libxaac-sys/build.rs index 06e3978..85a5eed 100644 --- a/crates/vendor/libxaac-sys/build.rs +++ b/crates/vendor/libxaac-sys/build.rs @@ -92,6 +92,15 @@ fn main() { cmake_cmd.arg(format!("-DLIBXAAC_ARM_FLOAT_ABI={abi}")); } + // The encoder clears every block it is given, and one of those blocks + // holds a complete USAC encoder even when the profile is AAC-LC — so the + // clear alone made about 55 MB resident per encoder, none of it ever + // used. xaac-rs, the only caller, hands over memory that is already zero + // (freshly mapped for the large blocks), which lets the encoder skip it + // and leaves the untouched pages unallocated. Any other caller of this + // crate's encoder must keep that promise. + cmake_cmd.arg("-DLIBXAAC_ZEROED_ALLOC=ON"); + run(&mut cmake_cmd); // Never `Debug`. MSVC's Debug configuration adds /RTC1, which it will // not accept beside the /O2 this library's cmake asks for, and it links diff --git a/crates/vendor/libxaac-sys/libxaac/cmake/utils.cmake b/crates/vendor/libxaac-sys/libxaac/cmake/utils.cmake index a36d7c7..ea9bc61 100644 --- a/crates/vendor/libxaac-sys/libxaac/cmake/utils.cmake +++ b/crates/vendor/libxaac-sys/libxaac/cmake/utils.cmake @@ -76,6 +76,12 @@ function(libxaac_add_definitions) add_definitions(-DX86_64 -D_X86_64_) endif() add_definitions(-DLOUDNESS_LEVELING_SUPPORT) + # libxaac-sys's build.rs passes -DLIBXAAC_ZEROED_ALLOC=ON because xaac-rs, the + # only caller, allocates the encoder's memory already zeroed. See + # IXHEAACE_ZEROED_ALLOC in encoder/ixheaace_api.c for what that saves. + if(LIBXAAC_ZEROED_ALLOC) + add_definitions(-DIXHEAACE_ZEROED_ALLOC) + endif() endfunction() # Adds libraries needed for executables diff --git a/crates/vendor/libxaac-sys/libxaac/encoder/ixheaace_api.c b/crates/vendor/libxaac-sys/libxaac/encoder/ixheaace_api.c index 943d6f9..0f28f5a 100644 --- a/crates/vendor/libxaac-sys/libxaac/encoder/ixheaace_api.c +++ b/crates/vendor/libxaac-sys/libxaac/encoder/ixheaace_api.c @@ -1581,8 +1581,16 @@ 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; } +/* IXHEAACE_ZEROED_ALLOC: every malloc_xheaace callback this encoder is built + * for returns memory that is already zero (xaac-rs maps fresh pages for the + * large blocks). Clearing it again is not merely redundant: the state carries a + * full USAC encoder by value, which an AAC-LC encoder never touches, and the + * memset made all of it resident: about 55 MB per encoder instead of under + * one. Defined through LIBXAAC_ZEROED_ALLOC in cmake/utils.cmake. */ +#ifndef IXHEAACE_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); +#endif 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] % @@ -1597,7 +1605,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; +#ifndef IXHEAACE_ZEROED_ALLOC memset(pstr_api_struct->pp_mem[i_idx], 0, pstr_api_struct->pstr_mem_info[i_idx].ui_size); +#endif pstr_api_struct->pp_mem[i_idx] = pv_value; @@ -1749,7 +1759,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; +#ifndef IXHEAACE_ZEROED_ALLOC memset(pstr_api_struct->pstr_state, 0, sizeof(*(pstr_api_struct->pstr_state))); +#endif pstr_api_struct->pstr_state->inp_delay = (FLOAT32 *)((WORD8 *)pstr_state + offset_size); offset_size = ia_enhaacplus_enc_sizeof_delay_buffer( @@ -3570,7 +3582,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; } +#ifndef IXHEAACE_ZEROED_ALLOC memset(pstr_output_config->arr_alloc_memory[pstr_output_config->malloc_count], 0, ui_api_size); +#endif pstr_output_config->ui_rem = (SIZE_T)((SIZE_T)pstr_output_config->arr_alloc_memory[pstr_output_config->malloc_count] % @@ -3582,7 +3596,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; +#ifndef IXHEAACE_ZEROED_ALLOC memset(pstr_api_struct, 0, sizeof(*pstr_api_struct)); +#endif ixheaace_set_default_config(pstr_api_struct, pstr_input_config); diff --git a/crates/vendor/xaac-rs/Cargo.toml b/crates/vendor/xaac-rs/Cargo.toml index 830147f..39933b9 100644 --- a/crates/vendor/xaac-rs/Cargo.toml +++ b/crates/vendor/xaac-rs/Cargo.toml @@ -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"] diff --git a/crates/vendor/xaac-rs/src/util.rs b/crates/vendor/xaac-rs/src/util.rs index c418756..f224256 100644 --- a/crates/vendor/xaac-rs/src/util.rs +++ b/crates/vendor/xaac-rs/src/util.rs @@ -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::()).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::()).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::(); let total_size = size as usize + requested_align + header_words; - let layout = - Layout::from_size_align(total_size, std::mem::align_of::()).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(); } @@ -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::()).expect("valid layout"); - unsafe { - dealloc(base, layout); - } + unsafe { release_block(base, total_size) }; } pub(crate) fn encoder_alloc() -> Option *mut std::ffi::c_void> { From 1284a88d552b6413d07e1c1c1e643173df2c3ba0 Mon Sep 17 00:00:00 2001 From: vyrti Date: Wed, 23 Sep 2026 16:26:52 +0300 Subject: [PATCH 03/12] Give the scan's index of one root a type of its own The fingerprint map and the root its keys are relative to travelled as two arguments, which took read_window past clippy's argument limit and left every caller translating paths by hand. IndexedTree owns both: lookups take the walk's absolute paths, and deletions come back out absolute. --- crates/vuio-core/src/media/scanner.rs | 134 ++++++++++++++------------ 1 file changed, 70 insertions(+), 64 deletions(-) diff --git a/crates/vuio-core/src/media/scanner.rs b/crates/vuio-core/src/media/scanner.rs index 09a7802..f6f63ee 100644 --- a/crates/vuio-core/src/media/scanner.rs +++ b/crates/vuio-core/src/media/scanner.rs @@ -32,7 +32,7 @@ const READ_WINDOW: usize = BATCH_SIZE; /// match. Times are whole seconds since the epoch because that is all the index /// stores — a `SystemTime` spent sixteen bytes carrying nanoseconds that were /// always zero — and the key is a boxed path below the root rather than an -/// owned path from it (see [`RootRelative`]). At 100,000 files that took the +/// owned path from it (see [`IndexedTree`]). At 100,000 files that took the /// table from 10.1 MB to 7.1 MB, and every key is shorter by the root. struct IndexedFile { id: i64, @@ -46,31 +46,74 @@ struct IndexedFile { seen: bool, } -/// A path as the scan's map keys it: relative to the root being scanned. +/// Everything indexed under the root being scanned, keyed by the path below +/// that root. /// /// Every file under one root repeats that root's prefix, and there is one key /// per file. Stripping it is free — the walk only ever produces paths under the /// root, and a deletion puts it back with a `join`. A record that somehow lies /// outside the root keeps its absolute path, which cannot collide with a /// relative one. -struct RootRelative<'a> { +struct IndexedTree<'a> { root: &'a Path, + files: HashMap, IndexedFile>, } -impl<'a> RootRelative<'a> { - fn of<'p>(&self, path: &'p Path) -> &'p Path { +impl<'a> IndexedTree<'a> { + /// Key the loaded records, moving each path rather than copying it. + fn new(root: &'a Path, fingerprints: Vec) -> Self { + let files = fingerprints + .into_iter() + .map(|fingerprint| { + let FileFingerprint { + id, + path, + size, + modified, + created_at, + tags_version, + } = fingerprint; + let key = match path.strip_prefix(root) { + Ok(relative) => relative.into(), + Err(_) => path.into_boxed_path(), + }; + let file = IndexedFile { + id, + size, + modified_secs: epoch_secs(modified), + created_at_secs: epoch_secs(created_at), + tags_version, + seen: false, + }; + (key, file) + }) + .collect(); + Self { root, files } + } + + fn key<'p>(&self, path: &'p Path) -> &'p Path { path.strip_prefix(self.root).unwrap_or(path) } - fn owned(&self, path: PathBuf) -> Box { - match path.strip_prefix(self.root) { - Ok(relative) => relative.into(), - Err(_) => path.into_boxed_path(), - } + fn get(&self, path: &Path) -> Option<&IndexedFile> { + self.files.get(self.key(path)) + } + + fn get_mut(&mut self, path: &Path) -> Option<&mut IndexedFile> { + let key = self.key(path); + self.files.get_mut(key) + } + + fn len(&self) -> usize { + self.files.len() } - fn absolute(&self, key: &Path) -> PathBuf { - self.root.join(key) + /// Every record the walk did not produce, as absolute paths. + fn unseen(&self) -> impl Iterator + '_ { + self.files + .iter() + .filter(|(_, indexed)| !indexed.seen) + .map(|(key, _)| self.root.join(key)) } } @@ -84,30 +127,6 @@ fn from_epoch_secs(secs: u64) -> SystemTime { } impl IndexedFile { - /// Split a loaded record into the map's key and value, moving the path - /// rather than copying it into both halves. - fn split(fingerprint: FileFingerprint, key: &RootRelative<'_>) -> (Box, Self) { - let FileFingerprint { - id, - path, - size, - modified, - created_at, - tags_version, - } = fingerprint; - ( - key.owned(path), - Self { - id, - size, - modified_secs: epoch_secs(modified), - created_at_secs: epoch_secs(created_at), - tags_version, - seen: false, - }, - ) - } - fn modified(&self) -> SystemTime { from_epoch_secs(self.modified_secs) } @@ -127,8 +146,7 @@ impl MediaScanner { async fn read_window( &self, paths: &mut Vec, - existing_files_map: &HashMap, IndexedFile>, - key: &RootRelative<'_>, + indexed: &IndexedTree<'_>, files_to_insert: &mut Vec, files_to_update: &mut Vec, result: &mut ScanResult, @@ -152,7 +170,7 @@ impl MediaScanner { }; result.files_read += 1; - match existing_files_map.get(key.of(&path)) { + match indexed.get(&path) { Some(existing) => { if self.fingerprint_needs_update(existing, ¤t_file) { let mut updated = current_file; @@ -514,17 +532,13 @@ impl MediaScanner { // watcher event that rescans a single folder used to load every row. debug!("Loading existing files from database..."); let canonical_root_str = canonical_root.to_string_lossy().into_owned(); - let key = RootRelative { - root: &canonical_root, - }; - let mut existing_files_map: HashMap, IndexedFile> = self - .database_manager - .load_file_fingerprints_under(&canonical_root_str) - .await? - .into_iter() - .map(|fingerprint| IndexedFile::split(fingerprint, &key)) - .collect(); - let existing_in_root = existing_files_map.len(); + let mut indexed = IndexedTree::new( + &canonical_root, + self.database_manager + .load_file_fingerprints_under(&canonical_root_str) + .await?, + ); + let existing_in_root = indexed.len(); debug!("Loaded {existing_in_root} existing files from database"); // Walk on a blocking thread, handing paths over as they are found rather @@ -616,7 +630,7 @@ impl MediaScanner { // jwalk descendants inherit the already-canonical root. It does // not follow file symlinks, so no syscall is needed here. - let unchanged = match (existing_files_map.get_mut(key.of(&path)), metadata) { + let unchanged = match (indexed.get_mut(&path), metadata) { (Some(existing), Some(metadata)) => { // Marking the record is what replaces a second set of every // path on disk: whatever is left unmarked is what is gone. @@ -640,8 +654,7 @@ impl MediaScanner { if pending_reads.len() >= READ_WINDOW { self.read_window( &mut pending_reads, - &existing_files_map, - &key, + &indexed, &mut files_to_insert, &mut files_to_update, &mut result, @@ -666,8 +679,7 @@ impl MediaScanner { if !pending_reads.is_empty() { self.read_window( &mut pending_reads, - &existing_files_map, - &key, + &indexed, &mut files_to_insert, &mut files_to_update, &mut result, @@ -690,20 +702,14 @@ impl MediaScanner { let reconcile_deletions = traversal.root_complete && traversal.uncertain_prefixes.is_empty(); let files_to_remove: Vec = if reconcile_deletions { - existing_files_map - .iter() - .filter(|(_, indexed)| !indexed.seen) - .map(|(relative, _)| key.absolute(relative)) - .collect() + indexed.unseen().collect() } else { // A partial walk cannot tell "absent" from "unreadable". Where only // some prefixes are in doubt, everything outside them is still // decidable. - existing_files_map - .iter() - .filter(|(_, indexed)| !indexed.seen) + indexed + .unseen() .filter(|_| traversal.root_complete) - .map(|(relative, _)| key.absolute(relative)) .filter(|path| { !traversal .uncertain_prefixes From 174500859d51fb0b8f5689d5fadde7351ae1649d Mon Sep 17 00:00:00 2001 From: vyrti Date: Wed, 23 Sep 2026 16:32:07 +0300 Subject: [PATCH 04/12] Load a scan's index of its root a page at a time The scan built its compact map from load_file_fingerprints_under, which returned the whole subtree at once: every record with its absolute path, in a vector that grew by doubling. At 100,000 files that was 18 MB of paths and a 10 MB vector alive beside the map being built from them, and it had become the scan's peak. The loader now takes a cursor and a limit and returns one page in path order, a keyset query that seeks the path index to where the previous page stopped. The scanner converts each 4,096-row page (about a megabyte) into the map before reading the next, so the load costs a page on top of the map instead of the subtree twice over. A cursor below the range is ignored rather than allowed to widen it. --- crates/vuio-core/src/database/mod.rs | 12 ++++- .../src/database/sqlite/media_repo/basic.rs | 20 +++++-- crates/vuio-core/src/database/sqlite/tests.rs | 54 +++++++++++++++++++ .../vuio-core/src/database/sqlite/traits.rs | 10 +++- crates/vuio-core/src/media/scanner.rs | 46 ++++++++++++---- 5 files changed, 126 insertions(+), 16 deletions(-) diff --git a/crates/vuio-core/src/database/mod.rs b/crates/vuio-core/src/database/mod.rs index 7b86d5b..88165ce 100644 --- a/crates/vuio-core/src/database/mod.rs +++ b/crates/vuio-core/src/database/mod.rs @@ -924,15 +924,25 @@ pub trait MediaRepository: Send + Sync { /// Load compact scanner comparison records instead of complete media metadata. async fn load_file_fingerprints(&self) -> Result>; - /// The same, for one subtree. + /// The same, for one subtree, one page at a time: at most `limit` records + /// whose paths sort after `after` (from the start of the subtree when + /// `None`), in path order. /// /// A scan compares what is on disk against what is indexed, and it only ever /// scans one root — so loading the whole table means every other library's /// rows are held in memory for nothing. That is most of the cost when a /// watcher event rescans a single folder. + /// + /// Paged because the scan keeps its own compact copy of each record, and + /// receiving the subtree in one piece meant holding every absolute path twice + /// over while that copy was built: at 100,000 files, 28 MB of rows beside + /// the map made from them. The caller passes the last path of one page as + /// `after` for the next, and a page shorter than `limit` is the last. async fn load_file_fingerprints_under( &self, canonical_prefix: &str, + after: Option<&str>, + limit: usize, ) -> Result>; /// One page of fingerprints, ordered by id, starting after `after_id`. diff --git a/crates/vuio-core/src/database/sqlite/media_repo/basic.rs b/crates/vuio-core/src/database/sqlite/media_repo/basic.rs index f9b9e1f..193077c 100644 --- a/crates/vuio-core/src/database/sqlite/media_repo/basic.rs +++ b/crates/vuio-core/src/database/sqlite/media_repo/basic.rs @@ -166,17 +166,31 @@ impl SqliteDatabase { pub(in crate::database::sqlite) async fn load_file_fingerprints_under_impl( &self, canonical_prefix: String, + after: Option, + limit: usize, ) -> Result> { self.execute_read(move |connection| { - // A range on `path` rather than a `LIKE`, so the primary key index + // A range on `path` rather than a `LIKE`, so the index on `path` // serves it. `subtree_range` stops at a component boundary, which is // what keeps `/media/Film` from matching `/media/Films`. let (start, end) = SqliteDatabase::subtree_range(&canonical_prefix); + // The cursor replaces the lower bound rather than adding a second + // one, so each page is a seek to where the last one stopped instead + // of a walk from the start of the subtree. A cursor below the range + // would widen it, so that one is ignored. + let (comparison, lower) = match after { + Some(after) if after >= start => (">", after), + _ => (">=", start), + }; let mut statement = connection.prepare_cached(&format!( - "SELECT {FINGERPRINT_COLUMNS} FROM media_files WHERE path >= ? AND path < ?" + "SELECT {FINGERPRINT_COLUMNS} FROM media_files \ + WHERE path {comparison} ? AND path < ? ORDER BY path LIMIT ?" ))?; let fingerprints = statement - .query_map([&start, &end], schema::fingerprint_from_row)? + .query_map( + rusqlite::params![lower, end, limit as i64], + schema::fingerprint_from_row, + )? .collect::>>()?; Ok(fingerprints) }) diff --git a/crates/vuio-core/src/database/sqlite/tests.rs b/crates/vuio-core/src/database/sqlite/tests.rs index 0260f81..64d1375 100644 --- a/crates/vuio-core/src/database/sqlite/tests.rs +++ b/crates/vuio-core/src/database/sqlite/tests.rs @@ -376,6 +376,60 @@ async fn directory_counts_return_to_zero_when_the_last_file_goes() { assert_eq!(remaining, 0, "empty directories must not linger"); } +/// A scan loads its root's records a page at a time. The pages have to tile the +/// subtree exactly — every record once, in order, nothing from a sibling whose +/// name merely starts the same way — and a cursor from outside the range must +/// not widen it. +#[tokio::test] +async fn fingerprints_under_a_root_come_back_in_pages_that_tile_it() { + let temp = tempdir().unwrap(); + let db = database(&temp, "pages").await; + + let mut inside: Vec = (0..7).map(|i| format!("/media/Film/{i:02}.mkv")).collect(); + inside.push("/media/Film/nested/deep.mkv".to_owned()); + // Either side of the range: '.' sorts just before '/', and "/media/Film0" + // is where the range ends. + let outside = [ + "/media/A.mkv", + "/media/Film.mkv", + "/media/Film0.mkv", + "/media/Films/other.mkv", + ]; + let files: Vec = inside + .iter() + .map(String::as_str) + .chain(outside) + .map(|path| MediaFile::new(PathBuf::from(path), 1, "video/x-matroska".to_owned())) + .collect(); + db.bulk_store_media_files(&files).await.unwrap(); + + let mut seen = Vec::new(); + let mut pages = Vec::new(); + let mut after: Option = None; + loop { + let page = db + .load_file_fingerprints_under("/media/Film", after.as_deref(), 3) + .await + .unwrap(); + pages.push(page.len()); + after = page.last().map(|f| f.path.to_string_lossy().into_owned()); + let last = page.len() < 3; + seen.extend(page.into_iter().map(|f| f.path.to_string_lossy().into_owned())); + if last { + break; + } + } + inside.sort(); + assert_eq!(seen, inside); + assert_eq!(pages, [3, 3, 2]); + + let widened = db + .load_file_fingerprints_under("/media/Film", Some("/a"), 100) + .await + .unwrap(); + assert_eq!(widened.len(), inside.len(), "a cursor below the range is ignored"); +} + #[tokio::test] async fn rebuilding_the_directory_tree_reproduces_incremental_maintenance() { let temp = tempdir().unwrap(); diff --git a/crates/vuio-core/src/database/sqlite/traits.rs b/crates/vuio-core/src/database/sqlite/traits.rs index 08514bd..fb5c8e4 100644 --- a/crates/vuio-core/src/database/sqlite/traits.rs +++ b/crates/vuio-core/src/database/sqlite/traits.rs @@ -72,8 +72,16 @@ impl MediaRepository for SqliteDatabase { async fn load_file_fingerprints_under( &self, canonical_prefix: &str, + after: Option<&str>, + limit: usize, ) -> Result> { - SqliteDatabase::load_file_fingerprints_under_impl(self, canonical_prefix.to_owned()).await + SqliteDatabase::load_file_fingerprints_under_impl( + self, + canonical_prefix.to_owned(), + after.map(str::to_owned), + limit, + ) + .await } async fn load_file_fingerprints_after( diff --git a/crates/vuio-core/src/media/scanner.rs b/crates/vuio-core/src/media/scanner.rs index f6f63ee..adb225c 100644 --- a/crates/vuio-core/src/media/scanner.rs +++ b/crates/vuio-core/src/media/scanner.rs @@ -21,6 +21,13 @@ const WALK_QUEUE: usize = 4096; /// write. const READ_WINDOW: usize = BATCH_SIZE; +/// How many indexed records to load at a time. +/// +/// Each page is converted into the scan's own compact form before the next is +/// read, so this — about a megabyte of rows — rather than the size of the +/// library is what the load costs on top of the map it builds. +const FINGERPRINT_PAGE: usize = 4096; + /// What a scan needs to know about a file it may already have indexed. /// /// Deliberately not [`FileFingerprint`]: that carries the path, and this lives @@ -60,8 +67,16 @@ struct IndexedTree<'a> { } impl<'a> IndexedTree<'a> { - /// Key the loaded records, moving each path rather than copying it. - fn new(root: &'a Path, fingerprints: Vec) -> Self { + fn new(root: &'a Path) -> Self { + Self { + root, + files: HashMap::new(), + } + } + + /// Key one page of loaded records, moving each path rather than copying it. + fn extend(&mut self, fingerprints: Vec) { + let root = self.root; let files = fingerprints .into_iter() .map(|fingerprint| { @@ -86,9 +101,8 @@ impl<'a> IndexedTree<'a> { seen: false, }; (key, file) - }) - .collect(); - Self { root, files } + }); + self.files.extend(files); } fn key<'p>(&self, path: &'p Path) -> &'p Path { @@ -532,12 +546,22 @@ impl MediaScanner { // watcher event that rescans a single folder used to load every row. debug!("Loading existing files from database..."); let canonical_root_str = canonical_root.to_string_lossy().into_owned(); - let mut indexed = IndexedTree::new( - &canonical_root, - self.database_manager - .load_file_fingerprints_under(&canonical_root_str) - .await?, - ); + let mut indexed = IndexedTree::new(&canonical_root); + let mut after: Option = None; + loop { + let page = self + .database_manager + .load_file_fingerprints_under(&canonical_root_str, after.as_deref(), FINGERPRINT_PAGE) + .await?; + let last_page = page.len() < FINGERPRINT_PAGE; + after = page + .last() + .map(|fingerprint| fingerprint.path.to_string_lossy().into_owned()); + indexed.extend(page); + if last_page { + break; + } + } let existing_in_root = indexed.len(); debug!("Loaded {existing_in_root} existing files from database"); From f9f015834ebe63adfd998c99f2fb9c2455d77b79 Mon Sep 17 00:00:00 2001 From: vyrti Date: Wed, 23 Sep 2026 16:32:07 +0300 Subject: [PATCH 05/12] Hand the memory a large scan freed back to the system Both the macOS allocator and glibc keep freed pages mapped for reuse, so whatever a scan peaked at stayed counted against the process for the rest of its run: after a 100,000-file startup scan, with the scan's own peak already reduced, 30 MB of malloc memory was still dirty for 17 MB in use. Once a scan that covered at least 10,000 files has dropped its index, the scanner asks the allocator to release what is free (malloc_zone_pressure_relief on macOS, malloc_trim on glibc; nothing elsewhere), on the blocking pool. A watcher's rescan of one folder is below the threshold and never pays for the call. --- crates/vuio-core/src/media/scanner.rs | 13 +++++++++++ crates/vuio-core/src/platform/mod.rs | 33 +++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/crates/vuio-core/src/media/scanner.rs b/crates/vuio-core/src/media/scanner.rs index adb225c..61c4cf0 100644 --- a/crates/vuio-core/src/media/scanner.rs +++ b/crates/vuio-core/src/media/scanner.rs @@ -28,6 +28,10 @@ const READ_WINDOW: usize = BATCH_SIZE; /// library is what the load costs on top of the map it builds. const FINGERPRINT_PAGE: usize = 4096; +/// How large a scan has to be before the memory it freed is handed back to the +/// system. See [`crate::platform::release_free_memory`]. +const RELEASE_AFTER_FILES: usize = 10_000; + /// What a scan needs to know about a file it may already have indexed. /// /// Deliberately not [`FileFingerprint`]: that carries the path, and this lives @@ -765,6 +769,15 @@ impl MediaScanner { result.files_read ); + // The index of the root is the scan's largest allocation and is gone + // now. After a large scan the allocator would otherwise keep the pages + // it freed for the rest of the run; a watcher's rescan of one folder + // leaves too little behind to be worth the call. + drop(indexed); + if total_files.max(existing_in_root) >= RELEASE_AFTER_FILES { + tokio::task::spawn_blocking(crate::platform::release_free_memory); + } + Ok(result) } diff --git a/crates/vuio-core/src/platform/mod.rs b/crates/vuio-core/src/platform/mod.rs index 344770d..c163945 100644 --- a/crates/vuio-core/src/platform/mod.rs +++ b/crates/vuio-core/src/platform/mod.rs @@ -24,6 +24,39 @@ pub use error::{ PlatformResult, WindowsError, }; +/// Hand memory the allocator is holding, but no longer using, back to the +/// system. +/// +/// A scan of a large library peaks well above what the server holds once it +/// is done, and both the macOS and the glibc allocator keep the pages that peak +/// freed mapped for reuse. Nothing the server does next needs them back soon, +/// so after such a scan they are returned rather than counted against it for +/// the rest of its run. A no-op where the allocator has no call for this. +pub fn release_free_memory() { + #[cfg(target_os = "macos")] + { + unsafe extern "C" { + fn malloc_zone_pressure_relief( + zone: *mut libc::malloc_zone_t, + goal: libc::size_t, + ) -> libc::size_t; + } + // SAFETY: a null zone means every zone and a zero goal means as much as + // each can give back; the call only releases pages that are free. + unsafe { + malloc_zone_pressure_relief(std::ptr::null_mut(), 0); + } + } + #[cfg(all(target_os = "linux", target_env = "gnu"))] + { + // SAFETY: `malloc_trim` has no preconditions; it only releases free + // memory from the top of the heap and from each arena. + unsafe { + libc::malloc_trim(0); + } + } +} + /// Operating system types supported by the platform abstraction layer #[derive(Debug, Clone, PartialEq, Eq)] pub enum OsType { From 3e527db768e4e09d516fc55e20ad648afd8ed5fb Mon Sep 17 00:00:00 2001 From: vyrti Date: Wed, 23 Sep 2026 16:32:24 +0300 Subject: [PATCH 06/12] Lower the transcode caches' ceilings to what they are used for Three caches in TranscodeState could together hold about 136 MB for the life of the process, and every entry past the first few was insurance against a request that rarely comes: segments 48 MB -> 24 MB what is asked for twice is a segment just played (a seek back, a re-buffer), so only the recent end of each stream earns its place seek runs 64 MB -> 24 MB eviction is oldest-first and a television's repeats come at the end of its binary search, once the probes have narrowed to one group of pictures; those last runs are what is kept indexes 8 -> 4 ~3 MB each for a two-hour track, needed across the few requests that open one file The worst case falls from about 136 MB to 60 MB. Entry counts are unchanged, and none of this touches a stream that is playing. --- .../vuio-core/src/media/transcode/session.rs | 28 ++++++++++++++----- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/crates/vuio-core/src/media/transcode/session.rs b/crates/vuio-core/src/media/transcode/session.rs index 331dc7c..ad95cd3 100644 --- a/crates/vuio-core/src/media/transcode/session.rs +++ b/crates/vuio-core/src/media/transcode/session.rs @@ -18,9 +18,13 @@ use super::AudioPlan; #[cfg(all(feature = "transcode-aac", feature = "casting"))] use super::TrackRates; -/// How many indexes to keep. A two-hour AC-3 track indexes to roughly 3 MB, so -/// this is single-digit megabytes for a household's worth of open streams. -const MAX_CACHED_INDEXES: usize = 8; +/// How many indexes to keep. A two-hour AC-3 track indexes to roughly 3 MB. +/// +/// An index earns its place across the handful of requests a renderer makes +/// while it opens and scrubs one file, so the count only has to cover the files +/// being opened at the same time. Four is a household's worth and holds 12 MB +/// at most; eight held 24 MB for streams long since settled. +const MAX_CACHED_INDEXES: usize = 4; /// Identifies a cached index. The file's size and high-resolution metadata /// marker are part of the key so replacing a file in place invalidates its @@ -90,8 +94,13 @@ impl IndexKey { /// /// A segment of 1080p video is single-digit megabytes, so a count alone would /// bound the wrong thing on a large file and the wrong thing on a small one. +/// +/// What gets asked for twice is a segment just played — a seek back, a stall +/// that re-buffers — so the cache only needs the recent end of what is +/// playing: 24 MB is several 1080p segments of each of a few browsers. It was +/// 48 MB, held for the life of the process once anyone had watched a film. const MAX_CACHED_SEGMENTS: usize = 24; -const MAX_CACHED_SEGMENT_BYTES: usize = 48 * 1024 * 1024; +const MAX_CACHED_SEGMENT_BYTES: usize = 24 * 1024 * 1024; /// Identifies the first run of packets a seeked response opens with. /// @@ -118,8 +127,13 @@ pub struct ChunkKey { /// /// One is a fraction of a second of film, so single-digit megabytes each on a /// high-bitrate feature — a count alone would bound the wrong thing. +/// +/// Eviction is oldest-first, and the repeats come at the end of a seek, when +/// the probes have narrowed to one group of pictures — so what a seek needs +/// back is the few runs it produced last, not all of them. 24 MB keeps those +/// for a high-bitrate film; it was 64 MB. const MAX_CACHED_CHUNKS: usize = 32; -const MAX_CACHED_CHUNK_BYTES: usize = 64 * 1024 * 1024; +const MAX_CACHED_CHUNK_BYTES: usize = 24 * 1024 * 1024; /// How many films' soundtrack measurements to keep. /// @@ -378,8 +392,8 @@ mod tests { track: 2, seq, }; - // Four segments of 16 MB: the fourth must push the first out, because - // the byte ceiling binds long before the entry count does. + // Four segments of 16 MB: the first is pushed out, because the byte + // ceiling binds long before the entry count does. for seq in 0..4 { state .remember_segment(key(seq), bytes::Bytes::from(vec![0u8; 16 * 1024 * 1024])) From 49c7ba4887eb83575b650b7ca9ebdc2d6700a8b4 Mon Sep 17 00:00:00 2001 From: vyrti Date: Wed, 23 Sep 2026 16:32:24 +0300 Subject: [PATCH 07/12] Key the watcher's file-id cache relative to its watch roots MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The cache pairs the halves of a rename on macOS and Windows and holds up to two generations of 25,000 paths. Every entry was an absolute PathBuf, so each one repeated its root's prefix: in a profile of a 100,000-file library it was the largest thing in the idle heap, 6.4 MB for one generation. Entries are now kept per watch root, keyed by a boxed path below it, which saves the root's length plus eight bytes per entry — 2.4 MB at the cap for a 40-byte root. A directory the watcher sees created inside a root is seeded into that root rather than registered as another, so the set of roots cannot grow with the library. Lookups still allocate nothing; removal drops a subtree from the root that holds it, or the whole root when that is what was removed. --- crates/vuio-core/src/watcher/file_ids.rs | 143 ++++++++++++++++++++--- 1 file changed, 130 insertions(+), 13 deletions(-) diff --git a/crates/vuio-core/src/watcher/file_ids.rs b/crates/vuio-core/src/watcher/file_ids.rs index c3bf75d..0bacf43 100644 --- a/crates/vuio-core/src/watcher/file_ids.rs +++ b/crates/vuio-core/src/watcher/file_ids.rs @@ -42,15 +42,78 @@ pub const DEFAULT_CAPACITY: usize = 25_000; /// becomes `previous` and a fresh one takes over, so the oldest half is dropped /// wholesale rather than tracked with per-entry LRU bookkeeping. Lookups check /// both. See the module docs for what this trades away. +/// +/// A path under a watched root is stored relative to that root, boxed rather +/// than as an owned `PathBuf`. Every entry used to repeat its root's prefix, +/// and at the cap there are 50,000 of them, so this saves the root's length +/// plus eight bytes fifty thousand times: 2.4 MB for a 40-byte root. #[derive(Debug)] pub struct BoundedFileIdCache { - live: HashMap, - previous: HashMap, + /// Directories seeded as watch roots, in the order they were added. A + /// directory under one of them is part of it, not another root, which is + /// what keeps the folders a watcher sees created from accumulating here. + roots: Vec, + live: Generation, + previous: Generation, capacity: usize, /// Set once the seed walk has been cut short, so it is logged only the once. truncated: bool, } +/// Where a path is stored: under which root, and by what key. +#[derive(Clone, Copy)] +struct Slot<'p> { + /// Index into `roots`, or `None` for a path under no root. + root: Option, + key: &'p Path, +} + +/// One generation of entries: for each root, the paths below it; and, for +/// anything under no root, the absolute path. +#[derive(Debug, Default)] +struct Generation { + below: Vec, FileId>>, + outside: HashMap, FileId>, + len: usize, +} + +impl Generation { + fn get(&self, slot: Slot<'_>) -> Option<&FileId> { + match slot.root { + Some(index) => self.below.get(index)?.get(slot.key), + None => self.outside.get(slot.key), + } + } + + fn insert(&mut self, slot: Slot<'_>, id: FileId) { + let map = match slot.root { + Some(index) => { + if self.below.len() <= index { + self.below.resize_with(index + 1, HashMap::new); + } + &mut self.below[index] + } + None => &mut self.outside, + }; + if map.insert(slot.key.into(), id).is_none() { + self.len += 1; + } + } + + /// Drop `prefix` and everything under it. + fn remove_under(&mut self, roots: &[PathBuf], prefix: &Path) { + for (map, root) in self.below.iter_mut().zip(roots) { + if root.starts_with(prefix) { + map.clear(); + } else if let Ok(relative) = prefix.strip_prefix(root) { + map.retain(|key, _| !key.starts_with(relative)); + } + } + self.outside.retain(|key, _| !key.starts_with(prefix)); + self.len = self.below.iter().map(HashMap::len).sum::() + self.outside.len(); + } +} + impl BoundedFileIdCache { pub fn new() -> Self { Self::with_capacity(DEFAULT_CAPACITY) @@ -58,8 +121,9 @@ impl BoundedFileIdCache { pub fn with_capacity(capacity: usize) -> Self { Self { - live: HashMap::new(), - previous: HashMap::new(), + roots: Vec::new(), + live: Generation::default(), + previous: Generation::default(), capacity: capacity.max(1), truncated: false, } @@ -67,19 +131,34 @@ impl BoundedFileIdCache { /// Entries across both generations. pub fn len(&self) -> usize { - self.live.len() + self.previous.len() + self.live.len + self.previous.len } pub fn is_empty(&self) -> bool { self.len() == 0 } + /// The root `path` belongs to — the innermost, should roots nest — and its + /// key there. + fn slot<'p>(&self, path: &'p Path) -> Slot<'p> { + self.roots + .iter() + .enumerate() + .filter_map(|(index, root)| Some((index, root, path.strip_prefix(root).ok()?))) + .max_by_key(|(_, root, _)| root.as_os_str().len()) + .map_or(Slot { root: None, key: path }, |(index, _, key)| Slot { + root: Some(index), + key, + }) + } + /// Insert one path, rotating the generations if `live` is full. - fn remember(&mut self, path: PathBuf, id: FileId) { - if self.live.len() >= self.capacity && !self.live.contains_key(&path) { + fn remember(&mut self, path: &Path, id: FileId) { + let slot = self.slot(path); + if self.live.len >= self.capacity && self.live.get(slot).is_none() { self.previous = std::mem::take(&mut self.live); } - self.live.insert(path, id); + self.live.insert(slot, id); } /// Seed ids for a tree that already exists, stopping at the cap. @@ -87,6 +166,9 @@ impl BoundedFileIdCache { /// Unlike `remember` this never rotates: rotating mid-walk would let a large /// library evict its own entries and walk to the end for nothing. fn seed(&mut self, root: &Path, recursive: bool) { + if self.slot(root).root.is_none() { + self.roots.push(root.to_path_buf()); + } let mut pending = vec![root.to_path_buf()]; while let Some(dir) = pending.pop() { let entries = match std::fs::read_dir(&dir) { @@ -108,7 +190,8 @@ impl BoundedFileIdCache { } let path = entry.path(); if let Ok(id) = get_file_id(&path) { - self.live.insert(path.clone(), id); + let slot = self.slot(&path); + self.live.insert(slot, id); } if recursive && entry.file_type().is_ok_and(|kind| kind.is_dir()) { pending.push(path); @@ -126,7 +209,8 @@ impl Default for BoundedFileIdCache { impl FileIdCache for BoundedFileIdCache { fn cached_file_id(&self, path: &Path) -> Option> { - self.live.get(path).or_else(|| self.previous.get(path)) + let slot = self.slot(path); + self.live.get(slot).or_else(|| self.previous.get(slot)) } fn add_path(&mut self, path: &Path, recursive_mode: RecursiveMode) { @@ -135,13 +219,13 @@ impl FileIdCache for BoundedFileIdCache { return; } if let Ok(id) = get_file_id(path) { - self.remember(path.to_path_buf(), id); + self.remember(path, id); } } fn remove_path(&mut self, path: &Path) { - self.live.retain(|cached, _| !cached.starts_with(path)); - self.previous.retain(|cached, _| !cached.starts_with(path)); + self.live.remove_under(&self.roots, path); + self.previous.remove_under(&self.roots, path); } /// Deliberately does nothing. @@ -242,6 +326,39 @@ mod tests { assert_eq!(cache.len(), 0); } + #[test] + fn a_root_holds_its_paths_and_the_folders_created_under_it() { + let temp = tempfile::tempdir().unwrap(); + let album = temp.path().join("Album"); + fs::create_dir(&album).unwrap(); + write_files(&album, 3); + write_files(temp.path(), 2); + + let mut cache = BoundedFileIdCache::with_capacity(100); + cache.add_path(temp.path(), RecursiveMode::Recursive); + + // A folder the watcher sees created is part of the root it appeared in, + // not a root of its own — or every new folder would add one. + let created = temp.path().join("New"); + fs::create_dir(&created).unwrap(); + write_files(&created, 2); + cache.add_path(&created, RecursiveMode::Recursive); + assert_eq!(cache.roots.len(), 1); + assert!(cache.cached_file_id(&created.join("file_1.mp3")).is_some()); + + // The album and its three files go; the rest of the root stays. + let before = cache.len(); + cache.remove_path(&album); + assert_eq!(cache.len(), before - 4); + assert!(cache.cached_file_id(&album.join("file_0.mp3")).is_none()); + assert!(cache + .cached_file_id(&temp.path().join("file_0.mp3")) + .is_some()); + + cache.remove_path(temp.path()); + assert!(cache.is_empty()); + } + #[test] fn rescan_does_not_rewalk() { let temp = tempfile::tempdir().unwrap(); From b8c79f0219623d1165188bb27f4bb9202cb1f7b9 Mon Sep 17 00:00:00 2001 From: vyrti Date: Thu, 24 Sep 2026 00:04:31 +0300 Subject: [PATCH 08/12] Reduce peak memory use in streaming and library jobs --- crates/vendor/libxaac-sys/build.rs | 9 - crates/vendor/libxaac-sys/examples/sample.rs | 29 ++- .../libxaac-sys/libxaac/cmake/utils.cmake | 6 - .../libxaac/encoder/ixheaace_api.c | 61 +++--- .../libxaac/encoder/ixheaace_api.h | 4 + crates/vendor/libxaac-sys/src/bindings.rs | 5 + crates/vendor/xaac-rs/src/encoder.rs | 5 +- .../vuio-cast/src/client/request_tracker.rs | 20 +- crates/vuio-core/src/casting/airplay/mod.rs | 7 +- .../src/casting/airplay/transport.rs | 15 +- crates/vuio-core/src/database/conformance.rs | 16 ++ crates/vuio-core/src/database/mod.rs | 21 +- .../src/database/playlist_formats.rs | 99 ++++----- .../src/database/playlist_formats/tests.rs | 49 +++++ .../src/database/sqlite/directory.rs | 8 +- .../src/database/sqlite/media_repo/listing.rs | 29 ++- .../src/database/sqlite/mediainfo_repo.rs | 33 ++- .../vuio-core/src/database/sqlite/schema.rs | 4 +- crates/vuio-core/src/database/sqlite/tests.rs | 15 ++ .../vuio-core/src/database/sqlite/traits.rs | 25 ++- .../vuio-core/src/lifecycle/media/events.rs | 35 ++-- .../vuio-core/src/media/remux/fmp4_writer.rs | 128 ++++++++++-- crates/vuio-core/src/media/scanner.rs | 55 +++-- crates/vuio-core/src/media/tests.rs | 40 ++++ .../vuio-core/src/media/transcode/frames.rs | 28 ++- crates/vuio-core/src/media/transcode/plan.rs | 11 + .../vuio-core/src/media/transcode/session.rs | 192 ++++++++++++++++-- crates/vuio-core/src/media/transcode/ts.rs | 48 ++++- crates/vuio-core/src/media/transcode/video.rs | 58 +++++- crates/vuio-core/src/mediainfo/job.rs | 130 +++++++----- .../src/platform/filesystem/metadata.rs | 45 +++- crates/vuio-core/src/radio/engine.rs | 76 ++++--- crates/vuio-core/src/radio/frames.rs | 163 ++++++++++++--- crates/vuio-core/src/watcher/file_ids.rs | 84 ++++++++ crates/vuio-core/src/web/casting.rs | 13 +- crates/vuio-core/src/web/casting/helpers.rs | 10 +- crates/vuio-core/src/web/diagnostics.rs | 3 +- crates/vuio-core/src/web/remux_streaming.rs | 20 +- .../vuio-core/src/web/transcode_streaming.rs | 31 +-- .../tests/mediainfo_integration_tests.rs | 71 ++++++- docs/memory-audit.md | 120 +++++++++++ 41 files changed, 1459 insertions(+), 362 deletions(-) create mode 100644 docs/memory-audit.md diff --git a/crates/vendor/libxaac-sys/build.rs b/crates/vendor/libxaac-sys/build.rs index 85a5eed..06e3978 100644 --- a/crates/vendor/libxaac-sys/build.rs +++ b/crates/vendor/libxaac-sys/build.rs @@ -92,15 +92,6 @@ fn main() { cmake_cmd.arg(format!("-DLIBXAAC_ARM_FLOAT_ABI={abi}")); } - // The encoder clears every block it is given, and one of those blocks - // holds a complete USAC encoder even when the profile is AAC-LC — so the - // clear alone made about 55 MB resident per encoder, none of it ever - // used. xaac-rs, the only caller, hands over memory that is already zero - // (freshly mapped for the large blocks), which lets the encoder skip it - // and leaves the untouched pages unallocated. Any other caller of this - // crate's encoder must keep that promise. - cmake_cmd.arg("-DLIBXAAC_ZEROED_ALLOC=ON"); - run(&mut cmake_cmd); // Never `Debug`. MSVC's Debug configuration adds /RTC1, which it will // not accept beside the /O2 this library's cmake asks for, and it links diff --git a/crates/vendor/libxaac-sys/examples/sample.rs b/crates/vendor/libxaac-sys/examples/sample.rs index 425adc2..f746422 100644 --- a/crates/vendor/libxaac-sys/examples/sample.rs +++ b/crates/vendor/libxaac-sys/examples/sample.rs @@ -2,6 +2,7 @@ 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, @@ -9,17 +10,32 @@ use libxaac_sys::{ 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}"); @@ -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); diff --git a/crates/vendor/libxaac-sys/libxaac/cmake/utils.cmake b/crates/vendor/libxaac-sys/libxaac/cmake/utils.cmake index ea9bc61..a36d7c7 100644 --- a/crates/vendor/libxaac-sys/libxaac/cmake/utils.cmake +++ b/crates/vendor/libxaac-sys/libxaac/cmake/utils.cmake @@ -76,12 +76,6 @@ function(libxaac_add_definitions) add_definitions(-DX86_64 -D_X86_64_) endif() add_definitions(-DLOUDNESS_LEVELING_SUPPORT) - # libxaac-sys's build.rs passes -DLIBXAAC_ZEROED_ALLOC=ON because xaac-rs, the - # only caller, allocates the encoder's memory already zeroed. See - # IXHEAACE_ZEROED_ALLOC in encoder/ixheaace_api.c for what that saves. - if(LIBXAAC_ZEROED_ALLOC) - add_definitions(-DIXHEAACE_ZEROED_ALLOC) - endif() endfunction() # Adds libraries needed for executables diff --git a/crates/vendor/libxaac-sys/libxaac/encoder/ixheaace_api.c b/crates/vendor/libxaac-sys/libxaac/encoder/ixheaace_api.c index 0f28f5a..a5b3f22 100644 --- a/crates/vendor/libxaac-sys/libxaac/encoder/ixheaace_api.c +++ b/crates/vendor/libxaac-sys/libxaac/encoder/ixheaace_api.c @@ -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; @@ -1581,16 +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; } -/* IXHEAACE_ZEROED_ALLOC: every malloc_xheaace callback this encoder is built - * for returns memory that is already zero (xaac-rs maps fresh pages for the - * large blocks). Clearing it again is not merely redundant: the state carries a - * full USAC encoder by value, which an AAC-LC encoder never touches, and the - * memset made all of it resident: about 55 MB per encoder instead of under - * one. Defined through LIBXAAC_ZEROED_ALLOC in cmake/utils.cmake. */ -#ifndef IXHEAACE_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); -#endif + 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] % @@ -1605,9 +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; -#ifndef IXHEAACE_ZEROED_ALLOC - memset(pstr_api_struct->pp_mem[i_idx], 0, pstr_api_struct->pstr_mem_info[i_idx].ui_size); -#endif + 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; @@ -1759,9 +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; -#ifndef IXHEAACE_ZEROED_ALLOC - memset(pstr_api_struct->pstr_state, 0, sizeof(*(pstr_api_struct->pstr_state))); -#endif + 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( @@ -3561,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; @@ -3582,9 +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; } -#ifndef IXHEAACE_ZEROED_ALLOC - memset(pstr_output_config->arr_alloc_memory[pstr_output_config->malloc_count], 0, ui_api_size); -#endif + 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] % @@ -3596,9 +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; -#ifndef IXHEAACE_ZEROED_ALLOC - memset(pstr_api_struct, 0, sizeof(*pstr_api_struct)); -#endif + if (!zeroed_alloc) { + memset(pstr_api_struct, 0, sizeof(*pstr_api_struct)); + } ixheaace_set_default_config(pstr_api_struct, pstr_input_config); @@ -3646,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; } @@ -3853,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); } @@ -3866,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; diff --git a/crates/vendor/libxaac-sys/libxaac/encoder/ixheaace_api.h b/crates/vendor/libxaac-sys/libxaac/encoder/ixheaace_api.h index 7e197ed..a9c26e0 100644 --- a/crates/vendor/libxaac-sys/libxaac/encoder/ixheaace_api.h +++ b/crates/vendor/libxaac-sys/libxaac/encoder/ixheaace_api.h @@ -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); diff --git a/crates/vendor/libxaac-sys/src/bindings.rs b/crates/vendor/libxaac-sys/src/bindings.rs index 8ff7749..73ee44c 100644 --- a/crates/vendor/libxaac-sys/src/bindings.rs +++ b/crates/vendor/libxaac-sys/src/bindings.rs @@ -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, diff --git a/crates/vendor/xaac-rs/src/encoder.rs b/crates/vendor/xaac-rs/src/encoder.rs index ccb140c..010a5eb 100644 --- a/crates/vendor/xaac-rs/src/encoder.rs +++ b/crates/vendor/xaac-rs/src/encoder.rs @@ -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, ) diff --git a/crates/vuio-cast/src/client/request_tracker.rs b/crates/vuio-cast/src/client/request_tracker.rs index db89823..d4c4ac9 100644 --- a/crates/vuio-cast/src/client/request_tracker.rs +++ b/crates/vuio-cast/src/client/request_tracker.rs @@ -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) } @@ -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)); diff --git a/crates/vuio-core/src/casting/airplay/mod.rs b/crates/vuio-core/src/casting/airplay/mod.rs index c17fe77..f4532f4 100644 --- a/crates/vuio-core/src/casting/airplay/mod.rs +++ b/crates/vuio-core/src/casting/airplay/mod.rs @@ -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)) @@ -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"); diff --git a/crates/vuio-core/src/casting/airplay/transport.rs b/crates/vuio-core/src/casting/airplay/transport.rs index 4c9e3b7..1c6e7d7 100644 --- a/crates/vuio-core/src/casting/airplay/transport.rs +++ b/crates/vuio-core/src/casting/airplay/transport.rs @@ -13,7 +13,7 @@ pub struct AirplayConnection { wire_buffer: Vec, plain_buffer: Vec, /// Where receiver-pushed media commands are delivered, when serving events. - commands: Option>, + commands: Option>, } struct SecureState { @@ -134,7 +134,7 @@ impl AirplayConnection { pub async fn serve_events( self, - replies: tokio::sync::mpsc::UnboundedSender<(u64, Vec)>, + replies: tokio::sync::mpsc::Sender<(u64, Vec)>, ) -> Result<()> { self.serve_events_with_commands(replies, None).await } @@ -143,8 +143,8 @@ impl AirplayConnection { /// receiver pushes (its remote's transport buttons) to `commands`. pub async fn serve_events_with_commands( mut self, - replies: tokio::sync::mpsc::UnboundedSender<(u64, Vec)>, - commands: Option>, + replies: tokio::sync::mpsc::Sender<(u64, Vec)>, + commands: Option>, ) -> Result<()> { self.commands = commands; loop { @@ -162,7 +162,10 @@ impl AirplayConnection { let reply = data_stream_frame(b"rply", b"\0\0\0\0", message.sequence, &[])?; self.write_plain(&reply).await?; } else if message.message_type.starts_with(b"rply") { - let _ = replies.send((message.sequence, message.body)); + // Replies are diagnostic only. A slow logger (or no + // consumer in audio mode) must not retain an endless queue + // or stall the receiver's event acknowledgements. + let _ = replies.try_send((message.sequence, message.body)); } else { tracing::debug!( sequence = message.sequence, @@ -240,7 +243,7 @@ impl AirplayConnection { .and_then(|dictionary| dictionary.get("value")) .and_then(plist::Value::as_string) { - let _ = sender.send(command.to_string()); + let _ = sender.send(command.to_string()).await; } } } diff --git a/crates/vuio-core/src/database/conformance.rs b/crates/vuio-core/src/database/conformance.rs index 83328e6..b391aef 100644 --- a/crates/vuio-core/src/database/conformance.rs +++ b/crates/vuio-core/src/database/conformance.rs @@ -392,6 +392,22 @@ pub async fn path_prefix_query_is_bounded_by_the_prefix() { .get_files_with_path_prefix(&canonical(Path::new("/media/Film"))) .await .unwrap(); + let locations = database + .get_file_locations_with_path_prefix(&canonical(Path::new("/media/Film"))) + .await + .unwrap(); + assert_eq!( + locations, + matched + .iter() + .filter_map(MediaFileView::to_file_location) + .collect::>() + ); + let single = database + .get_file_locations_with_path_prefix(&canonical(Path::new("/media/Film/a.mkv"))) + .await + .unwrap(); + assert_eq!(single, locations[..1]); let names = matched .iter() .map(|file| file.filename.clone()) diff --git a/crates/vuio-core/src/database/mod.rs b/crates/vuio-core/src/database/mod.rs index 88165ce..e4c1252 100644 --- a/crates/vuio-core/src/database/mod.rs +++ b/crates/vuio-core/src/database/mod.rs @@ -1074,6 +1074,12 @@ pub trait MediaRepository: Send + Sync { /// Get files with a specific canonical path prefix. async fn get_files_with_path_prefix(&self, canonical_prefix: &str) -> Result>; + /// Playback fields only, without the library's full tag/stream records. + async fn get_file_locations_with_path_prefix( + &self, + canonical_prefix: &str, + ) -> Result>; + /// Get direct subdirectories using canonical paths. async fn get_direct_subdirectories( &self, @@ -1279,11 +1285,22 @@ pub trait MediaInfoRepository: Send + Sync { async fn mediainfo_stats(&self, threshold: u8) -> Result; /// Forget everything, so the next run starts over. async fn clear_mediainfo(&self) -> Result; - /// Ids of files that have no usable row yet, oldest first. + /// Number of pending files and the largest pending id at the start of a run. + async fn missing_mediainfo_summary(&self, version: u32, threshold: u8) -> Result<(usize, i64)>; + /// One bounded page of files that have no usable row yet, oldest first. /// /// `version` is the current reader version: rows written by an older one are /// treated as absent so a bumped version re-fetches. - async fn media_ids_missing_mediainfo(&self, version: u32, threshold: u8) -> Result>; + /// The exclusive cursor advances even for failed lookups. The inclusive + /// upper bound keeps files added during the run for the next run. + async fn media_ids_missing_mediainfo( + &self, + version: u32, + threshold: u8, + after_id: i64, + through_id: i64, + limit: usize, + ) -> Result>; } /// Aggregate database capability used by the application. diff --git a/crates/vuio-core/src/database/playlist_formats.rs b/crates/vuio-core/src/database/playlist_formats.rs index 3ccea8c..19ea000 100644 --- a/crates/vuio-core/src/database/playlist_formats.rs +++ b/crates/vuio-core/src/database/playlist_formats.rs @@ -121,32 +121,26 @@ impl PlaylistFileManager { // Collect all track paths first let mut track_paths = Vec::new(); - let lines: Vec<&str> = content.lines().collect(); - let mut i = 0; - - while i < lines.len() { - let line = lines[i].trim(); + let mut lines = content.lines(); + while let Some(line) = lines.next() { + let line = line.trim(); // Skip empty lines and comments (except #EXTINF) if line.is_empty() || (line.starts_with('#') && !line.starts_with("#EXTINF")) { - i += 1; continue; } // Handle extended M3U format if line.starts_with("#EXTINF") { // Next line should be the file path - i += 1; - if i < lines.len() { - let file_path_str = lines[i].trim(); + if let Some(file_path_str) = lines.next() { + let file_path_str = file_path_str.trim(); track_paths.push(resolve_playlist_entry(base_dir, file_path_str)); } } else if !line.starts_with('#') { // Simple M3U format - just file paths track_paths.push(resolve_playlist_entry(base_dir, line)); } - - i += 1; } // Create list of (path, position) pairs @@ -318,56 +312,47 @@ impl PlaylistFileManager { file_paths_with_positions: &[(String, u32)], source_path: Option<&str>, ) -> Result> { - if file_paths_with_positions.is_empty() { - return Ok(Vec::new()); - } - - // Extract paths for batch query - let paths: Vec = file_paths_with_positions - .iter() - .map(|(path_str, _)| PathBuf::from(path_str)) - .collect(); - - // Get all media files in a single query - let media_files = database.get_files_by_paths(&paths).await?; - - // Create a map from path to media file for quick lookup - let mut path_to_file = std::collections::HashMap::new(); - for media_file in media_files { - if let Some(file_id) = media_file.id { - path_to_file.insert(media_file.path.clone(), file_id); - } - } - - // Streams are valid playlist entries even though they are not present on - // the local filesystem. Materialize missing HTTP(S) entries as virtual - // radio files before building the playlist entry batch. - for (location, _) in file_paths_with_positions { - if !is_http_stream(location) { - continue; - } - let path = PathBuf::from(location); - if path_to_file.contains_key(&path) { - continue; + let mut media_file_entries = Vec::new(); + // Only IDs survive resolution. Do not retain the full metadata and + // duplicate paths for every entry of a library-sized playlist at once. + for entries in file_paths_with_positions.chunks(512) { + let paths: Vec = entries + .iter() + .map(|(path_str, _)| PathBuf::from(path_str)) + .collect(); + let media_files = database.get_files_by_paths(&paths).await?; + let mut path_to_file = std::collections::HashMap::new(); + for media_file in media_files { + if let Some(file_id) = media_file.id { + path_to_file.insert(media_file.path, file_id); + } } - let mut stream = MediaFile::new(path.clone(), 0, "audio/radio".to_string()); - stream.title = Some(location.clone()); - stream.album = source_path.map(str::to_owned); - let file_id = database.store_media_file(&stream).await?; - path_to_file.insert(path, file_id); - } - - // Build list of (media_file_id, position) pairs for files that exist in database - let mut media_file_entries = Vec::new(); + // Streams need no local file. Previously materialized URLs are + // found by the next batch too, including duplicates across batches. + for (location, _) in entries { + if !is_http_stream(location) { + continue; + } + let path = PathBuf::from(location); + if path_to_file.contains_key(&path) { + continue; + } - for (file_path_str, position) in file_paths_with_positions { - let file_path = PathBuf::from(file_path_str); + let mut stream = MediaFile::new(path.clone(), 0, "audio/radio".to_string()); + stream.title = Some(location.clone()); + stream.album = source_path.map(str::to_owned); + let file_id = database.store_media_file(&stream).await?; + path_to_file.insert(path, file_id); + } - if let Some(&file_id) = path_to_file.get(&file_path) { - media_file_entries.push((file_id, *position)); - } else { - warn!("File not found in media database: {}", file_path.display()); + for (file_path_str, position) in entries { + let file_path = Path::new(file_path_str); + if let Some(&file_id) = path_to_file.get(file_path) { + media_file_entries.push((file_id, *position)); + } else { + warn!("File not found in media database: {}", file_path.display()); + } } } diff --git a/crates/vuio-core/src/database/playlist_formats/tests.rs b/crates/vuio-core/src/database/playlist_formats/tests.rs index 320e2ae..c374da7 100644 --- a/crates/vuio-core/src/database/playlist_formats/tests.rs +++ b/crates/vuio-core/src/database/playlist_formats/tests.rs @@ -108,6 +108,55 @@ async fn test_generic_playlist_import_materializes_http_stream() { .is_none()); } +#[tokio::test] +async fn playlist_resolution_preserves_positions_and_duplicates_across_batches() { + use crate::database::sqlite::SqliteDatabase; + + let temp = tempfile::tempdir().unwrap(); + let database = SqliteDatabase::new(temp.path().join("batched.db")) + .await + .unwrap(); + database.initialize().await.unwrap(); + let path = temp.path().canonicalize().unwrap().join("song.mp3"); + let id = database + .store_media_file(&MediaFile::new(path.clone(), 1, "audio/mpeg".into())) + .await + .unwrap(); + let url = "https://radio.example/stream"; + let entries: Vec<_> = (0..1300) + .map(|position| { + let location = match position % 3 { + 0 => path.to_string_lossy().into_owned(), + 1 => url.to_owned(), + _ => temp + .path() + .join("missing.mp3") + .to_string_lossy() + .into_owned(), + }; + (location, position) + }) + .collect(); + let resolved = PlaylistFileManager::resolve_playlist_tracks(&database, &entries, None) + .await + .unwrap(); + let stream_id = database + .get_file_by_path(Path::new(url)) + .await + .unwrap() + .unwrap() + .id + .unwrap(); + let expected: Vec<_> = (0..1300) + .filter_map(|position| match position % 3 { + 0 => Some((id, position)), + 1 => Some((stream_id, position)), + _ => None, + }) + .collect(); + assert_eq!(resolved, expected); +} + #[tokio::test] async fn test_non_recursive_radio_root_uses_radio_importer() { use crate::database::sqlite::SqliteDatabase; diff --git a/crates/vuio-core/src/database/sqlite/directory.rs b/crates/vuio-core/src/database/sqlite/directory.rs index b1faf66..e7d52ad 100644 --- a/crates/vuio-core/src/database/sqlite/directory.rs +++ b/crates/vuio-core/src/database/sqlite/directory.rs @@ -61,7 +61,7 @@ impl DirectoryDelta { let directories = self .counts .keys() - .map(|(path, _)| path.clone()) + .map(|(path, _)| path.as_str()) .collect::>(); { @@ -136,6 +136,12 @@ pub(super) fn rebuild(transaction: &Transaction<'_>) -> Result<()> { let path: String = row.get(0)?; let family: String = row.get(1)?; delta.record(&path, &family, 1); + // Repair may cover millions of directories. Apply bounded batches + // inside the same transaction instead of retaining the whole tree + // (and a second collection of its paths) until the scan ends. + if delta.counts.len() >= 4096 { + std::mem::take(&mut delta).apply(transaction)?; + } } } delta.apply(transaction) diff --git a/crates/vuio-core/src/database/sqlite/media_repo/listing.rs b/crates/vuio-core/src/database/sqlite/media_repo/listing.rs index b2a38c9..5669ad6 100644 --- a/crates/vuio-core/src/database/sqlite/media_repo/listing.rs +++ b/crates/vuio-core/src/database/sqlite/media_repo/listing.rs @@ -4,12 +4,37 @@ use anyhow::Result; use std::path::PathBuf; use crate::database::sqlite::query::{self, MimeFilter}; -use crate::database::sqlite::schema::{self, MEDIA_COLUMNS}; +use crate::database::sqlite::schema::{self, FILE_LOCATION_COLUMNS, MEDIA_COLUMNS}; use crate::database::sqlite::session::directory_listing_sql; use crate::database::sqlite::SqliteDatabase; -use crate::database::{MediaDirectory, MediaFile}; +use crate::database::{FileLocation, MediaDirectory, MediaFile}; impl SqliteDatabase { + pub(in crate::database::sqlite) async fn get_file_locations_with_path_prefix_impl( + &self, + canonical_prefix: &str, + ) -> Result> { + let prefix = canonical_prefix.to_owned(); + self.execute_read(move |connection| { + let (predicate, params) = query::subtree_params(&prefix); + let mut statement = connection.prepare_cached(&format!( + "SELECT {FILE_LOCATION_COLUMNS} FROM media_files \ + WHERE media_files.path = ? OR ({predicate}) \ + ORDER BY media_files.path" + ))?; + let mut bound = vec![rusqlite::types::Value::Text(prefix)]; + bound.extend(params); + let files = statement + .query_map( + rusqlite::params_from_iter(bound.iter()), + schema::file_location_from_row, + )? + .collect::>>()?; + Ok(files) + }) + .await + } + pub(in crate::database::sqlite) async fn get_direct_subdirectories_impl( &self, canonical_parent: &str, diff --git a/crates/vuio-core/src/database/sqlite/mediainfo_repo.rs b/crates/vuio-core/src/database/sqlite/mediainfo_repo.rs index 9bc7376..8904aa6 100644 --- a/crates/vuio-core/src/database/sqlite/mediainfo_repo.rs +++ b/crates/vuio-core/src/database/sqlite/mediainfo_repo.rs @@ -191,10 +191,34 @@ impl SqliteDatabase { .await } + pub(super) async fn missing_mediainfo_summary_impl( + &self, + version: u32, + threshold: u8, + ) -> Result<(usize, i64)> { + self.execute_read(move |connection| { + Ok(connection + .prepare_cached( + "SELECT COUNT(*), COALESCE(MAX(media_files.id), 0) FROM media_files \ + LEFT JOIN mediainfo ON mediainfo.media_file_id = media_files.id \ + WHERE mediainfo.media_file_id IS NULL \ + OR mediainfo.mediainfo_version < ?1 \ + OR mediainfo.confidence < ?2", + )? + .query_row(rusqlite::params![version, threshold], |row| { + Ok((row.get::<_, i64>(0)? as usize, row.get(1)?)) + })?) + }) + .await + } + pub(super) async fn media_ids_missing_mediainfo_impl( &self, version: u32, threshold: u8, + after_id: i64, + through_id: i64, + limit: usize, ) -> Result> { self.execute_read(move |connection| { // Three cases count as "needs looking up": never tried, tried by an @@ -204,13 +228,14 @@ impl SqliteDatabase { let mut statement = connection.prepare_cached( "SELECT media_files.id FROM media_files \ LEFT JOIN mediainfo ON mediainfo.media_file_id = media_files.id \ - WHERE mediainfo.media_file_id IS NULL \ + WHERE media_files.id > ?3 AND media_files.id <= ?4 \ + AND (mediainfo.media_file_id IS NULL \ OR mediainfo.mediainfo_version < ?1 \ - OR mediainfo.confidence < ?2 \ - ORDER BY media_files.id", + OR mediainfo.confidence < ?2) \ + ORDER BY media_files.id LIMIT ?5", )?; let rows = statement.query_map( - rusqlite::params![version as i64, threshold as i64], + rusqlite::params![version, threshold, after_id, through_id, limit.min(i64::MAX as usize) as i64], |row| row.get::<_, i64>(0), )?; let mut ids = Vec::new(); diff --git a/crates/vuio-core/src/database/sqlite/schema.rs b/crates/vuio-core/src/database/sqlite/schema.rs index 622538e..ad36a92 100644 --- a/crates/vuio-core/src/database/sqlite/schema.rs +++ b/crates/vuio-core/src/database/sqlite/schema.rs @@ -676,13 +676,15 @@ fn apply_pragmas(connection: &Connection, cache_mb: usize) -> Result<()> { // A negative cache_size is a KiB budget rather than a page count, which is // what the configuration actually expresses. let cache_kib = (cache_mb.max(1) * 1024) as i64; + // Large sorts, index rebuilds and temporary tables must be able to spill + // to disk. MEMORY bypasses the main page-cache budget for all of them. connection .execute_batch(&format!( "PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000; - PRAGMA temp_store = MEMORY; + PRAGMA temp_store = FILE; PRAGMA cache_size = -{cache_kib};" )) .context("Failed to configure the SQLite connection")?; diff --git a/crates/vuio-core/src/database/sqlite/tests.rs b/crates/vuio-core/src/database/sqlite/tests.rs index 64d1375..8283ae7 100644 --- a/crates/vuio-core/src/database/sqlite/tests.rs +++ b/crates/vuio-core/src/database/sqlite/tests.rs @@ -464,6 +464,21 @@ async fn rebuilding_the_directory_tree_reproduces_incremental_maintenance() { .unwrap() }; + // More distinct directory counters than one repair batch, with shared + // ancestors whose counts must add up across every flush. + for batch in 0..5 { + let files: Vec<_> = (0..1000) + .map(|i| { + MediaFile::new( + PathBuf::from(format!("/media/large/{}/song.mp3", batch * 1000 + i)), + 1, + "audio/mpeg".to_owned(), + ) + }) + .collect(); + db.bulk_store_media_files(&files).await.unwrap(); + } + let incremental = snapshot(db.clone()).await; assert!(!incremental.is_empty()); diff --git a/crates/vuio-core/src/database/sqlite/traits.rs b/crates/vuio-core/src/database/sqlite/traits.rs index fb5c8e4..0621271 100644 --- a/crates/vuio-core/src/database/sqlite/traits.rs +++ b/crates/vuio-core/src/database/sqlite/traits.rs @@ -205,6 +205,13 @@ impl MediaRepository for SqliteDatabase { SqliteDatabase::get_files_with_path_prefix_impl(self, canonical_prefix).await } + async fn get_file_locations_with_path_prefix( + &self, + canonical_prefix: &str, + ) -> Result> { + SqliteDatabase::get_file_locations_with_path_prefix_impl(self, canonical_prefix).await + } + async fn get_direct_subdirectories( &self, canonical_parent_path: &str, @@ -428,7 +435,21 @@ impl MediaInfoRepository for SqliteDatabase { SqliteDatabase::clear_mediainfo_impl(self).await } - async fn media_ids_missing_mediainfo(&self, version: u32, threshold: u8) -> Result> { - SqliteDatabase::media_ids_missing_mediainfo_impl(self, version, threshold).await + async fn missing_mediainfo_summary(&self, version: u32, threshold: u8) -> Result<(usize, i64)> { + SqliteDatabase::missing_mediainfo_summary_impl(self, version, threshold).await + } + + async fn media_ids_missing_mediainfo( + &self, + version: u32, + threshold: u8, + after_id: i64, + through_id: i64, + limit: usize, + ) -> Result> { + SqliteDatabase::media_ids_missing_mediainfo_impl( + self, version, threshold, after_id, through_id, limit, + ) + .await } } diff --git a/crates/vuio-core/src/lifecycle/media/events.rs b/crates/vuio-core/src/lifecycle/media/events.rs index 0f05408..00a6bee 100644 --- a/crates/vuio-core/src/lifecycle/media/events.rs +++ b/crates/vuio-core/src/lifecycle/media/events.rs @@ -392,16 +392,22 @@ pub(in crate::lifecycle) async fn handle_file_system_event = files_in_old_path + let moves: Vec<(i64, PathBuf)> = files .iter() .filter_map(|file| { - let id = file.id?; // Both sides canonical: the stored path is, and // the event's is not — /var against /private/var // would strip nothing at all. Some(( - id, + file.id, repoint( &file.path, Path::new(&canonical_from_prefix), @@ -426,7 +431,9 @@ pub(in crate::lifecycle) async fn handle_file_system_event 0 { info!("Moved {moved} indexed files with the renamed directory"); // Scan the new directory location using bulk operations diff --git a/crates/vuio-core/src/media/remux/fmp4_writer.rs b/crates/vuio-core/src/media/remux/fmp4_writer.rs index 3d294c1..64367be 100644 --- a/crates/vuio-core/src/media/remux/fmp4_writer.rs +++ b/crates/vuio-core/src/media/remux/fmp4_writer.rs @@ -615,11 +615,12 @@ impl Fmp4Writer { pub fn build_mdat(packets: &[MediaPacket]) -> Vec { let total_size: usize = packets.iter().map(|p| p.data.len()).sum(); let mut mdat = Vec::with_capacity(8 + total_size); + mdat.extend_from_slice(&((8 + total_size) as u32).to_be_bytes()); mdat.extend_from_slice(b"mdat"); for p in packets { mdat.extend_from_slice(&p.data); } - Self::wrap_box(&mdat) + mdat } /// Build a complete fMP4 segment (moof + mdat) from a list of media packets. @@ -661,11 +662,17 @@ impl Fmp4Writer { samples: &samples, }; let moof = Self::build_moof_multi(sequence_number, &[run], &[data_offset]); - let mdat = Self::build_mdat(packets); - - let mut segment = Vec::with_capacity(moof.len() + mdat.len()); + let payload: usize = packets.iter().map(|packet| packet.data.len()).sum(); + // Write directly into the response. A UHD segment can be tens of MB; + // separately building, wrapping and then copying mdat multiplied that + // payload's peak allocation for every concurrent viewer. + let mut segment = Vec::with_capacity(moof.len() + 8 + payload); segment.extend_from_slice(&moof); - segment.extend_from_slice(&mdat); + segment.extend_from_slice(&((8 + payload) as u32).to_be_bytes()); + segment.extend_from_slice(b"mdat"); + for packet in packets { + segment.extend_from_slice(&packet.data); + } segment } @@ -741,18 +748,15 @@ impl Fmp4Writer { .iter() .map(|(_, packets)| packets.iter().map(|p| p.data.len()).sum::()) .sum(); - let mut mdat = Vec::with_capacity(8 + payload); - mdat.extend_from_slice(b"mdat"); + let mut segment = Vec::with_capacity(moof.len() + 8 + payload); + segment.extend_from_slice(&moof); + segment.extend_from_slice(&((8 + payload) as u32).to_be_bytes()); + segment.extend_from_slice(b"mdat"); for (_, packets) in tracks { for packet in *packets { - mdat.extend_from_slice(&packet.data); + segment.extend_from_slice(&packet.data); } } - let mdat = Self::wrap_box(&mdat); - - let mut segment = Vec::with_capacity(moof.len() + mdat.len()); - segment.extend_from_slice(&moof); - segment.extend_from_slice(&mdat); segment } @@ -965,7 +969,7 @@ mod tests { data: vec![1, 2, 3, 4], }; let mdat = Fmp4Writer::build_mdat(&[pkt]); - assert_eq!(&mdat[4..8], b"mdat"); + assert_eq!(&mdat, b"\0\0\0\x0cmdat\x01\x02\x03\x04"); } #[test] @@ -1035,6 +1039,102 @@ mod tests { assert!(segment.len() > 108); // moof + mdat header + 100 bytes of data // Verify moof magic at offset 4 assert_eq!(&segment[4..8], b"moof"); + let moof_len = u32::from_be_bytes(segment[..4].try_into().unwrap()) as usize; + assert_eq!(&segment[moof_len..moof_len + 4], &108u32.to_be_bytes()); + assert_eq!(&segment[moof_len + 4..moof_len + 8], b"mdat"); + assert_eq!(&segment[moof_len + 8..], &packets[0].data); + assert_eq!( + segment, + Fmp4Writer::build_multi_track_segment(1, &[(&track, &packets)], &[0]) + ); + } + + #[test] + fn multi_track_payloads_follow_their_trun_offsets() { + let video = track_of(1, TrackKind::Video); + let audio = track_of(2, TrackKind::Audio); + let make_packet = |track_id, byte, size| MediaPacket { + track_id, + pts: 0, + dts: 0, + duration: 1024, + is_keyframe: true, + data: vec![byte; size], + }; + let video_packets = [make_packet(1, 0x11, 31), make_packet(1, 0x22, 43)]; + let audio_packets = [make_packet(2, 0x33, 17)]; + let segment = Fmp4Writer::build_multi_track_segment( + 1, + &[(&video, &video_packets), (&audio, &audio_packets)], + &[0, 0], + ); + let moof_len = u32::from_be_bytes(segment[..4].try_into().unwrap()) as usize; + let offsets: Vec<_> = segment[..moof_len] + .windows(4) + .enumerate() + .filter(|(_, magic)| *magic == b"trun") + .map(|(pos, _)| { + u32::from_be_bytes(segment[pos + 12..pos + 16].try_into().unwrap()) as usize + }) + .collect(); + assert_eq!(offsets, [moof_len + 8, moof_len + 8 + 74]); + assert_eq!( + &segment[offsets[0]..offsets[1]], + &[vec![0x11; 31], vec![0x22; 43]].concat() + ); + assert_eq!(&segment[offsets[1]..], &[0x33; 17]); + assert_eq!( + u32::from_be_bytes(segment[moof_len..moof_len + 4].try_into().unwrap()), + 99 + ); + } + + /// Run the test binary directly under /usr/bin/time -l, in separate + /// processes with and without VUIO_LEGACY_FRAGMENT=1, to compare peak RSS. + #[test] + #[ignore = "isolated 64 MiB allocation probe"] + fn fragment_rss_probe() { + let track = track_of(1, TrackKind::Video); + let packets = vec![MediaPacket { + track_id: 1, + pts: 0, + dts: 0, + duration: 90_000, + is_keyframe: true, + data: vec![0x5a; 64 * 1024 * 1024], + }]; + let segment = if std::env::var_os("VUIO_LEGACY_FRAGMENT").is_some() { + let samples = Fmp4Writer::samples_for(&track, &packets); + let run = TrackRun { + track_id: 1, + base_decode_time: 0, + samples: &samples, + }; + let size = Fmp4Writer::build_moof_multi(1, &[run], &[0]).len(); + let run = TrackRun { + track_id: 1, + base_decode_time: 0, + samples: &samples, + }; + let moof = Fmp4Writer::build_moof_multi(1, &[run], &[size as u32 + 8]); + // The former multi-track builder kept all three copies live. + let mut body = Vec::with_capacity(8 + packets[0].data.len()); + body.extend_from_slice(b"mdat"); + body.extend_from_slice(&packets[0].data); + let mdat = Fmp4Writer::wrap_box(&body); + let mut segment = Vec::with_capacity(moof.len() + mdat.len()); + segment.extend_from_slice(&moof); + segment.extend_from_slice(&mdat); + std::hint::black_box((&body, &mdat)); + segment + } else { + Fmp4Writer::build_multi_track_segment(1, &[(&track, &packets)], &[0]) + }; + use std::hash::{Hash, Hasher}; + let mut hash = std::collections::hash_map::DefaultHasher::new(); + segment.hash(&mut hash); + println!("fragment: {} bytes, hash {}", segment.len(), hash.finish()); + std::hint::black_box((&segment, &packets)); } #[test] diff --git a/crates/vuio-core/src/media/scanner.rs b/crates/vuio-core/src/media/scanner.rs index 61c4cf0..007a180 100644 --- a/crates/vuio-core/src/media/scanner.rs +++ b/crates/vuio-core/src/media/scanner.rs @@ -726,36 +726,33 @@ impl MediaScanner { result.errors.extend(traversal.errors); result.complete = traversal.root_complete && traversal.uncertain_prefixes.is_empty(); - // Whatever the walk never produced is gone from disk. - let reconcile_deletions = - traversal.root_complete && traversal.uncertain_prefixes.is_empty(); - let files_to_remove: Vec = if reconcile_deletions { - indexed.unseen().collect() - } else { - // A partial walk cannot tell "absent" from "unreadable". Where only - // some prefixes are in doubt, everything outside them is still - // decidable. - indexed - .unseen() - .filter(|_| traversal.root_complete) - .filter(|path| { - !traversal - .uncertain_prefixes - .iter() - .any(|prefix| path.starts_with(prefix)) - }) - .collect() - }; + // A partial walk cannot tell "absent" from "unreadable". Delete only + // outside uncertain prefixes, and keep at most one batch of absolute + // paths: removing a large subtree must not duplicate the scan's index. + if traversal.root_complete { + let mut files_to_remove = Vec::new(); + for path in indexed.unseen().filter(|path| { + !traversal + .uncertain_prefixes + .iter() + .any(|prefix| path.starts_with(prefix)) + }) { + files_to_remove.push(path); + if files_to_remove.len() == BATCH_SIZE { + self.database_manager + .bulk_remove_media_files(&files_to_remove) + .await?; + result.removed += files_to_remove.len(); + files_to_remove.clear(); + } + } + if !files_to_remove.is_empty() { + self.database_manager + .bulk_remove_media_files(&files_to_remove) + .await?; + result.removed += files_to_remove.len(); + } - if !files_to_remove.is_empty() { - info!( - "Removing {} deleted files from database", - files_to_remove.len() - ); - self.database_manager - .bulk_remove_media_files(&files_to_remove) - .await?; - result.removed += files_to_remove.len(); } result.total_scanned = total_files; diff --git a/crates/vuio-core/src/media/tests.rs b/crates/vuio-core/src/media/tests.rs index c350429..5a70c12 100644 --- a/crates/vuio-core/src/media/tests.rs +++ b/crates/vuio-core/src/media/tests.rs @@ -272,6 +272,46 @@ async fn scans_keep_media_when_the_library_is_unreadable() { } } +#[tokio::test] +async fn recursive_scan_reconciles_deletions_across_batches() { + let temp = tempdir().unwrap(); + let root = temp.path().join("media"); + std::fs::create_dir(&root).unwrap(); + let root = std::fs::canonicalize(root).unwrap(); + std::fs::write(root.join("keep.mp4"), b"a").unwrap(); + let db = Arc::new( + SqliteDatabase::new(temp.path().join("delete-batches.db")) + .await + .unwrap(), + ); + db.initialize().await.unwrap(); + let scanner = MediaScanner::with_filesystem_manager( + Box::new(BaseFileSystemManager::new(true)), + db.clone(), + ); + scanner.scan_directory_recursive(&root).await.unwrap(); + let missing: Vec<_> = (0..2501) + .map(|i| { + MediaFile::new( + root.join(format!("gone/{i}.mp4")), + 1, + "video/mp4".to_owned(), + ) + }) + .collect(); + db.bulk_store_media_files(&missing).await.unwrap(); + drop(missing); + let result = scanner.scan_directory_recursive(&root).await.unwrap(); + assert_eq!(result.removed, 2501); + assert_eq!(result.unchanged, 1); + assert!(db + .get_file_by_path(&root.join("keep.mp4")) + .await + .unwrap() + .is_some()); + assert_eq!(db.load_file_fingerprints().await.unwrap().len(), 1); +} + /// A scan compares one root against one root. It loads only that subtree's /// records, and a sibling library — including one whose path is a string prefix /// of this one — must be neither examined nor deleted. diff --git a/crates/vuio-core/src/media/transcode/frames.rs b/crates/vuio-core/src/media/transcode/frames.rs index d2cfd09..580ccda 100644 --- a/crates/vuio-core/src/media/transcode/frames.rs +++ b/crates/vuio-core/src/media/transcode/frames.rs @@ -14,6 +14,7 @@ use anyhow::{bail, Context, Result}; use std::io::Read; +use std::sync::Arc; use super::TranscodeCodec; @@ -46,8 +47,9 @@ pub struct FrameIndex { pub codec: TranscodeCodec, /// Sample rate declared by the first frame, in Hz. pub sample_rate: u32, - /// The frames, in stream order. - pub frames: Vec, + /// Immutable offsets shared by the cached plan and every active stream. + /// Cloning an index must not copy several MB for each listener or seek. + pub frames: Arc<[IndexedFrame]>, /// Sum of every frame's `samples` — the exact decoded length. pub total_samples: u64, } @@ -158,7 +160,7 @@ impl FrameIndex { Ok(Self { codec, sample_rate, - frames, + frames: frames.into(), total_samples, }) } @@ -341,7 +343,7 @@ mod tests { assert_eq!(idx.sample_rate, 48_000); // 48 kHz / 192 kbps → Table 5.18 frmsizecod 20 → 768-byte frames. assert!(idx.frames.len() >= 4, "got {} frames", idx.frames.len()); - for f in &idx.frames { + for f in idx.frames.iter() { assert_eq!(f.len, 768); assert_eq!(f.samples, 1536, "base AC-3 is always six 256-sample blocks"); } @@ -392,10 +394,26 @@ mod tests { assert_eq!(i, idx.frames.len() - 1); } + #[test] + fn cloned_indexes_share_frame_storage() { + let index = FrameIndex { + codec: TranscodeCodec::Ac3, + sample_rate: 48_000, + frames: vec![IndexedFrame { + offset: 0, + len: 768, + samples: 1536, + }] + .into(), + total_samples: 1536, + }; + let clone = index.clone(); + assert!(Arc::ptr_eq(&index.frames, &clone.frames)); + } + #[test] fn a_stream_that_is_not_this_codec_is_rejected() { let junk = vec![0u8; 4096]; assert!(FrameIndex::build(TranscodeCodec::Ac3, &mut &junk[..]).is_err()); } } - diff --git a/crates/vuio-core/src/media/transcode/plan.rs b/crates/vuio-core/src/media/transcode/plan.rs index b43b995..b7161e9 100644 --- a/crates/vuio-core/src/media/transcode/plan.rs +++ b/crates/vuio-core/src/media/transcode/plan.rs @@ -58,6 +58,17 @@ impl std::fmt::Debug for AudioPlan { pub(crate) const TARGET_CHANNELS: u16 = 2; impl AudioPlan { + /// Owned heap storage plus the plan itself, for the cache's byte ceiling. + pub(crate) fn retained_bytes(&self) -> usize { + std::mem::size_of::() + + self.source_path.capacity() + + match &self.source { + PacketSource::Elementary(index) => std::mem::size_of_val(index.frames.as_ref()), + #[cfg(feature = "demux")] + PacketSource::Container(_) => 0, + } + } + /// Index a raw `.ac3`/`.eac3`/`.dts` file and probe its decoded shape. /// /// Blocking: it reads the whole file's headers and decodes one frame, so diff --git a/crates/vuio-core/src/media/transcode/session.rs b/crates/vuio-core/src/media/transcode/session.rs index ad95cd3..27a4c66 100644 --- a/crates/vuio-core/src/media/transcode/session.rs +++ b/crates/vuio-core/src/media/transcode/session.rs @@ -22,9 +22,10 @@ use super::TrackRates; /// /// An index earns its place across the handful of requests a renderer makes /// while it opens and scrubs one file, so the count only has to cover the files -/// being opened at the same time. Four is a household's worth and holds 12 MB -/// at most; eight held 24 MB for streams long since settled. +/// being opened at the same time. The byte ceiling also covers long recordings +/// and codecs with many more frames per second than AC-3. const MAX_CACHED_INDEXES: usize = 4; +const MAX_CACHED_INDEX_BYTES: usize = 12 * 1024 * 1024; /// Identifies a cached index. The file's size and high-resolution metadata /// marker are part of the key so replacing a file in place invalidates its @@ -186,9 +187,10 @@ struct SegmentCache { struct Cache { entries: HashMap>, /// Insertion order, oldest first. A plain queue rather than a true LRU: with - /// a cap of eight the difference is not measurable, and this needs no + /// a cap of four the difference is not measurable, and this needs no /// bookkeeping on the read path. order: Vec, + bytes: usize, } impl Default for TranscodeState { @@ -231,11 +233,21 @@ impl TranscodeState { /// Remember `index` under `key`, evicting the oldest entry if full. pub async fn remember(&self, key: IndexKey, index: Arc) { let mut cache = self.cache.lock().await; - if cache.entries.insert(key, index).is_none() { - cache.order.push(key); - while cache.order.len() > MAX_CACHED_INDEXES { - let oldest = cache.order.remove(0); - cache.entries.remove(&oldest); + if let Some(old) = cache.entries.remove(&key) { + cache.bytes -= old.retained_bytes(); + cache.order.retain(|stored| *stored != key); + } + let bytes = index.retained_bytes(); + if bytes > MAX_CACHED_INDEX_BYTES { + return; + } + cache.bytes += bytes; + cache.entries.insert(key, index); + cache.order.push(key); + while cache.order.len() > MAX_CACHED_INDEXES || cache.bytes > MAX_CACHED_INDEX_BYTES { + let oldest = cache.order.remove(0); + if let Some(old) = cache.entries.remove(&oldest) { + cache.bytes -= old.retained_bytes(); } } } @@ -275,16 +287,22 @@ impl TranscodeState { }; let len = chunk.len(); if len > MAX_CACHED_CHUNK_BYTES { + if let Some(old) = cache.entries.remove(&key) { + cache.bytes -= old.len(); + cache.order.retain(|stored| *stored != key); + } return; } - if cache.entries.insert(key, chunk).is_none() { + if let Some(old) = cache.entries.insert(key, chunk) { + cache.bytes -= old.len(); + } else { cache.order.push(key); - cache.bytes += len; - while cache.order.len() > MAX_CACHED_CHUNKS || cache.bytes > MAX_CACHED_CHUNK_BYTES { - let oldest = cache.order.remove(0); - if let Some(gone) = cache.entries.remove(&oldest) { - cache.bytes = cache.bytes.saturating_sub(gone.len()); - } + } + cache.bytes += len; + while cache.order.len() > MAX_CACHED_CHUNKS || cache.bytes > MAX_CACHED_CHUNK_BYTES { + let oldest = cache.order.remove(0); + if let Some(gone) = cache.entries.remove(&oldest) { + cache.bytes -= gone.len(); } } } @@ -298,17 +316,26 @@ impl TranscodeState { pub async fn remember_segment(&self, key: SegmentKey, segment: bytes::Bytes) { let mut cache = self.segments.lock().await; let len = segment.len(); - if cache.entries.insert(key, segment).is_none() { + if len > MAX_CACHED_SEGMENT_BYTES { + if let Some(old) = cache.entries.remove(&key) { + cache.bytes -= old.len(); + cache.order.retain(|stored| *stored != key); + } + return; + } + if let Some(old) = cache.entries.insert(key, segment) { + cache.bytes -= old.len(); + } else { cache.order.push(key); - cache.bytes += len; } + cache.bytes += len; while cache.order.len() > MAX_CACHED_SEGMENTS || cache.bytes > MAX_CACHED_SEGMENT_BYTES { let Some(oldest) = cache.order.first().copied() else { break; }; cache.order.remove(0); if let Some(evicted) = cache.entries.remove(&oldest) { - cache.bytes = cache.bytes.saturating_sub(evicted.len()); + cache.bytes -= evicted.len(); } } } @@ -328,7 +355,7 @@ mod tests { crate::media::transcode::FrameIndex { codec: TranscodeCodec::Ac3, sample_rate: 48_000, - frames: Vec::new(), + frames: Arc::from([]), total_samples: 0, }, ), @@ -356,6 +383,41 @@ mod tests { assert!(state.cached(&key(2)).await.is_some()); } + #[tokio::test] + async fn large_indexes_are_bounded_by_bytes_including_replacements() { + fn large_index(bytes: usize) -> Arc { + let mut plan = index(); + let frames = match &mut Arc::get_mut(&mut plan).unwrap().source { + super::super::PacketSource::Elementary(frames) => frames, + #[cfg(feature = "demux")] + super::super::PacketSource::Container(_) => unreachable!(), + }; + frames.frames = vec![ + super::super::IndexedFrame { + offset: 0, + len: 768, + samples: 1536 + }; + bytes / std::mem::size_of::() + ] + .into(); + plan + } + let state = TranscodeState::new(1); + let large = large_index(MAX_CACHED_INDEX_BYTES / 2); + state.remember(key(1), large.clone()).await; + state.remember(key(2), index()).await; + state.remember(key(2), large).await; + assert!(state.cached(&key(1)).await.is_none()); + assert!(state.cached(&key(2)).await.is_some()); + assert!(state.cache.lock().await.bytes <= MAX_CACHED_INDEX_BYTES); + state + .remember(key(2), large_index(MAX_CACHED_INDEX_BYTES + 1024)) + .await; + assert!(state.cached(&key(2)).await.is_none()); + assert_eq!(state.cache.lock().await.bytes, 0); + } + #[tokio::test] async fn a_file_replaced_in_place_does_not_reuse_its_index() { let state = TranscodeState::new(1); @@ -403,6 +465,98 @@ mod tests { assert!(state.cached_segment(&key(3)).await.is_some()); } + #[tokio::test] + async fn replacing_a_segment_recounts_bytes_and_keeps_the_ceiling() { + let state = TranscodeState::new(1); + let key = |seq| SegmentKey { + file: key(1), + track: 2, + seq, + }; + state + .remember_segment(key(0), bytes::Bytes::from_static(b"x")) + .await; + state + .remember_segment(key(0), bytes::Bytes::from(vec![0; 20 * 1024 * 1024])) + .await; + state + .remember_segment(key(1), bytes::Bytes::from(vec![0; 10 * 1024 * 1024])) + .await; + + let cache = state.segments.lock().await; + assert!(cache.bytes <= MAX_CACHED_SEGMENT_BYTES); + assert_eq!( + cache.bytes, + cache.entries.values().map(bytes::Bytes::len).sum::() + ); + assert!( + !cache.entries.contains_key(&key(0)), + "the older large segment is evicted" + ); + assert!(cache.entries.contains_key(&key(1))); + } + + #[test] + fn replacing_a_chunk_recounts_bytes_and_keeps_the_ceiling() { + let state = TranscodeState::new(1); + let key = |origin| ChunkKey { + file: key(1), + origin, + tracks: 1, + }; + state.remember_chunk(key(0), Arc::new(vec![0])); + state.remember_chunk(key(0), Arc::new(vec![0; 20 * 1024 * 1024])); + state.remember_chunk(key(1), Arc::new(vec![0; 10 * 1024 * 1024])); + + let cache = state.chunks.lock().unwrap(); + assert!(cache.bytes <= MAX_CACHED_CHUNK_BYTES); + assert_eq!( + cache.bytes, + cache + .entries + .values() + .map(|chunk| chunk.len()) + .sum::() + ); + assert!( + !cache.entries.contains_key(&key(0)), + "the older large chunk is evicted" + ); + assert!(cache.entries.contains_key(&key(1))); + } + + #[tokio::test] + async fn an_oversized_replacement_is_not_retained() { + let state = TranscodeState::new(1); + let segment = SegmentKey { + file: key(1), + track: 2, + seq: 0, + }; + let chunk = ChunkKey { + file: key(1), + origin: 0, + tracks: 1, + }; + + state + .remember_segment(segment, bytes::Bytes::from_static(b"old")) + .await; + state.remember_chunk(chunk, Arc::new(b"old".to_vec())); + state + .remember_segment( + segment, + bytes::Bytes::from(vec![0; MAX_CACHED_SEGMENT_BYTES + 1]), + ) + .await; + state.remember_chunk(chunk, Arc::new(vec![0; MAX_CACHED_CHUNK_BYTES + 1])); + + assert!(state.cached_segment(&segment).await.is_none()); + assert!(state.cached_chunk(&chunk).is_none()); + assert_eq!(state.segments.lock().await.bytes, 0); + assert_eq!(state.chunks.lock().unwrap().bytes, 0); + } + #[tokio::test] async fn a_segment_is_found_again_under_the_key_that_stored_it() { let state = TranscodeState::new(1); diff --git a/crates/vuio-core/src/media/transcode/ts.rs b/crates/vuio-core/src/media/transcode/ts.rs index bdb6c5e..907ae07 100644 --- a/crates/vuio-core/src/media/transcode/ts.rs +++ b/crates/vuio-core/src/media/transcode/ts.rs @@ -1179,12 +1179,19 @@ fn open_chain(stream: &mut Stream, codec: TranscodeCodec, frame: &[u8]) -> Resul } /// Take one frame's decoded PCM and encode it. -fn take_decoded(pending: &mut Vec, decode: &mut Encode, ticks: u64, pcm: Vec) -> Result<()> { - // Where this run starts, if it is contiguous — asked of every packet, so - // that one rounded container timestamp cannot place the whole run. - let samples = (ticks as i128 * i64::from(decode.sample_rate) as i128 - / TS_CLOCK_HZ as i128) as i64; - decode.anchors.push(samples - decode.decoded as i64); +fn take_decoded( + pending: &mut Vec, + decode: &mut Encode, + ticks: u64, + pcm: Vec, +) -> Result<()> { + // Collect only until the run is placed. Later estimates are never used; + // retaining one per frame grew for the whole film on every soundtrack. + if decode.next_pts.is_none() { + let samples = + (ticks as i128 * i64::from(decode.sample_rate) as i128 / TS_CLOCK_HZ as i128) as i64; + decode.anchors.push(samples - decode.decoded as i64); + } decode.decoded += (pcm.len() / (decode.decoded_channels as usize * 2)) as u64; let pcm = super::fit_channels(&pcm, decode.decoded_channels, decode.target_channels); let frames = decode.encoder.push(&pcm)?; @@ -1265,6 +1272,35 @@ mod tests { use super::*; use crate::media::remux::TrackKind; + #[test] + fn timing_estimates_stop_accumulating_after_the_run_is_placed() { + let mut decode = Encode { + encoder: Reencoder::Aac(Box::new(AacEncoder::new(48_000, 2).unwrap())), + target_channels: 2, + decoded_channels: 2, + sample_rate: 48_000, + next_pts: None, + anchors: Vec::new(), + decoded: 0, + held: Vec::new(), + }; + let mut pending = Vec::new(); + for frame in 0..ANCHOR_PACKETS * 2 { + take_decoded( + &mut pending, + &mut decode, + frame as u64 * 1920, + vec![0; 4096], + ) + .unwrap(); + pending.clear(); + } + assert!(decode.next_pts.is_some()); + assert!(decode.anchors.is_empty()); + assert_eq!(decode.anchors.capacity(), 0); + assert!(decode.held.is_empty()); + } + fn track(id: u32, kind: TrackKind, codec: TrackCodec, channels: u8) -> TrackInfo { TrackInfo { id, diff --git a/crates/vuio-core/src/media/transcode/video.rs b/crates/vuio-core/src/media/transcode/video.rs index bfdc282..4560921 100644 --- a/crates/vuio-core/src/media/transcode/video.rs +++ b/crates/vuio-core/src/media/transcode/video.rs @@ -418,7 +418,10 @@ impl AudioDecode { /// Take one frame's decoded PCM: note where the packet says the run starts, /// widen the samples to the output's channel count, and encode them. fn take(&mut self, sink: &mut TrackSink, ticks: u64, pcm: Vec) -> Result<()> { - self.anchors.push(ticks as i64 - self.decoded as i64); + // Once anchored, no later estimate is consulted or needs retaining. + if self.next_dts.is_none() { + self.anchors.push(ticks as i64 - self.decoded as i64); + } self.decoded += (pcm.len() / (self.decoded_channels as usize * 2)) as u64; let pcm = super::fit_channels(&pcm, self.decoded_channels, DECODED_CHANNELS); let adts = self.encoder.push(&pcm)?; @@ -496,6 +499,7 @@ type PrimedPacket = (u32, i64, Vec); /// than that, and small enough that a file with a track that never appears /// costs nothing much to give up on. const PRIME_PACKETS: usize = 512; +const PRIME_BYTES: usize = 16 * 1024 * 1024; /// Read far enough ahead to describe every Dolby track being passed through. /// @@ -526,11 +530,16 @@ fn prime_dolby_tracks( return (primed, first_frames); } + let mut bytes = 0; for _ in 0..PRIME_PACKETS { + if bytes >= PRIME_BYTES { + break; + } let Ok(Some(packet)) = format.next_packet() else { break; }; let (id, pts, data) = (packet.track_id, packet.pts.get(), packet.data.to_vec()); + bytes += data.len(); if wanted.contains(&id) { first_frames.entry(id).or_insert_with(|| data.clone()); } @@ -645,3 +654,50 @@ fn track_time_base( .find(|t| t.id == track_id) .and_then(|t| t.time_base) } + +#[cfg(all(test, feature = "transcode-ac3"))] +mod tests { + use super::*; + + #[test] + fn timing_estimates_stop_accumulating_after_the_run_is_placed() { + let ac3 = include_bytes!("../../../../vuio-codec-ac3/tests/fixtures/sine440_stereo.ac3"); + let (decoder, _) = + PcmDecoder::open(TranscodeCodec::Ac3, 48_000, Some(2), &ac3[..768]).unwrap(); + let mut decode = AudioDecode { + codec: TranscodeCodec::Ac3, + decoder, + encoder: AacEncoder::new(48_000, 2).unwrap(), + decoded_channels: 2, + next_dts: None, + anchors: Vec::new(), + decoded: 0, + held: Vec::new(), + }; + let track = TrackInfo { + id: 1, + track_kind: TrackKind::Audio, + codec: "AAC".into(), + codec_kind: TrackCodec::Aac, + language: None, + name: None, + sample_rate: Some(48_000), + channels: Some(2), + width: None, + height: None, + is_default: true, + extra_data: vec![0x11, 0x90], + }; + let mut sink = TrackSink::new(track, None); + for frame in 0..ANCHOR_PACKETS * 2 { + decode + .take(&mut sink, frame as u64 * 1024, vec![0; 4096]) + .unwrap(); + sink.pending.clear(); + } + assert!(decode.next_dts.is_some()); + assert!(decode.anchors.is_empty()); + assert_eq!(decode.anchors.capacity(), 0); + assert!(decode.held.is_empty()); + } +} diff --git a/crates/vuio-core/src/mediainfo/job.rs b/crates/vuio-core/src/mediainfo/job.rs index 6c0f7d6..9173b28 100644 --- a/crates/vuio-core/src/mediainfo/job.rs +++ b/crates/vuio-core/src/mediainfo/job.rs @@ -21,6 +21,8 @@ use tokio_util::sync::CancellationToken; /// Records are written in batches: one transaction per file would make the write /// lock the bottleneck in a job that is otherwise waiting on the network. const WRITE_BATCH: usize = 25; +/// A provider-limited run can take days. Keep only the next page of ids in RAM. +const WORK_PAGE: usize = 256; /// What the dashboard polls while a run is in progress. #[derive(Clone, Debug, Default)] @@ -272,9 +274,9 @@ async fn set_up_library_fetch(state: AppState) }; let threshold = settings.min_confidence.min(100); - let pending = match state + let (total, through_id) = match state .database - .media_ids_missing_mediainfo(MEDIAINFO_VERSION, threshold) + .missing_mediainfo_summary(MEDIAINFO_VERSION, threshold) .await { Ok(pending) => pending, @@ -288,7 +290,6 @@ async fn set_up_library_fetch(state: AppState) return Err(error); } }; - let total = pending.len(); // A child of the application token, so shutdown stops the run without the // caller having to remember to cancel it. @@ -304,7 +305,7 @@ async fn set_up_library_fetch(state: AppState) let tracker = state.background_tasks.clone(); tracker.spawn(async move { - let outcome = fetch_all(&state, generation, pending, cancel.clone()).await; + let outcome = fetch_all(&state, generation, through_id, cancel.clone()).await; let cancelled = cancel.is_cancelled(); let error = outcome.err().map(|error| error.to_string()); if let Some(error) = error.as_deref() { @@ -326,7 +327,7 @@ async fn set_up_library_fetch(state: AppState) async fn fetch_all( state: &AppState, generation: u64, - pending: Vec, + through_id: i64, cancel: CancellationToken, ) -> Result<()> { let config = state.current_config(); @@ -349,67 +350,84 @@ async fn fetch_all( let mut batch: Vec = Vec::with_capacity(WRITE_BATCH); - for media_file_id in pending { - if cancel.is_cancelled() { + let mut after_id = 0; + while !cancel.is_cancelled() { + let pending = state + .database + .media_ids_missing_mediainfo( + MEDIAINFO_VERSION, + threshold, + after_id, + through_id, + WORK_PAGE, + ) + .await?; + if pending.is_empty() { break; } - - let Some(file) = state.database.get_file_by_id(media_file_id).await? else { - continue; - }; - { - let mut job = state.mediainfo_job.lock().await; - if job.generation != generation { - // Superseded. Its progress is not ours to write. - return Ok(()); + for media_file_id in pending { + after_id = media_file_id; + if cancel.is_cancelled() { + break; } - job.current = Some(file.filename.clone()); - } - let outcome = match query_for(&file) { - Some((kind, query)) => { - fetch_one( - &http, - &providers, - &credentials, - artwork.as_ref(), - kind, - &query, - media_file_id, - ) - .await + let Some(file) = state.database.get_file_by_id(media_file_id).await? else { + continue; + }; + { + let mut job = state.mediainfo_job.lock().await; + if job.generation != generation { + // Superseded. Its progress is not ours to write. + return Ok(()); + } + job.current = Some(file.filename.clone()); } - // Nothing worth asking about is not a failure, it is a file this - // feature does not apply to. - None => Ok(None), - }; - let mut job = state.mediainfo_job.lock().await; - if job.generation != generation { - return Ok(()); - } - job.processed += 1; - match outcome { - Ok(Some(record)) => { - if record.confidence >= threshold { - job.matched += 1; - } else { - job.low_confidence += 1; + let outcome = match query_for(&file) { + Some((kind, query)) => { + fetch_one( + &http, + &providers, + &credentials, + artwork.as_ref(), + kind, + &query, + media_file_id, + ) + .await } - batch.push(record); + // Nothing worth asking about is not a failure, it is a file this + // feature does not apply to. + None => Ok(None), + }; + + let mut job = state.mediainfo_job.lock().await; + if job.generation != generation { + return Ok(()); } - Ok(None) => {} - Err(error) => { - job.failed += 1; - job.last_error = Some(error.to_string()); - tracing::debug!(file = %file.filename, %error, "Media info lookup failed"); + job.processed += 1; + match outcome { + Ok(Some(record)) => { + if record.confidence >= threshold { + job.matched += 1; + } else { + job.low_confidence += 1; + } + batch.push(record); + } + Ok(None) => {} + Err(error) => { + job.failed += 1; + job.last_error = Some(error.to_string()); + tracing::debug!(file = %file.filename, %error, "Media info lookup failed"); + } } - } - drop(job); + drop(job); - if batch.len() >= WRITE_BATCH { - state.database.bulk_store_mediainfo(&batch).await?; - batch.clear(); + if batch.len() >= WRITE_BATCH { + state.database.bulk_store_mediainfo(&batch).await?; + batch.clear(); + } } } diff --git a/crates/vuio-core/src/platform/filesystem/metadata.rs b/crates/vuio-core/src/platform/filesystem/metadata.rs index 9bc8232..f5d3552 100644 --- a/crates/vuio-core/src/platform/filesystem/metadata.rs +++ b/crates/vuio-core/src/platform/filesystem/metadata.rs @@ -41,6 +41,23 @@ pub(crate) const TAGS_VERSION: u32 = 2; /// dominate the table. const MAX_TAG_VALUE_LEN: usize = 4096; +// Probes also read pictures and container indexes even though a scan only +// keeps text and stream properties. Bound this independently of the number of +// CPUs and of concurrent scans/watch events. The blocking job owns the permit. +static METADATA_PROBES: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(2); + +async fn limited_probe( + limit: &'static tokio::sync::Semaphore, + probe: impl FnOnce() -> T + Send + 'static, +) -> Result { + let permit = limit.acquire().await.expect("probe semaphore stays open"); + tokio::task::spawn_blocking(move || { + let _permit = permit; + probe() + }) + .await +} + /// Tags whose values are large enough to be worth storing nowhere. const OVERSIZED_TAGS: &[&str] = &["Lyrics", "AcoustIdFingerprint", "CdToc"]; @@ -59,7 +76,7 @@ pub(crate) async fn extract_stream_info( media_file: &mut MediaFile, ) -> Result<(), Box> { let path = media_file.path.clone(); - match tokio::task::spawn_blocking(move || probe_metadata(&path)).await { + match limited_probe(&METADATA_PROBES, move || probe_metadata(&path)).await { Ok(Ok(probed)) => { media_file.stream = probed.stream; if media_file.duration.is_none() { @@ -91,7 +108,7 @@ pub(crate) async fn extract_audio_metadata( // Probing is synchronous file I/O and parsing, so it stays off the async // runtime the same way the previous reader did. - match tokio::task::spawn_blocking(move || probe_metadata(&path)).await { + match limited_probe(&METADATA_PROBES, move || probe_metadata(&path)).await { Ok(Ok(probed)) => probed.apply(media_file), Ok(Err(error)) => { tracing::debug!( @@ -575,6 +592,30 @@ pub(crate) fn fallback_parse_filename(media_file: &mut MediaFile) { mod tests { use super::*; + #[tokio::test] + async fn cancelling_a_probe_keeps_its_slot_until_blocking_work_finishes() { + static LIMIT: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(1); + let (started, running) = tokio::sync::oneshot::channel(); + let (release, blocked) = std::sync::mpsc::channel(); + let request = tokio::spawn(limited_probe(&LIMIT, move || { + started.send(()).unwrap(); + blocked.recv_timeout(Duration::from_secs(5)).unwrap(); + })); + running.await.unwrap(); + request.abort(); + assert!(request.await.unwrap_err().is_cancelled()); + assert!( + LIMIT.try_acquire().is_err(), + "the parser still owns its slot" + ); + release.send(()).unwrap(); + let permit = tokio::time::timeout(Duration::from_secs(5), LIMIT.acquire()) + .await + .unwrap() + .unwrap(); + drop(permit); + } + /// An AIFF whose ID3v2.3 tag carries one front-cover picture of `len` bytes. /// /// Built by hand because symphonia only reads, and AIFF is the container a diff --git a/crates/vuio-core/src/radio/engine.rs b/crates/vuio-core/src/radio/engine.rs index 5dabc81..e714411 100644 --- a/crates/vuio-core/src/radio/engine.rs +++ b/crates/vuio-core/src/radio/engine.rs @@ -75,12 +75,12 @@ impl NowPlaying { } } -/// One track in a station's queue. +/// Paths are needed only while sorting and resuming a queue. Playout retains +/// just the ids and loads one track's current metadata when it reaches it. #[derive(Clone, Debug)] struct Track { + id: i64, path: PathBuf, - title: String, - artist: Option, } /// A station that is on the air. @@ -269,7 +269,7 @@ impl Station { /// The queue a station will play, and what had to be left out of it. struct QueuePlan { - tracks: Vec, + tracks: Vec, codec: Codec, skipped: usize, } @@ -317,20 +317,13 @@ async fn build_queue( if !folders.iter().any(|folder| is_within(path, folder)) { return Ok(()); } - let track = Track { - path: PathBuf::from(path), - title: file - .title() - .filter(|title| !title.is_empty()) - .unwrap_or_else(|| file.filename()) - .to_owned(), - artist: file.artist().filter(|a| !a.is_empty()).map(str::to_owned), + let Some(id) = file.id() else { return Ok(()) }; + let destination = match crate::radio::frames::codec_for_path(Path::new(path)) { + Some(Codec::Mp3) => &mut mp3, + Some(Codec::Aac) => &mut aac, + None => { skipped += 1; return Ok(()) } }; - match crate::radio::frames::codec_for_path(&track.path) { - Some(Codec::Mp3) => mp3.push(track), - Some(Codec::Aac) => aac.push(track), - None => skipped += 1, - } + destination.push(Track { id, path: PathBuf::from(path) }); Ok(()) })?; @@ -366,15 +359,18 @@ async fn build_queue( (aac, Codec::Aac) }; - tracks.sort_by(|left, right| left.path.cmp(&right.path)); + tracks.sort_unstable_by(|left, right| left.path.cmp(&right.path)); if row.mode == BroadcastMode::Shuffle { SplitMix64::new(row.seed).shuffle(&mut tracks); } resume_after(&mut tracks, row.cursor_path.as_deref()); + let mut ids: Vec<_> = tracks.into_iter().map(|track| track.id).collect(); + // collect may reuse the larger Track allocation in place. + ids.shrink_to_fit(); Ok(QueuePlan { - tracks, + tracks: ids, codec, skipped, }) @@ -422,7 +418,7 @@ struct Playout { station: Arc, state: AppState, row: RadioStation, - tracks: Vec, + tracks: Vec, random: SplitMix64, } @@ -504,11 +500,11 @@ impl Playout { // The clock advances at emission, including audio sent before a later // read fails. A track's final Result cannot tell us whether it was silent. let audio_before_pass = clock.audio; - for track in &queue { + for &track_id in &queue { if self.station.cancel.is_cancelled() { return; } - match self.play(track, &mut clock).await { + match self.play(track_id, &mut clock).await { Ok(()) => {} // A track that has been moved or is not what its extension // claims should cost one track, not the station. Once a whole @@ -517,12 +513,12 @@ impl Playout { // pass, for as long as it stays gone. Err(error) if !quiet_so_far => tracing::warn!( station = %self.row.name, - path = %track.path.display(), + track_id, "Skipping a track that could not be broadcast: {error:#}" ), Err(error) => tracing::debug!( station = %self.row.name, - path = %track.path.display(), + track_id, "Skipping a track that could not be broadcast: {error:#}" ), } @@ -617,7 +613,13 @@ impl Playout { /// Play one track, in real time, to everyone listening. `clock` is the /// station's, not this track's — see [`PlayoutClock`]. - async fn play(&self, track: &Track, clock: &mut PlayoutClock) -> Result<()> { + async fn play(&self, track_id: i64, clock: &mut PlayoutClock) -> Result<()> { + let track = self + .state + .database + .get_file_by_id(track_id) + .await? + .ok_or_else(|| anyhow::anyhow!("track {track_id} is no longer in the library"))?; let reader = TrackReader::open(&track.path, self.station.codec).await?; // `send_replace` rather than `send`: what is playing is state the studio @@ -625,8 +627,9 @@ impl Playout { // a value while the channel has no receivers — which is exactly the // case for a station nobody has tuned into yet. self.station.now_playing.send_replace(NowPlaying { - title: track.title.clone(), - artist: track.artist.clone(), + title: track.title.as_deref().filter(|title| !title.is_empty()) + .unwrap_or(&track.filename).to_owned(), + artist: track.artist.as_ref().filter(|artist| !artist.is_empty()).cloned(), path: Some(track.path.to_string_lossy().into_owned()), started_at_epoch_secs: SystemTime::now() .duration_since(UNIX_EPOCH) @@ -634,6 +637,7 @@ impl Playout { .unwrap_or_default(), }); self.record_cursor(&track.path).await; + drop(track); self.station.play_reader(reader, clock).await } @@ -795,16 +799,26 @@ mod tests { fn queue(names: &[&str]) -> Vec { names .iter() - .map(|name| Track { + .enumerate() + .map(|(id, name)| Track { + id: id as i64, path: PathBuf::from(format!("/music/{name}.mp3")), - title: (*name).to_owned(), - artist: None, }) .collect() } fn order(tracks: &[Track]) -> Vec { - tracks.iter().map(|track| track.title.clone()).collect() + tracks + .iter() + .map(|track| { + track + .path + .file_stem() + .unwrap() + .to_string_lossy() + .into_owned() + }) + .collect() } #[test] diff --git a/crates/vuio-core/src/radio/frames.rs b/crates/vuio-core/src/radio/frames.rs index 545700a..8502925 100644 --- a/crates/vuio-core/src/radio/frames.rs +++ b/crates/vuio-core/src/radio/frames.rs @@ -116,8 +116,7 @@ pub enum Framing { } /// A track being read out frame by frame. -pub enum TrackReader { - /// A file that is already a run of frames, cut from a rolling buffer. +pub enum TrackReader { /// A file that is already a run of frames, cut from a rolling buffer. Framed { file: tokio::fs::File, buffer: BytesMut, @@ -127,9 +126,11 @@ pub enum TrackReader { /// no audio and must not be broadcast. first_frame: bool, }, - /// A container that had to be demuxed up front. - Prepared { - frames: std::vec::IntoIter, + /// A synchronous container reader feeding a small, bounded queue. + #[cfg(feature = "metadata")] + Demuxed { + frames: tokio::sync::mpsc::Receiver>, + first: Option, }, } @@ -149,11 +150,17 @@ impl TrackReader { #[cfg(feature = "metadata")] (Codec::Aac, "m4a" | "m4b" | "mp4") => { let owned = path.to_path_buf(); - let frames = - tokio::task::spawn_blocking(move || demux_mp4_aac(&owned)).await??; - Ok(Self::Prepared { - frames: frames.into_iter(), - }) + // At most 32 ADTS frames (under 256 KiB), regardless of track + // length. Dropping the receiver wakes a blocked producer, so + // skipping an audiobook also stops its demuxer. + let (sender, mut frames) = tokio::sync::mpsc::channel(32); + tokio::task::spawn_blocking(move || { + if let Err(error) = demux_mp4_aac(&owned, &sender) { + let _ = sender.blocking_send(Err(error)); + } + }); + let first = frames.recv().await.context("container yielded no AAC frames")??; + Ok(Self::Demuxed { frames, first: Some(first) }) } _ => bail!( "{} cannot be broadcast on a {} station", @@ -195,7 +202,11 @@ impl TrackReader { /// The next frame, or `None` at the end of the track. pub async fn next_frame(&mut self) -> Result> { match self { - Self::Prepared { frames } => Ok(frames.next()), + #[cfg(feature = "metadata")] + Self::Demuxed { frames, first } => match first.take() { + Some(frame) => Ok(Some(frame)), + None => frames.recv().await.transpose(), + }, Self::Framed { file, buffer, @@ -622,11 +633,10 @@ impl<'a> BitReader<'a> { /// Demux an MP4 into the ADTS frames an AAC stream is made of. /// -/// Blocking, and done in one pass when the track is opened rather than -/// incrementally: symphonia's reader is synchronous, and one track's worth of -/// frames is the same order of memory as the file itself. +/// Blocking, with backpressure from the playout clock. The receiver closing is +/// normal cancellation and must stop the read before another packet is parsed. #[cfg(feature = "metadata")] -fn demux_mp4_aac(path: &Path) -> Result> { +fn demux_mp4_aac(path: &Path, sender: &tokio::sync::mpsc::Sender>) -> Result<()> { use symphonia::core::codecs::audio::well_known::CODEC_ID_AAC; use symphonia::core::formats::probe::Hint; use symphonia::core::formats::{FormatOptions, TrackType}; @@ -687,8 +697,10 @@ fn demux_mp4_aac(path: &Path) -> Result> { })?; let fallback = Duration::from_secs_f64(1024.0 / f64::from(config.sample_rate())); - let mut frames = Vec::new(); - while let Some(packet) = format.next_packet()? { + while !sender.is_closed() { + let Some(packet) = format.next_packet()? else { + break; + }; if packet.track_id != track_id || packet.data.is_empty() { continue; } @@ -700,25 +712,128 @@ fn demux_mp4_aac(path: &Path) -> Result> { .filter(|value| !value.is_zero()) .unwrap_or(fallback); + if packet.data.len() > 0x1fff - 7 { + bail!("AAC packet is too large for an ADTS frame"); + } let mut bytes = BytesMut::with_capacity(7 + packet.data.len()); bytes.extend_from_slice(&config.header(packet.data.len())); bytes.extend_from_slice(&packet.data); - frames.push(Frame { + if sender.blocking_send(Ok(Frame { bytes: bytes.freeze(), duration, - }); - } - - if frames.is_empty() { - bail!("{} yielded no AAC frames", path.display()); + })).is_err() { + break; + } } - Ok(frames) + Ok(()) } #[cfg(test)] mod tests { use super::*; + #[cfg(feature = "metadata")] + fn aac_container() -> tempfile::NamedTempFile { + use crate::media::remux::{Fmp4Writer, MediaPacket, TrackCodec, TrackInfo, TrackKind}; + use std::io::Write; + let track = TrackInfo { + id: 1, + track_kind: TrackKind::Audio, + codec: "AAC".into(), + codec_kind: TrackCodec::Aac, + language: None, + name: None, + sample_rate: Some(48_000), + channels: Some(2), + width: None, + height: None, + is_default: true, + extra_data: vec![0x11, 0x90], + }; + let packets: Vec<_> = (0..512) + .map(|i| MediaPacket { + track_id: 1, + pts: i * 1024, + dts: i * 1024, + duration: 1024, + is_keyframe: true, + data: vec![(i % 251) as u8; 128], + }) + .collect(); + let mut file = tempfile::Builder::new().suffix(".m4a").tempfile().unwrap(); + file.write_all(&Fmp4Writer::build_ftyp()).unwrap(); + file.write_all(&Fmp4Writer::build_moov(&track)).unwrap(); + file.write_all(&Fmp4Writer::build_segment(1, &track, 0, &packets)) + .unwrap(); + file + } + + #[cfg(feature = "metadata")] + #[tokio::test] + async fn aac_container_streams_every_frame_in_order() { + let file = aac_container(); + let mut reader = TrackReader::open(file.path(), Codec::Aac).await.unwrap(); + let mut count = 0; + while let Some(frame) = reader.next_frame().await.unwrap() { + assert_eq!(&frame.bytes[7..], &[(count % 251) as u8; 128]); + assert_eq!(frame.bytes.len(), 135); + assert!((frame.duration.as_secs_f64() - 1024.0 / 48_000.0).abs() < 1e-8); + count += 1; + } + assert_eq!(count, 512); + } + + #[cfg(feature = "metadata")] + #[tokio::test] + async fn dropping_the_radio_reader_unblocks_the_demuxer() { + let file = aac_container(); + let path = file.path().to_path_buf(); + let (sender, mut receiver) = tokio::sync::mpsc::channel(1); + let worker = tokio::task::spawn_blocking(move || demux_mp4_aac(&path, &sender)); + receiver.recv().await.unwrap().unwrap(); + assert!( + !worker.is_finished(), + "a bounded producer cannot read the whole file ahead" + ); + drop(receiver); + tokio::time::timeout(Duration::from_secs(5), worker) + .await + .unwrap() + .unwrap() + .unwrap(); + } + + /// Supply VUIO_MEMORY_AUDIO=/path/to/long.m4a. VUIO_RETAIN_RADIO=1 + /// reproduces the former whole-track retention for a separate RSS run. + #[cfg(feature = "metadata")] + #[tokio::test] + #[ignore = "isolated audiobook allocation probe"] + async fn radio_rss_probe() { + use std::hash::{Hash, Hasher}; + let path = std::env::var_os("VUIO_MEMORY_AUDIO").expect("set VUIO_MEMORY_AUDIO"); + let mut reader = TrackReader::open(Path::new(&path), Codec::Aac) + .await + .unwrap(); + let mut held = Vec::new(); + let retain = std::env::var_os("VUIO_RETAIN_RADIO").is_some(); + let mut hash = std::collections::hash_map::DefaultHasher::new(); + let mut bytes = 0; + let mut frames = 0; + while let Some(frame) = reader.next_frame().await.unwrap() { + bytes += frame.bytes.len(); + frames += 1; + frame.bytes.hash(&mut hash); + if retain { + held.push(frame); + } + } + println!( + "radio: {frames} frames, {bytes} bytes, hash {}", + hash.finish() + ); + std::hint::black_box(held); + } + /// A 128 kbit/s, 44.1 kHz MPEG-1 Layer III frame header. fn mpeg1_layer3_header() -> [u8; 4] { [0xFF, 0xFB, 0x90, 0x00] diff --git a/crates/vuio-core/src/watcher/file_ids.rs b/crates/vuio-core/src/watcher/file_ids.rs index 0bacf43..820be15 100644 --- a/crates/vuio-core/src/watcher/file_ids.rs +++ b/crates/vuio-core/src/watcher/file_ids.rs @@ -112,6 +112,16 @@ impl Generation { self.outside.retain(|key, _| !key.starts_with(prefix)); self.len = self.below.iter().map(HashMap::len).sum::() + self.outside.len(); } + + /// Forget a deregistered watch root, including the hash table's retained + /// bucket allocation. Removing from the vector also keeps later root slots + /// aligned with their maps. + fn remove_root(&mut self, index: usize) { + if index < self.below.len() { + self.below.remove(index); + } + self.len = self.below.iter().map(HashMap::len).sum::() + self.outside.len(); + } } impl BoundedFileIdCache { @@ -226,6 +236,18 @@ impl FileIdCache for BoundedFileIdCache { fn remove_path(&mut self, path: &Path) { self.live.remove_under(&self.roots, path); self.previous.remove_under(&self.roots, path); + // `unwatch` calls this for a root, while ordinary delete events call it + // for files or subdirectories. Keeping a removed root here would leave + // its now-empty HashMap's bucket allocation alive indefinitely. It also + // made every later lookup walk all roots ever configured, not just the + // roots still watched. + for index in (0..self.roots.len()).rev() { + if self.roots[index].starts_with(path) { + self.roots.remove(index); + self.live.remove_root(index); + self.previous.remove_root(index); + } + } } /// Deliberately does nothing. @@ -357,6 +379,68 @@ mod tests { cache.remove_path(temp.path()); assert!(cache.is_empty()); + assert!(cache.roots.is_empty()); + assert!(cache.live.below.is_empty()); + } + + #[test] + fn replacing_watch_roots_releases_old_tables_and_preserves_other_roots() { + let temp = tempfile::tempdir().unwrap(); + let roots: Vec<_> = (0..3) + .map(|index| temp.path().join(format!("root_{index}"))) + .collect(); + for root in &roots { + fs::create_dir(root).unwrap(); + write_files(root, 8); + } + + let mut cache = BoundedFileIdCache::with_capacity(24); + cache.add_path(&roots[0], RecursiveMode::Recursive); + cache.add_path(&roots[1], RecursiveMode::Recursive); + assert_eq!(cache.len(), 16); + + cache.remove_path(&roots[0]); + assert_eq!(cache.roots, vec![roots[1].clone()]); + assert_eq!(cache.live.below.len(), 1); + assert_eq!(cache.len(), 8); + assert!(cache.cached_file_id(&roots[1].join("file_0.mp3")).is_some()); + + cache.add_path(&roots[2], RecursiveMode::Recursive); + assert_eq!(cache.roots, vec![roots[1].clone(), roots[2].clone()]); + assert_eq!(cache.live.below.len(), 2); + assert_eq!(cache.len(), 16); + assert!(cache.cached_file_id(&roots[2].join("file_0.mp3")).is_some()); + + cache.remove_path(temp.path()); + assert!(cache.roots.is_empty()); + assert!(cache.live.below.is_empty()); + assert!(cache.is_empty()); + } + + #[test] + fn removing_a_root_reindexes_both_generations() { + let temp = tempfile::tempdir().unwrap(); + let first = temp.path().join("first"); + let second = temp.path().join("second"); + fs::create_dir(&first).unwrap(); + fs::create_dir(&second).unwrap(); + write_files(&first, 2); + write_files(&second, 2); + + let mut cache = BoundedFileIdCache::with_capacity(2); + cache.add_path(&first, RecursiveMode::Recursive); + // Register the second root without seeding it: the first filled the + // cap. A later event rotates the first root's table to `previous`. + cache.add_path(&second, RecursiveMode::Recursive); + cache.add_path(&second.join("file_0.mp3"), RecursiveMode::NonRecursive); + assert!(cache.cached_file_id(&first.join("file_0.mp3")).is_some()); + assert!(cache.cached_file_id(&second.join("file_0.mp3")).is_some()); + + cache.remove_path(&first); + assert_eq!(cache.roots, vec![second.clone()]); + assert!(cache.cached_file_id(&second.join("file_0.mp3")).is_some()); + assert!(cache.cached_file_id(&first.join("file_0.mp3")).is_none()); + assert_eq!(cache.len(), 1); } #[test] diff --git a/crates/vuio-core/src/web/casting.rs b/crates/vuio-core/src/web/casting.rs index bab4bba..f445d5b 100644 --- a/crates/vuio-core/src/web/casting.rs +++ b/crates/vuio-core/src/web/casting.rs @@ -4,7 +4,7 @@ pub(crate) mod helpers; pub use helpers::{cast_file_helper, cast_tracks_helper}; use crate::{ - database::{DatabaseManager, FileLocation, MediaFileView}, + database::{DatabaseManager, FileLocation}, state::AppState, }; use axum::{extract::State, http::StatusCode, response::IntoResponse}; @@ -281,24 +281,21 @@ async fn resolve_castable_folder( .fold(root.clone(), |path, component| path.join(component)); let files = state .database - .get_files_with_path_prefix(folder.to_string_lossy().as_ref()) + .get_file_locations_with_path_prefix(folder.to_string_lossy().as_ref()) .await .map_err(|error| format!("Database error: {error}"))?; for file in files { - if !is_castable_mime(file.mime_type()) || !matches_media_kind(file.mime_type(), media) { + if !is_castable_mime(&file.mime_type) || !matches_media_kind(&file.mime_type, media) { continue; } - let Some(location) = file.to_file_location() else { - continue; - }; - if seen.insert(location.id) { + if seen.insert(file.id) { let relative = file .path .strip_prefix(&root) .unwrap_or(&file.path) .to_string_lossy() .into_owned(); - videos.push((relative, location)); + videos.push((relative, file)); } } } diff --git a/crates/vuio-core/src/web/casting/helpers.rs b/crates/vuio-core/src/web/casting/helpers.rs index 5de9c86..2e7749f 100644 --- a/crates/vuio-core/src/web/casting/helpers.rs +++ b/crates/vuio-core/src/web/casting/helpers.rs @@ -544,19 +544,19 @@ pub(crate) async fn tool_cast_folder_to_renderer( let canonical = crate::web::mcp::canonical_media_path(state, path).await?; let files = state .database - .get_files_with_path_prefix(&canonical) + .get_file_locations_with_path_prefix(&canonical) .await .map_err(|error| format!("Database error: {error}"))?; let mut tracks: Vec<(String, FileLocation)> = files .into_iter() .filter(|file| { - crate::web::casting::is_castable_mime(file.mime_type()) - && crate::web::casting::matches_media_kind(file.mime_type(), media) + crate::web::casting::is_castable_mime(&file.mime_type) + && crate::web::casting::matches_media_kind(&file.mime_type, media) }) - .filter_map(|file| { + .map(|file| { let name = file.path.to_string_lossy().into_owned(); - file.to_file_location().map(|location| (name, location)) + (name, file) }) .collect(); if tracks.is_empty() { diff --git a/crates/vuio-core/src/web/diagnostics.rs b/crates/vuio-core/src/web/diagnostics.rs index 1afcc8f..eb53ae1 100644 --- a/crates/vuio-core/src/web/diagnostics.rs +++ b/crates/vuio-core/src/web/diagnostics.rs @@ -232,7 +232,8 @@ async fn read_last_log_lines( let start = length.saturating_sub(MAX_TAIL_BYTES); file.seek(std::io::SeekFrom::Start(start)).await?; let mut bytes = Vec::with_capacity((length - start) as usize); - file.read_to_end(&mut bytes).await?; + // A busy log can grow after metadata() and while it is being read. + file.take(MAX_TAIL_BYTES).read_to_end(&mut bytes).await?; let text = String::from_utf8_lossy(&bytes); let lines = text.lines().rev().take(limit).collect::>(); let mut result = lines.into_iter().rev().collect::>().join("\n"); diff --git a/crates/vuio-core/src/web/remux_streaming.rs b/crates/vuio-core/src/web/remux_streaming.rs index 13d1dc5..936f6c1 100644 --- a/crates/vuio-core/src/web/remux_streaming.rs +++ b/crates/vuio-core/src/web/remux_streaming.rs @@ -40,6 +40,10 @@ use tracing::error; /// a keyframe every ten seconds has ten-second segments. const SEGMENT_DURATION_SECS: u32 = 4; +// Passthrough video also buffers a whole segment. Bound those builds even when +// no audio decoder is enabled, including work whose HTTP request was dropped. +static SEGMENT_BUILDS: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(4); + /// How one film's segments are laid out on its timeline. struct Segmentation { /// Where each segment starts, followed by where the last one ends: one more @@ -480,9 +484,16 @@ async fn segment_response( } } - // Only a decoded rendition is rationed. A passthrough copy is file I/O, and - // refusing it under load would stop a browser from playing a film the CPU - // was never being asked to work on. + let Ok(build_permit) = SEGMENT_BUILDS.try_acquire() else { + return Ok(( + axum::http::StatusCode::SERVICE_UNAVAILABLE, + [(header::RETRY_AFTER, "1")], + "All segment builders are in use.", + ) + .into_response()); + }; + + // Decoded renditions also share the CPU ceiling with progressive streams. #[cfg(feature = "transcode")] let _permit = if track.codec_kind.transcode_codec().is_some() { match state.transcode.try_acquire() { @@ -504,6 +515,9 @@ async fn segment_response( let owned_track = track.clone(); let (start_secs, end_secs) = range; let bytes = tokio::task::spawn_blocking(move || { + let _build_permit = build_permit; + #[cfg(feature = "transcode")] + let _transcode_permit = _permit; build_segment_bytes(&owned_path, &owned_track, seq, start_secs, end_secs) }) .await diff --git a/crates/vuio-core/src/web/transcode_streaming.rs b/crates/vuio-core/src/web/transcode_streaming.rs index 0b4f017..58e7a67 100644 --- a/crates/vuio-core/src/web/transcode_streaming.rs +++ b/crates/vuio-core/src/web/transcode_streaming.rs @@ -51,7 +51,7 @@ pub async fn serve_transcoded_aac( let Some(permit) = state.transcode.try_acquire() else { return Ok(busy(&state, &file.filename)); }; - let plan = plan_for(&state, &file).await?; + let (plan, permit) = plan_for(&state, &file, permit).await?; let response = Response::builder() .status(StatusCode::OK) @@ -139,7 +139,7 @@ pub async fn serve_transcoded_ac3( let Some(permit) = state.transcode.try_acquire() else { return Ok(busy(&state, &file.filename)); }; - let plan = plan_for(&state, &file).await?; + let (plan, permit) = plan_for(&state, &file, permit).await?; let Some(total) = plan.ac3_size() else { let response = Response::builder() @@ -320,7 +320,7 @@ pub async fn serve_transcoded_wav( return Ok(busy(&state, &file.filename)); }; - let plan = plan_for(&state, &file).await?; + let (plan, permit) = plan_for(&state, &file, permit).await?; // A source that will not say how long it is gets a chunked body: no length, // no ranges, `DLNA.ORG_OP=00`. That loses the scrub bar; a guessed length @@ -477,29 +477,34 @@ fn busy(state: &AppState, filename: &str) -> Response { pub(crate) async fn plan_for( state: &AppState, file: &Resolved, -) -> Result, AppError> { + permit: tokio::sync::OwnedSemaphorePermit, +) -> Result<(Arc, tokio::sync::OwnedSemaphorePermit), AppError> { let key = IndexKey::for_file(file.id, &file.path) .await .ok_or(AppError::NotFound)?; if let Some(plan) = state.transcode.cached(&key).await { - return Ok(plan); + return Ok((plan, permit)); } let owned = file.path.clone(); let codec = file.codec; let kind = file.kind; - let plan = tokio::task::spawn_blocking(move || match kind { - SourceKind::Elementary => AudioPlan::elementary(&owned, codec), - #[cfg(feature = "demux")] - SourceKind::Container => AudioPlan::container(&owned), + let (plan, permit) = tokio::task::spawn_blocking(move || { + // Planning can index an entire recording. Keep its slot even if the + // waiting HTTP handler is cancelled; return it for the streaming phase. + let plan = match kind { + SourceKind::Elementary => AudioPlan::elementary(&owned, codec), + #[cfg(feature = "demux")] + SourceKind::Container => AudioPlan::container(&owned), + }; + (plan, permit) }) .await - .map_err(|e| AppError::Internal(anyhow::anyhow!("transcode planner panicked: {e}")))? - .map_err(AppError::Internal)?; - let plan = Arc::new(plan); + .map_err(|e| AppError::Internal(anyhow::anyhow!("transcode planner panicked: {e}")))?; + let plan = Arc::new(plan.map_err(AppError::Internal)?); state.transcode.remember(key, plan.clone()).await; - Ok(plan) + Ok((plan, permit)) } /// Build the response body: the WAV header, then decoded PCM, clipped to the diff --git a/crates/vuio-core/tests/mediainfo_integration_tests.rs b/crates/vuio-core/tests/mediainfo_integration_tests.rs index 5f707be..89e58c2 100644 --- a/crates/vuio-core/tests/mediainfo_integration_tests.rs +++ b/crates/vuio-core/tests/mediainfo_integration_tests.rs @@ -157,7 +157,10 @@ async fn work_is_whatever_is_missing_stale_or_not_good_enough() { // Never looked up. assert_eq!( - database.media_ids_missing_mediainfo(1, 60).await.unwrap(), + database + .media_ids_missing_mediainfo(1, 60, 0, i64::MAX, 10) + .await + .unwrap(), vec![id] ); @@ -167,24 +170,84 @@ async fn work_is_whatever_is_missing_stale_or_not_good_enough() { .await .unwrap(); assert!(database - .media_ids_missing_mediainfo(1, 60) + .media_ids_missing_mediainfo(1, 60, 0, i64::MAX, 10) .await .unwrap() .is_empty()); // Raising the threshold past it puts it back in the queue. assert_eq!( - database.media_ids_missing_mediainfo(1, 95).await.unwrap(), + database + .media_ids_missing_mediainfo(1, 95, 0, i64::MAX, 10) + .await + .unwrap(), vec![id] ); // So does bumping the reader version, which is the whole point of storing it. assert_eq!( - database.media_ids_missing_mediainfo(2, 60).await.unwrap(), + database + .media_ids_missing_mediainfo(2, 60, 0, i64::MAX, 10) + .await + .unwrap(), vec![id] ); } +#[tokio::test] +async fn pending_work_pages_advance_past_misses_and_exclude_later_insertions() { + let (database, first_id, _temp) = database_with_one_file().await; + let mut expected = vec![first_id]; + for i in 0..10 { + expected.push( + database + .store_media_file(&MediaFile::new( + PathBuf::from(format!("/media/page-{i}.mp4")), + 1, + "video/mp4".into(), + )) + .await + .unwrap(), + ); + } + let (count, through) = database.missing_mediainfo_summary(1, 60).await.unwrap(); + assert_eq!(count, expected.len()); + assert_eq!(through, *expected.last().unwrap()); + let later = database + .store_media_file(&MediaFile::new( + PathBuf::from("/media/later.mp4"), + 1, + "video/mp4".into(), + )) + .await + .unwrap(); + let mut cursor = 0; + let mut seen = Vec::new(); + loop { + let page = database + .media_ids_missing_mediainfo(1, 60, cursor, through, 3) + .await + .unwrap(); + assert!(page.len() <= 3); + let Some(last) = page.last() else { break }; + cursor = *last; + // Successful lookups disappear from the query; misses remain eligible. + // Neither may shift the next page or make this run retry a miss. + database + .bulk_store_mediainfo(&[record_for(page[0], 90)]) + .await + .unwrap(); + seen.extend(page); + } + assert_eq!(seen, expected); + assert!(!seen.contains(&later)); + assert!(database + .media_ids_missing_mediainfo(1, 60, 0, through, 0) + .await + .unwrap() + .is_empty()); +} + #[tokio::test] async fn a_rescan_does_not_wipe_fetched_media_info() { // The reason this lives in its own table rather than `media_tags`, which is diff --git a/docs/memory-audit.md b/docs/memory-audit.md new file mode 100644 index 0000000..1e2fb19 --- /dev/null +++ b/docs/memory-audit.md @@ -0,0 +1,120 @@ +# Memory audit: September 2026 + +## Measured peak RSS + +Measured on macOS in separate processes using `/usr/bin/time -l` and the same +debug-profile core test binary (the workspace optimizes codecs in this profile). +These are isolated workload measurements, **not whole-server or idle-RSS claims**. +The comparison paths reproduce the previous allocation/retention patterns inside +the probes; they are not separate builds of the old revision. + +| Workload | Previous pattern | Current implementation | Reduction | +| --- | ---: | ---: | ---: | +| Build an fMP4 fragment with 64 MiB of payload | 278,380,544 B (265.5 MiB) | 144,293,888 B (137.6 MiB) | 48% | +| Read a two-hour AAC audiobook for radio | 164,003,840 B (156.4 MiB) | 14,548,992 B (13.9 MiB) | 91% | + +Both fragment paths produced 67,108,976 bytes, with hash +`9318397001415464912`. Both radio paths produced 336,963 frames and 117,404,618 +bytes, with hash `15861541014108818885`. Hashes use Rust's `DefaultHasher` and +are useful for comparison within the same build, not as a stable file format. +The radio probe drains frames without real-time pacing; the production channel +also bounds read-ahead when playback is slower. + +The fragment builder now writes `mdat` directly into its final output instead +of keeping two additional payload-sized copies. The radio reader now uses +backpressure with a 32-frame queue instead of retaining the entire audiobook. + +## Other fixes and bounds + +- Radio queues retain track IDs rather than paths, titles and artists; only the + current track's metadata is loaded for playout. +- Elementary-stream frame indexes share immutable storage across listeners. + Their cache has a 12 MiB byte budget as well as a four-entry limit. Oversized + indexes can still be used by an active stream, but are not cached. +- Replacing cached chunks and segments updates byte accounting and evicts as + needed, including removal of stale entries on oversized replacement. +- Video/TS timestamp estimates stop accumulating after initial placement. + fMP4 Dolby priming also stops reading ahead after 16 MiB or 512 packets + (the byte threshold can be exceeded by the final packet). +- All HLS segment builds, including passthrough video, share four slots. Busy + requests receive 503 with `Retry-After: 1`. Metadata probes share two slots. + Blocking workers retain their permits after caller cancellation; elementary + transcode planning likewise keeps its existing transcode slot. +- Metadata-fetch jobs page pending IDs in groups of 256, using an initial ID + high-water mark; misses are not retried forever and later insertions do not + extend the job. +- Directory repair flushes accumulated directory deltas at 4,096 entries; + folder renames and scan deletions operate in 1,000-file batches. Playlist + resolution loads at most 512 full metadata records per batch. Folder casting + queries playback fields rather than full records. +- SQLite temporary sorts/index work can spill to disk (`temp_store = FILE`) + instead of requiring the entire temporary structure in RAM. +- AirPlay event/command queues are bounded. Diagnostic replies may be dropped + if their consumer is slow; remote commands use backpressure. Cast request + registration prunes abandoned waiters. Log-tail reads remain byte-bounded + even while a log grows. +- Watcher root removal drops its old file-ID hash tables, releasing retained + capacity while preserving other roots. AAC zeroed-allocation optimization is + explicitly opted into only by callers whose allocator guarantees zeroed memory. + +Regression coverage includes multi-page deletion, directory repair and metadata +jobs, playlist duplicates across batch boundaries, cache replacements, shared +frame storage, radio frame order/cancellation, metadata-probe cancellation, +fragment payload offsets, and long-running timestamp state. + +Verification: 838 core unit/integration tests, 75 casting unit tests and four +AAC codec tests passed; nine core tests were ignored (including the two RSS +probes run separately). Strict library Clippy and no-default-feature checks for +transcode-only and casting-only builds passed. Tests used all server features +except `web-ui`, whose generated assets are absent in this worktree. All-target +Clippy with `-D warnings` hits an existing unused web-UI test helper in that +feature configuration; the library lint run is clean. + +## Reproducing the RSS probes + +Build the unit-test executable (without the separately generated web UI): + +```sh +cargo test --locked -p vuio-core --no-default-features \ + --features casting,dashboard,diagnostics,mcp,metadata,mediainfo,transcode-ac3,transcode-dts,transcode-aac \ + --lib --no-run +``` + +Set `audit_test_binary` to the executable path Cargo prints, then run each case +in a fresh process: + +```sh +/usr/bin/time -l "$audit_test_binary" fragment_rss_probe --ignored --nocapture +VUIO_LEGACY_FRAGMENT=1 /usr/bin/time -l "$audit_test_binary" fragment_rss_probe --ignored --nocapture + +audit_media_dir=$(mktemp -d /tmp/vuio-memory-probe.XXXXXX) +ffmpeg -hide_banner -loglevel error -f lavfi \ + -i 'sine=frequency=440:sample_rate=48000:duration=10' \ + -ac 2 -c:a aac -b:a 128k "$audit_media_dir/seed.m4a" +ffmpeg -hide_banner -loglevel error -stream_loop 719 \ + -i "$audit_media_dir/seed.m4a" -t 7200 -c copy "$audit_media_dir/audiobook.m4a" +VUIO_MEMORY_AUDIO="$audit_media_dir/audiobook.m4a" /usr/bin/time -l \ + "$audit_test_binary" radio_rss_probe --ignored --nocapture +VUIO_MEMORY_AUDIO="$audit_media_dir/audiobook.m4a" VUIO_RETAIN_RADIO=1 \ + /usr/bin/time -l "$audit_test_binary" radio_rss_probe --ignored --nocapture +``` + +On Linux use `/usr/bin/time -v`; its maximum-RSS field is in KiB rather than +macOS's bytes. The generated media remains in the temporary directory for +repeat runs. + +## Remaining scaling limits + +This is not a guarantee that every allocation in the server is bounded. The +scanner still keeps one compact fingerprint per indexed file under the root +being scanned; very large roots remain a significant RAM workload. Casting and +radio queues also scale with their number of tracks, though their records are +smaller now. Active response bodies and indexes can outlive cache eviction. + +Symphonia's metadata/visual byte-limit options do not enforce every parser +allocation. Probe concurrency limits reduce simultaneous allocation peaks, +but do not impose a hard per-file memory ceiling. A malformed file, a very large +container index, or an unusually large video packet still needs separate +parser-level investigation. Measure representative whole-server workloads +before translating the isolated reductions above into an RSS expectation for +a deployment. From e6176de418e22550b0c42fdd9fbba3f278c75dd9 Mon Sep 17 00:00:00 2001 From: vyrti Date: Thu, 24 Sep 2026 01:00:57 +0300 Subject: [PATCH 09/12] Let metadata probes use every core again, up to eight 17d1309 capped symphonia probes at two for the whole process, to bound what the parsers allocate: symphonia declares a limit on picture bytes but no reader enforces it. The scanner, though, spreads its reads across every core on purpose (read_window's buffer_unordered), and two slots undid that. With 200 files already cached, two slots probed them in 7.9 ms and eight in 4.1 ms on this eight-core machine; on a network share, where a probe mostly waits on round trips, the gap is larger. The slots now follow the core count, at least two and at most eight, still shared by every scan and watch event, so a many-core server does not multiply the parser's peak by its core count. --- .../src/platform/filesystem/metadata.rs | 24 +++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/crates/vuio-core/src/platform/filesystem/metadata.rs b/crates/vuio-core/src/platform/filesystem/metadata.rs index f5d3552..70eb8f6 100644 --- a/crates/vuio-core/src/platform/filesystem/metadata.rs +++ b/crates/vuio-core/src/platform/filesystem/metadata.rs @@ -41,10 +41,26 @@ pub(crate) const TAGS_VERSION: u32 = 2; /// dominate the table. const MAX_TAG_VALUE_LEN: usize = 4096; -// Probes also read pictures and container indexes even though a scan only -// keeps text and stream properties. Bound this independently of the number of -// CPUs and of concurrent scans/watch events. The blocking job owns the permit. -static METADATA_PROBES: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(2); +/// Probes that may parse at once, across every scan and watch event. +/// +/// A probe also reads pictures and container indexes a scan does not keep — +/// symphonia declares a limit on picture bytes but no reader enforces it — so +/// the count is shared rather than per scan, and the blocking job owns its +/// permit. It follows the core count because a scan spreads its reads across +/// the cores (see `read_window` in the scanner): two slots halved the probe +/// rate on an eight-core machine with the files already cached, and on a +/// network share a probe spends most of its time waiting on round trips. +/// Eight is the ceiling, so a many-core server does not multiply the parser's +/// peak by its core count. +static METADATA_PROBES: std::sync::LazyLock = + std::sync::LazyLock::new(|| tokio::sync::Semaphore::new(metadata_probe_slots())); + +fn metadata_probe_slots() -> usize { + std::thread::available_parallelism() + .map(std::num::NonZeroUsize::get) + .unwrap_or(4) + .clamp(2, 8) +} async fn limited_probe( limit: &'static tokio::sync::Semaphore, From 4869f4898ba238a0f6241ffd2331cf5af74b530e Mon Sep 17 00:00:00 2001 From: vyrti Date: Thu, 24 Sep 2026 01:00:57 +0300 Subject: [PATCH 10/12] Queue HLS segment requests for a build slot instead of refusing them 17d1309 put passthrough segments behind the same four build slots as decoded ones, which bounds this path's memory, but a request that found them busy was answered 503 at once. A build keeps its slot until it finishes even when its request is gone, so a player that scrubs met the builds its own seeks had abandoned as a run of 503s, and passthrough had never been refused before. A request now waits up to five seconds for a slot, inside a player's own first-byte timeout (hls.js allows ten), and is refused only after that. --- crates/vuio-core/src/web/remux_streaming.rs | 59 +++++++++++++++++++-- 1 file changed, 56 insertions(+), 3 deletions(-) diff --git a/crates/vuio-core/src/web/remux_streaming.rs b/crates/vuio-core/src/web/remux_streaming.rs index 936f6c1..191f669 100644 --- a/crates/vuio-core/src/web/remux_streaming.rs +++ b/crates/vuio-core/src/web/remux_streaming.rs @@ -40,10 +40,32 @@ use tracing::error; /// a keyframe every ten seconds has ten-second segments. const SEGMENT_DURATION_SECS: u32 = 4; -// Passthrough video also buffers a whole segment. Bound those builds even when -// no audio decoder is enabled, including work whose HTTP request was dropped. +/// Segments being built at once, passthrough included. +/// +/// A build holds its segment twice over — the packets it read and the fragment +/// written from them — and a 4K remux's segment runs to tens of megabytes, so +/// this count is what bounds the path's memory. A build keeps its slot until it +/// finishes, even once the request that asked for it has gone. static SEGMENT_BUILDS: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(4); +/// How long a request waits for a build slot before it is turned away. +/// +/// Waiting rather than refusing on the spot: a passthrough build is file I/O, +/// so a slot is rarely far off, and a seek leaves the builds it abandoned +/// holding theirs until they finish — which a player that scrubs met as a run +/// of 503s. Five seconds sits inside a player's own first-byte timeout (hls.js +/// allows ten), so a request still turned away gets a 503 it retries rather +/// than a timeout it gives up on. +const SEGMENT_BUILD_WAIT: std::time::Duration = std::time::Duration::from_secs(5); + +/// A build slot from `limit`, queueing for at most `wait`. +async fn segment_build_slot( + limit: &'static tokio::sync::Semaphore, + wait: std::time::Duration, +) -> Option> { + tokio::time::timeout(wait, limit.acquire()).await.ok()?.ok() +} + /// How one film's segments are laid out on its timeline. struct Segmentation { /// Where each segment starts, followed by where the last one ends: one more @@ -484,7 +506,7 @@ async fn segment_response( } } - let Ok(build_permit) = SEGMENT_BUILDS.try_acquire() else { + let Some(build_permit) = segment_build_slot(&SEGMENT_BUILDS, SEGMENT_BUILD_WAIT).await else { return Ok(( axum::http::StatusCode::SERVICE_UNAVAILABLE, [(header::RETRY_AFTER, "1")], @@ -628,6 +650,37 @@ mod tests { ); } + /// A request that finds every builder busy queues for the next one to come + /// free. Those a seek abandoned finish within moments, and a player that + /// scrubs must not meet them as a run of 503s. + #[tokio::test] + async fn a_busy_builder_is_waited_for_rather_than_refused() { + static LIMIT: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(1); + let held = LIMIT.try_acquire().unwrap(); + let waiting = tokio::spawn(segment_build_slot( + &LIMIT, + std::time::Duration::from_secs(5), + )); + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + assert!(!waiting.is_finished(), "queued, not refused"); + + drop(held); + let slot = tokio::time::timeout(std::time::Duration::from_secs(5), waiting) + .await + .expect("the freed slot is handed on") + .unwrap(); + assert!(slot.is_some()); + } + + /// The wait is bounded: a builder that never frees still ends in a 503. + #[tokio::test] + async fn a_builder_that_never_frees_turns_the_request_away() { + static LIMIT: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(1); + let _held = LIMIT.try_acquire().unwrap(); + let slot = segment_build_slot(&LIMIT, std::time::Duration::from_millis(20)).await; + assert!(slot.is_none()); + } + #[test] #[ignore = "diagnostic helper for a locally generated Matroska fixture"] fn write_local_hls_fixture_segments() { From 9dacbaf6a5f8e8516fd1b9c84d7eac0c405f7db9 Mon Sep 17 00:00:00 2001 From: vyrti Date: Thu, 24 Sep 2026 01:00:57 +0300 Subject: [PATCH 11/12] Keep a radio track that is indexed again mid-pass MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Since 17d1309 a station's queue holds ids rather than paths. A row that is removed and indexed again, as a deleted-and-restored file or an editor's write-and-rename save leaves it, comes back under a new id, and the pass under way skipped the track; loop and shuffle stations picked it up only at the next pass, and a linear station, whose single pass is its broadcast, never played it. A queue of paths had played it anyway. A lookup that misses now reads the queue again and carries on from the latest track already tried, leaving out everything the pass attempted. One re-read per run of misses, so a folder being deleted costs one rebuild rather than one per track. The new test fails on the old loop, which broadcast a and c but not b. The ids handed to the re-read are every one the pass has dealt with, not the previous queue's slice. A second rebuild happens from wherever the library now sorts, and a slice of one queue would let what the first part of the pass had played come back — with two tracks re-indexed at different points, 'a' broadcast again inside one linear pass. The second lifecycle test fails that way and passes with this. --- crates/vuio-core/src/radio/engine.rs | 113 +++++++- .../vuio-core/tests/radio_lifecycle_tests.rs | 253 ++++++++++++++++++ 2 files changed, 355 insertions(+), 11 deletions(-) diff --git a/crates/vuio-core/src/radio/engine.rs b/crates/vuio-core/src/radio/engine.rs index e714411..dbe2389 100644 --- a/crates/vuio-core/src/radio/engine.rs +++ b/crates/vuio-core/src/radio/engine.rs @@ -25,7 +25,7 @@ //! starting it again. use crate::database::{ - BroadcastMode, DatabaseManager, DatabaseReadSession, MediaFileQuery, MediaFileView, + BroadcastMode, DatabaseManager, DatabaseReadSession, MediaFile, MediaFileQuery, MediaFileView, RadioStation, }; use crate::radio::frames::{Codec, Frame, TrackReader}; @@ -399,6 +399,32 @@ fn resume_after(tracks: &mut [Track], cursor: Option<&str>) { } } +/// What remains of a pass when its queue is read again part way through. +/// +/// `fresh` is the queue as rebuilt, and `attempted` everything the pass has +/// tried so far, in order, across re-reads. The pass carries on after the +/// latest attempted track the new queue still holds, and leaves out +/// everything already attempted: what is left is the tracks it had not +/// reached, plus any indexed again under a new id. +fn rest_of_pass(mut fresh: Vec, attempted: &[i64]) -> Vec { + let tried: std::collections::HashMap = attempted + .iter() + .enumerate() + .map(|(order, &id)| (id, order)) + .collect(); + let resume_at = fresh + .iter() + .enumerate() + .filter_map(|(position, id)| tried.get(id).map(|&order| (order, position))) + .max() + .map(|(_, position)| position + 1); + if let Some(resume_at) = resume_at { + fresh.rotate_left(resume_at); + } + fresh.retain(|id| !tried.contains_key(id)); + fresh +} + /// Whether `path` sits inside `folder`. Both are compared case-insensitively /// with separators normalised, because a folder arrives as an operator typed it. fn is_within(path: &str, folder: &str) -> bool { @@ -495,16 +521,55 @@ impl Playout { break; } - let queue = std::mem::take(&mut self.tracks); + let mut queue = std::mem::take(&mut self.tracks); let quiet_so_far = self.station.silent_passes() > 0; // The clock advances at emission, including audio sent before a later // read fails. A track's final Result cannot tell us whether it was silent. let audio_before_pass = clock.audio; - for &track_id in &queue { + let mut next = 0; + // Every id this pass has dealt with, across queue re-reads. A + // re-read rebuilds from wherever the library now sorts, and a set + // taken from one queue alone would let something an earlier part + // of the pass had broadcast come back and be played again. + let mut attempted: Vec = Vec::new(); + // At most one re-read per run of missing tracks; see below. + let mut may_requeue = true; + while let Some(&track_id) = queue.get(next) { + next += 1; + attempted.push(track_id); if self.station.cancel.is_cancelled() { return; } - match self.play(track_id, &mut clock).await { + let outcome = match self.state.database.get_file_by_id(track_id).await { + Ok(Some(track)) => self.play(track, &mut clock).await, + // The queue holds ids, and a row that has gone may be back + // under a new one: a file deleted and indexed again, or + // saved by an editor that writes a copy and renames it over + // the original. A queue of paths played it regardless. Read + // the queue again and carry on from here, rather than lose + // the track for the rest of the pass — for a linear + // station, the rest of its broadcast. + Ok(None) if may_requeue => { + may_requeue = false; + match build_queue(&self.state, &self.row).await { + Ok(plan) => { + queue = rest_of_pass(plan.tracks, &attempted); + next = 0; + continue; + } + Err(error) => Err(error + .context(format!("track {track_id} is no longer in the library"))), + } + } + Ok(None) => Err(anyhow::anyhow!( + "track {track_id} is no longer in the library" + )), + Err(error) => Err(error), + }; + if outcome.is_ok() { + may_requeue = true; + } + match outcome { Ok(()) => {} // A track that has been moved or is not what its extension // claims should cost one track, not the station. Once a whole @@ -613,13 +678,7 @@ impl Playout { /// Play one track, in real time, to everyone listening. `clock` is the /// station's, not this track's — see [`PlayoutClock`]. - async fn play(&self, track_id: i64, clock: &mut PlayoutClock) -> Result<()> { - let track = self - .state - .database - .get_file_by_id(track_id) - .await? - .ok_or_else(|| anyhow::anyhow!("track {track_id} is no longer in the library"))?; + async fn play(&self, track: MediaFile, clock: &mut PlayoutClock) -> Result<()> { let reader = TrackReader::open(&track.path, self.station.codec).await?; // `send_replace` rather than `send`: what is playing is state the studio @@ -853,6 +912,38 @@ mod tests { assert!(empty.is_empty(), "an empty queue must not panic"); } + /// Track 2 went missing and came back as 9, sorting where it always did. + /// The pass picks up at 9 and plays nothing it has already tried. + #[test] + fn a_requeued_pass_carries_on_with_a_track_indexed_again() { + assert_eq!(rest_of_pass(vec![1, 9, 3, 4], &[1, 2]), [9, 3, 4]); + // Resumed mid-queue, the pass wraps round to what came before it. + assert_eq!(rest_of_pass(vec![1, 9, 3, 4], &[3, 4, 2]), [1, 9]); + // New tracks are part of what remains; ones already tried are not. + assert_eq!(rest_of_pass(vec![5, 1, 3, 7], &[1, 3, 2]), [7, 5]); + } + + /// With none of the tried tracks left there is nothing to carry on after, + /// and the whole new queue is what remains. + #[test] + fn a_requeued_pass_with_nothing_left_to_anchor_on_keeps_the_new_order() { + assert_eq!(rest_of_pass(vec![7, 8], &[1, 2]), [7, 8]); + assert_eq!(rest_of_pass(Vec::new(), &[1, 2]), Vec::::new()); + assert_eq!(rest_of_pass(vec![1, 2], &[1, 2]), Vec::::new()); + } + + /// A second re-read in one pass. The ids handed over are the whole pass's, + /// so what an earlier part of it broadcast does not come back, even where + /// the rebuilt queue puts it ahead of the resume point. + #[test] + fn a_second_requeued_pass_leaves_out_everything_the_pass_attempted() { + // Played 1, missed 2, rebuilt, played 3, missed 4: 1 sorts ahead of + // what the pass resumes from, and still must not return. + assert_eq!(rest_of_pass(vec![1, 9, 3, 4], &[1, 2, 3, 4]), [9]); + // Untried tracks ahead of the resume point survive, at the tail. + assert_eq!(rest_of_pass(vec![1, 8, 3, 4], &[1, 2, 3, 4]), [8]); + } + #[test] fn folder_matching_is_by_subtree() { assert!(is_within("/music/rock/a.mp3", "/music")); diff --git a/crates/vuio-core/tests/radio_lifecycle_tests.rs b/crates/vuio-core/tests/radio_lifecycle_tests.rs index c5d0a72..eaed5af 100644 --- a/crates/vuio-core/tests/radio_lifecycle_tests.rs +++ b/crates/vuio-core/tests/radio_lifecycle_tests.rs @@ -192,3 +192,256 @@ async fn a_station_whose_files_have_gone_waits_instead_of_spinning() { state.background_tasks.close(); state.background_tasks.wait().await; } + +/// `seconds` of MPEG-1 Layer III frames at 128 kbit/s and 44.1 kHz. The +/// station frames them without decoding, so zeros serve for the audio. +fn silent_mp3(seconds: f64) -> Vec { + const FRAME_LEN: usize = 417; + let frames = (seconds * 44_100.0 / 1_152.0).ceil() as usize; + let mut bytes = Vec::with_capacity(frames * FRAME_LEN); + for _ in 0..frames { + bytes.extend_from_slice(&[0xFF, 0xFB, 0x90, 0x00]); + bytes.resize(bytes.len() + FRAME_LEN - 4, 0); + } + bytes +} + +/// A track whose row is removed and indexed again comes back under a new id, +/// which the queue of ids being played does not hold. It must still be played +/// in the pass under way — for a linear station, the only pass there is. +/// +/// The first track lasts long enough to still be on the air when the second is +/// indexed again; the other two are short, so the broadcast ends in about a +/// second and a half. +#[tokio::test] +async fn a_track_indexed_again_mid_pass_is_still_played() { + let temp = tempfile::tempdir().expect("temp dir"); + let media = temp.path().join("media"); + std::fs::create_dir_all(&media).expect("media dir"); + let media = std::fs::canonicalize(&media).expect("canonical media dir"); + + let mut tracks = Vec::new(); + for (name, seconds) in [("a", 3.0), ("b", 0.5), ("c", 0.5)] { + let track = media.join(format!("{name}.mp3")); + std::fs::write(&track, silent_mp3(seconds)).expect("write track"); + tracks.push(track); + } + + let state = common::state_over(temp.path(), &media).await; + for track in &tracks { + state + .database + .store_media_file(&MediaFile::new(track.clone(), 1, "audio/mpeg".to_owned())) + .await + .expect("index track"); + } + + let row = state + .database + .create_radio_station(&RadioStationInput { + name: "linear".to_owned(), + genre: String::new(), + folders: vec![media.to_string_lossy().into_owned()], + mode: BroadcastMode::Linear, + }) + .await + .expect("create station"); + + // The queue is built by the time `start` returns, so it holds `b`'s old id. + let station = state.radio.start(&state, &row).await.expect("start"); + let mut playing = station.attach().now_playing; + + let old_id = state + .database + .get_file_by_path(&tracks[1]) + .await + .expect("look up b") + .expect("b is indexed") + .id; + assert!(state + .database + .remove_media_file(&tracks[1]) + .await + .expect("remove b")); + let new_id = state + .database + .store_media_file(&MediaFile::new( + tracks[1].clone(), + 1, + "audio/mpeg".to_owned(), + )) + .await + .expect("index b again"); + assert_ne!(old_id, Some(new_id), "b must come back under a new id"); + + let mut heard = vec![playing.borrow_and_update().path.clone()]; + let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(10); + while !station.is_off_air() { + assert!( + tokio::time::Instant::now() < deadline, + "the station never reached the end of its queue" + ); + let wait = std::time::Duration::from_millis(50); + if let Ok(Ok(())) = tokio::time::timeout(wait, playing.changed()).await { + heard.push(playing.borrow_and_update().path.clone()); + } + } + + let heard: Vec = heard.into_iter().flatten().collect(); + let expected: Vec = tracks + .iter() + .map(|track| track.to_string_lossy().into_owned()) + .collect(); + assert_eq!(heard, expected, "every track once, in order"); + + state.cancellation.cancel(); + state.background_tasks.close(); + state.background_tasks.wait().await; +} + +/// Two tracks indexed again in one pass, at different points, and a queue +/// re-read for each. A re-read rebuilds the queue from wherever the library +/// now sorts, so the ids the pass hands over must be every id it has dealt +/// with this pass, not the previous queue's slice: with only that slice, the +/// second rebuild lets a track the first part of the pass had played come +/// back and be broadcast a second time. +/// +/// The first track lasts long enough for both re-indexings to happen while it +/// and its successor play; the later tracks are short, so the broadcast ends +/// in about seven seconds. +#[tokio::test] +async fn two_tracks_indexed_again_mid_pass_play_once_each() { + let temp = tempfile::tempdir().expect("temp dir"); + let media = temp.path().join("media"); + std::fs::create_dir_all(&media).expect("media dir"); + let media = std::fs::canonicalize(&media).expect("canonical media dir"); + + let mut tracks = Vec::new(); + for (name, seconds) in [("a", 3.0), ("b", 3.0), ("c", 0.5), ("d", 0.5)] { + let track = media.join(format!("{name}.mp3")); + std::fs::write(&track, silent_mp3(seconds)).expect("write track"); + tracks.push(track); + } + + let state = common::state_over(temp.path(), &media).await; + for track in &tracks { + state + .database + .store_media_file(&MediaFile::new(track.clone(), 1, "audio/mpeg".to_owned())) + .await + .expect("index track"); + } + + let row = state + .database + .create_radio_station(&RadioStationInput { + name: "linear".to_owned(), + genre: String::new(), + folders: vec![media.to_string_lossy().into_owned()], + mode: BroadcastMode::Linear, + }) + .await + .expect("create station"); + + // The queue is built by the time `start` returns, so it holds the ids of + // `b` and `d` as first indexed. + let station = state.radio.start(&state, &row).await.expect("start"); + let mut playing = station.attach().now_playing; + + let old_b_id = state + .database + .get_file_by_path(&tracks[1]) + .await + .expect("look up b") + .expect("b is indexed") + .id; + let old_d_id = state + .database + .get_file_by_path(&tracks[3]) + .await + .expect("look up d") + .expect("d is indexed") + .id; + + // Retire `b`'s row and index the file again under a new id, while `a` — + // whose three seconds the queue is still walking through — plays. The + // re-read this forces finds `b`'s new id and holds `d`'s old id. + assert!(state + .database + .remove_media_file(&tracks[1]) + .await + .expect("remove b")); + let new_b_id = state + .database + .store_media_file(&MediaFile::new( + tracks[1].clone(), + 1, + "audio/mpeg".to_owned(), + )) + .await + .expect("index b again"); + assert_ne!(old_b_id, Some(new_b_id), "b must come back under a new id"); + + let mut b_slot_seen = false; + let mut d_reindexed = false; + let mut heard = vec![playing.borrow_and_update().path.clone()]; + let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(20); + while !station.is_off_air() { + assert!( + tokio::time::Instant::now() < deadline, + "the station never reached the end of its queue" + ); + let wait = std::time::Duration::from_millis(50); + let current = if let Ok(Ok(())) = tokio::time::timeout(wait, playing.changed()).await { + let current = playing.borrow_and_update().path.clone(); + heard.push(current.clone()); + current + } else { + continue; + }; + if !b_slot_seen && current == Some(tracks[1].to_string_lossy().into_owned()) { + b_slot_seen = true; + // The pass has ploughed through the re-read and is on `b`'s new id — + // i.e. it now holds `d`'s old id. Retire that row and index the file + // again too, so the second re-read is forced as well. + assert!(state + .database + .remove_media_file(&tracks[3]) + .await + .expect("remove d")); + let new_d_id = state + .database + .store_media_file(&MediaFile::new( + tracks[3].clone(), + 1, + "audio/mpeg".to_owned(), + )) + .await + .expect("index d again"); + assert_ne!(old_d_id, Some(new_d_id), "d must come back under a new id"); + d_reindexed = true; + } + } + assert!(d_reindexed, "d's second re-indexing must have happened"); + let d_path = tracks[3].to_string_lossy().into_owned(); + assert!( + heard + .iter() + .any(|path| path.as_deref() == Some(d_path.as_str())), + "d must still be played after its re-indexing" + ); + + let heard: Vec = heard.into_iter().flatten().collect(); + let expected: Vec = tracks + .iter() + .map(|track| track.to_string_lossy().into_owned()) + .collect(); + assert_eq!( + heard, expected, + "every track once, in order, across re-reads" + ); + + state.cancellation.cancel(); + state.background_tasks.close(); + state.background_tasks.wait().await; +} From 9e83902f08217acbe17110ff2b4b05903d71fc0b Mon Sep 17 00:00:00 2001 From: vyrti Date: Thu, 24 Sep 2026 01:00:57 +0300 Subject: [PATCH 12/12] Measure the single-track fragment builder in the memory audit The audit's fragment row came from the multi-track builder, which only films with re-encoded audio go through; every HLS segment uses the single-track one, which kept one extra payload-sized copy rather than two. The RSS probe now measures either shape (VUIO_FRAGMENT_SHAPE=single): for 64 MiB of payload, 201.8 to 137.6 MiB single-track (32%) and 265.8 to 137.8 MiB multi-track (48%), all with identical output. The audit also describes the probe and segment-slot changes, and notes that every figure is a macOS peak: glibc keeps freed memory in arenas, and the Docker image is built on musl, where release_free_memory does nothing. --- .../vuio-core/src/media/remux/fmp4_writer.rs | 15 ++++++- docs/memory-audit.md | 42 ++++++++++++++----- 2 files changed, 45 insertions(+), 12 deletions(-) diff --git a/crates/vuio-core/src/media/remux/fmp4_writer.rs b/crates/vuio-core/src/media/remux/fmp4_writer.rs index 64367be..652746b 100644 --- a/crates/vuio-core/src/media/remux/fmp4_writer.rs +++ b/crates/vuio-core/src/media/remux/fmp4_writer.rs @@ -1091,6 +1091,8 @@ mod tests { /// Run the test binary directly under /usr/bin/time -l, in separate /// processes with and without VUIO_LEGACY_FRAGMENT=1, to compare peak RSS. + /// VUIO_FRAGMENT_SHAPE=single measures the single-track builder HLS + /// segments use instead of the multi-track one. #[test] #[ignore = "isolated 64 MiB allocation probe"] fn fragment_rss_probe() { @@ -1103,6 +1105,7 @@ mod tests { is_keyframe: true, data: vec![0x5a; 64 * 1024 * 1024], }]; + let single = std::env::var("VUIO_FRAGMENT_SHAPE").as_deref() == Ok("single"); let segment = if std::env::var_os("VUIO_LEGACY_FRAGMENT").is_some() { let samples = Fmp4Writer::samples_for(&track, &packets); let run = TrackRun { @@ -1117,16 +1120,26 @@ mod tests { samples: &samples, }; let moof = Fmp4Writer::build_moof_multi(1, &[run], &[size as u32 + 8]); - // The former multi-track builder kept all three copies live. let mut body = Vec::with_capacity(8 + packets[0].data.len()); body.extend_from_slice(b"mdat"); body.extend_from_slice(&packets[0].data); let mdat = Fmp4Writer::wrap_box(&body); + // The former single-track builder dropped the unwrapped body before + // the final copy. The multi-track one shadowed it, so all three + // copies were live at once. + let body = if single { + drop(body); + None + } else { + Some(body) + }; let mut segment = Vec::with_capacity(moof.len() + mdat.len()); segment.extend_from_slice(&moof); segment.extend_from_slice(&mdat); std::hint::black_box((&body, &mdat)); segment + } else if single { + Fmp4Writer::build_segment(1, &track, 0, &packets) } else { Fmp4Writer::build_multi_track_segment(1, &[(&track, &packets)], &[0]) }; diff --git a/docs/memory-audit.md b/docs/memory-audit.md index 1e2fb19..bd0b8f4 100644 --- a/docs/memory-audit.md +++ b/docs/memory-audit.md @@ -10,24 +10,30 @@ the probes; they are not separate builds of the old revision. | Workload | Previous pattern | Current implementation | Reduction | | --- | ---: | ---: | ---: | -| Build an fMP4 fragment with 64 MiB of payload | 278,380,544 B (265.5 MiB) | 144,293,888 B (137.6 MiB) | 48% | +| Build a single-track fMP4 segment (every HLS segment) with 64 MiB of payload | 211,550,208 B (201.8 MiB) | 144,310,272 B (137.6 MiB) | 32% | +| Build a multi-track fMP4 fragment (a film with re-encoded audio for a television) with 64 MiB of payload | 278,675,456 B (265.8 MiB) | 144,523,264 B (137.8 MiB) | 48% | | Read a two-hour AAC audiobook for radio | 164,003,840 B (156.4 MiB) | 14,548,992 B (13.9 MiB) | 91% | -Both fragment paths produced 67,108,976 bytes, with hash +All four fragment paths produced 67,108,976 bytes, with hash `9318397001415464912`. Both radio paths produced 336,963 frames and 117,404,618 bytes, with hash `15861541014108818885`. Hashes use Rust's `DefaultHasher` and are useful for comparison within the same build, not as a stable file format. The radio probe drains frames without real-time pacing; the production channel also bounds read-ahead when playback is slower. -The fragment builder now writes `mdat` directly into its final output instead -of keeping two additional payload-sized copies. The radio reader now uses +Both fragment builders now write `mdat` directly into their final output. The +single-track builder, which HLS passthrough and HLS audio go through, used to +keep one additional payload-sized copy; the multi-track builder kept two, which +is the larger saving but the less common path. The radio reader now uses backpressure with a 32-frame queue instead of retaining the entire audiobook. ## Other fixes and bounds - Radio queues retain track IDs rather than paths, titles and artists; only the - current track's metadata is loaded for playout. + current track's metadata is loaded for playout. A track whose row disappears + mid-pass — deleted and indexed again, which gives it a new ID — makes the + station read its queue again and carry on from where it was, so the track is + not lost for the rest of the pass (for a linear station, the whole broadcast). - Elementary-stream frame indexes share immutable storage across listeners. Their cache has a 12 MiB byte budget as well as a four-entry limit. Oversized indexes can still be used by an active stream, but are not cached. @@ -36,10 +42,14 @@ backpressure with a 32-frame queue instead of retaining the entire audiobook. - Video/TS timestamp estimates stop accumulating after initial placement. fMP4 Dolby priming also stops reading ahead after 16 MiB or 512 packets (the byte threshold can be exceeded by the final packet). -- All HLS segment builds, including passthrough video, share four slots. Busy - requests receive 503 with `Retry-After: 1`. Metadata probes share two slots. - Blocking workers retain their permits after caller cancellation; elementary - transcode planning likewise keeps its existing transcode slot. +- All HLS segment builds, including passthrough video, share four slots. A + request waits up to five seconds for one before it receives 503 with + `Retry-After: 1`: a seek's abandoned builds keep their slots until they + finish, and refusing at once turned scrubbing into a run of 503s. Metadata + probes share one slot per core, at least two and at most eight, across every + scan and watch event; two slots halved the probe rate on an eight-core + machine. Blocking workers retain their permits after caller cancellation; + elementary transcode planning likewise keeps its existing transcode slot. - Metadata-fetch jobs page pending IDs in groups of 256, using an initial ID high-water mark; misses are not retried forever and later insertions do not extend the job. @@ -62,8 +72,8 @@ jobs, playlist duplicates across batch boundaries, cache replacements, shared frame storage, radio frame order/cancellation, metadata-probe cancellation, fragment payload offsets, and long-running timestamp state. -Verification: 838 core unit/integration tests, 75 casting unit tests and four -AAC codec tests passed; nine core tests were ignored (including the two RSS +Verification: 845 core unit/integration tests, 75 casting unit tests and four +AAC codec tests passed; ten core tests were ignored (including the two RSS probes run separately). Strict library Clippy and no-default-feature checks for transcode-only and casting-only builds passed. Tests used all server features except `web-ui`, whose generated assets are absent in this worktree. All-target @@ -86,6 +96,9 @@ in a fresh process: ```sh /usr/bin/time -l "$audit_test_binary" fragment_rss_probe --ignored --nocapture VUIO_LEGACY_FRAGMENT=1 /usr/bin/time -l "$audit_test_binary" fragment_rss_probe --ignored --nocapture +VUIO_FRAGMENT_SHAPE=single /usr/bin/time -l "$audit_test_binary" fragment_rss_probe --ignored --nocapture +VUIO_FRAGMENT_SHAPE=single VUIO_LEGACY_FRAGMENT=1 \ + /usr/bin/time -l "$audit_test_binary" fragment_rss_probe --ignored --nocapture audit_media_dir=$(mktemp -d /tmp/vuio-memory-probe.XXXXXX) ffmpeg -hide_banner -loglevel error -f lavfi \ @@ -118,3 +131,10 @@ container index, or an unusually large video packet still needs separate parser-level investigation. Measure representative whole-server workloads before translating the isolated reductions above into an RSS expectation for a deployment. + +Every figure here is a peak measured on macOS. How much of a peak stays +resident afterwards depends on the allocator, and the deployments use others: +glibc keeps freed memory in per-thread arenas for reuse, and +`release_free_memory` (macOS and glibc only) hands it back after a large scan, +not after streaming. The Docker image is built on Alpine; musl has no such +call, so there `release_free_memory` does nothing.