From bb6b435ae4856661a02480f75fcb9623fa4ea73f Mon Sep 17 00:00:00 2001 From: zarzet <42882290+zarzet@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:00:16 +0700 Subject: [PATCH] perf(library): read folder images and CUE sheets once A scan read, hashed and compared the folder image (cover.jpg and the like) once per song that used it, and on a large image that did not fit the thumbnail cache it decoded and resized the image again for every song under the global thumbnail mutex. Each folder image of a scan now keeps the artwork it resolved to (thumbnail, type and stored-file record), so the songs of a folder read and resize it once. The memo lives in the scan's folder image, so the next scan reads a changed image again; a cancelled read is not kept. The reader opens the image with open_native_read instead of validating the path a second time. Every incremental scan also parsed every CUE sheet to learn which audio it owns. A sheet the scan skips as unchanged now keeps the audio reference read at the same size and modification time in the scan state; the reference is still resolved against the files on disk each scan, and files the walk just found need no probe. Changed sheets and full scans parse as before. CUE thumbnails now use the scan's sync batch like audio thumbnails, so on Apple platforms they are flushed with the scan's single folder sync instead of a full sync per file. --- .../crates/extensions/src/backend/cover.rs | 195 ++++++++--- .../crates/extensions/src/backend/library.rs | 25 +- .../extensions/src/backend/library/scan.rs | 323 +++++++++++++++++- 3 files changed, 478 insertions(+), 65 deletions(-) diff --git a/rust_backend/crates/extensions/src/backend/cover.rs b/rust_backend/crates/extensions/src/backend/cover.rs index 16d0b69b5..ae2945b33 100644 --- a/rust_backend/crates/extensions/src/backend/cover.rs +++ b/rust_backend/crates/extensions/src/backend/cover.rs @@ -15,7 +15,7 @@ use std::collections::BTreeMap; use std::io::{Read, Write}; use std::panic::{AssertUnwindSafe, catch_unwind}; use std::path::Path; -use std::sync::{Arc, Condvar, Mutex}; +use std::sync::{Arc, Condvar, Mutex, PoisonError}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; type Check<'a> = dyn Fn() -> Result<(), String> + 'a; @@ -51,6 +51,66 @@ pub fn library_cover_is_current(modified: SystemTime, regenerate: Option= marker) } +/// Library artwork ready to store: the thumbnail when one could be made, and +/// the record of where its bytes are stored. +#[derive(Clone)] +pub(super) struct LibraryArtwork { + data: Arc<[u8]>, + mime: String, + stored: Option>>>, +} + +impl LibraryArtwork { + /// Library caching may retain unsupported image bytes when the resize + /// fails. + fn new(cover: CoverArt, check: &Check<'_>) -> Self { + let Ok(thumbnail) = mornye_core::cover::library_thumbnail_entry(&cover.data, check) else { + return Self { + data: cover.data.into(), + mime: cover.mime, + stored: None, + }; + }; + let mime = if thumbnail.data.starts_with(b"\x89PNG") { + "image/png".into() + } else if thumbnail.data.starts_with(b"\xff\xd8") { + "image/jpeg".into() + } else { + cover.mime + }; + Self { + data: thumbnail.data, + mime, + stored: Some(thumbnail.stored), + } + } +} + +/// The artwork of one folder image for one scan, read and resized once for +/// every song that uses it. A later scan starts again, so it sees a changed +/// image. +#[derive(Default)] +pub(super) struct FolderArtwork(Mutex>>); + +impl FolderArtwork { + fn get_or_read( + &self, + check: &Check<'_>, + read: impl FnOnce() -> Result, + ) -> Result { + let mut artwork = self.0.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(result) = artwork.as_ref() { + return result.clone(); + } + let result = read(); + // A cancelled read says nothing about the image. + if check().is_ok() { + *artwork = Some(result.clone()); + } + result + } +} + struct Entry { data: Arc<[u8]>, expires: Instant, @@ -283,6 +343,27 @@ impl Backend { cache_directory: &str, explicit_key: &str, check: &Check<'_>, + ) -> Result { + self.save_cover_to_cache_batched( + audio_path, + hint, + cache_directory, + explicit_key, + None, + check, + ) + } + + /// [`Self::save_cover_to_cache_with_hint_and_key`]; with `batch`, the scan + /// flushes the thumbnail folder once at its end instead of per file. + pub(super) fn save_cover_to_cache_batched( + &self, + audio_path: &str, + hint: &str, + cache_directory: &str, + explicit_key: &str, + batch: Option<&SyncBatch>, + check: &Check<'_>, ) -> Result { self.cache_cover( audio_path, @@ -290,8 +371,10 @@ impl Backend { cache_directory, explicit_key, None, - read_cover, - None, + |input, format, check| { + read_cover(input, format, check).map(|cover| LibraryArtwork::new(cover, check)) + }, + batch, cfg!(target_os = "android"), check, ) @@ -320,7 +403,9 @@ impl Backend { cache_directory, explicit_key, format, - read, + |input, format, check| { + read(input, format, check).map(|cover| LibraryArtwork::new(cover, check)) + }, batch, cfg!(target_os = "android"), check, @@ -330,12 +415,13 @@ impl Backend { /// Caches the folder image at `image_path` (cover.jpg and the like) as /// the Library thumbnail of a song without embedded artwork. `key` must /// name this version of the image, so a replaced image gets a new - /// thumbnail. + /// thumbnail. Songs that share `artwork` read and resize the image once. pub(super) fn save_folder_cover_to_cache_for_scan( &self, image_path: &str, cache_directory: &str, key: &str, + artwork: &FolderArtwork, batch: Option<&SyncBatch>, check: &Check<'_>, ) -> Result { @@ -346,19 +432,23 @@ impl Backend { key, Some("image"), |input, _, check| { - input.native_display()?; - let mut file = input - .open(OpenOptions::new().read(true)) - .map_err(|error| error.to_string())?; - let data = mornye_core::cover::read_folder_image(&mut file, check)?; - let mime = if data.starts_with(b"\x89PNG") { - "image/png" - } else { - "image/jpeg" - }; - Ok(CoverArt { - data, - mime: mime.into(), + artwork.get_or_read(check, || { + let mut file = input + .open_native_read() + .map_err(|error| error.to_string())?; + let data = mornye_core::cover::read_folder_image(&mut file, check)?; + let mime = if data.starts_with(b"\x89PNG") { + "image/png" + } else { + "image/jpeg" + }; + Ok(LibraryArtwork::new( + CoverArt { + data, + mime: mime.into(), + }, + check, + )) }) }, batch, @@ -375,7 +465,7 @@ impl Backend { cache_directory: &str, explicit_key: &str, format_override: Option<&str>, - read: impl FnOnce(&crate::files::FilePath, &str, &Check<'_>) -> Result, + read: impl FnOnce(&crate::files::FilePath, &str, &Check<'_>) -> Result, batch: Option<&SyncBatch>, content_addressed: bool, check: &Check<'_>, @@ -455,7 +545,7 @@ impl Backend { } )); } - let mut cover = if let Some((_, cached)) = cached { + let cover = if let Some((_, cached)) = cached { let mut data = Vec::new(); cached .open(OpenOptions::new().read(true)) @@ -467,32 +557,24 @@ impl Backend { check()?; return Ok(cached.display()); } - CoverArt { - data, - mime: if cached.display().ends_with(".png") { - "image/png" - } else { - "image/jpeg" - } - .into(), - } + let mime = if cached.display().ends_with(".png") { + "image/png" + } else { + "image/jpeg" + }; + LibraryArtwork::new( + CoverArt { + data, + mime: mime.into(), + }, + &check, + ) } else { read(&input, &format, &check)? }; - let mut stored = None; - if let Ok(thumbnail) = mornye_core::cover::library_thumbnail_entry(&cover.data, &check) { - let resized = thumbnail.data; - cover.mime = if resized.starts_with(b"\x89PNG") { - "image/png" - } else if resized.starts_with(b"\xff\xd8") { - "image/jpeg" - } else { - &cover.mime - } - .into(); - cover.data = resized.to_vec(); - stored = (LINK_THUMBNAILS && !content_addressed).then_some(thumbnail.stored); - } + let stored = cover + .stored + .filter(|_| LINK_THUMBNAILS && !content_addressed); // Library caching may retain unsupported image bytes, but must never // swallow cancellation while attempting the optional resize. check()?; @@ -526,7 +608,7 @@ impl Backend { .read_to_end(&mut existing) .map_err(|error| error.to_string())?; check()?; - if existing != cover.data { + if *existing != *cover.data { return Err("content-addressed library artwork differs from its name".into()); } return Ok(output.display()); @@ -828,6 +910,14 @@ pub(super) mod tests { .unwrap() } + fn read_artwork( + input: &crate::files::FilePath, + format: &str, + check: &Check<'_>, + ) -> Result { + read_cover(input, format, check).map(|cover| LibraryArtwork::new(cover, check)) + } + fn id3_audio(jpeg: &[u8]) -> Vec { let mut picture = b"\0image/jpeg\0\x03\0\0".to_vec(); picture.extend(jpeg); @@ -859,7 +949,7 @@ pub(super) mod tests { cache.to_str().unwrap(), &format!("song-{index}"), None, - read_cover, + read_artwork, None, true, &|| Ok(()), @@ -912,11 +1002,14 @@ pub(super) mod tests { cache.to_str().unwrap(), "legacy", None, - |_, _, _| { - Ok(CoverArt { - data: pictures[1].clone(), - mime: "image/jpeg".into(), - }) + |_, _, check| { + Ok(LibraryArtwork::new( + CoverArt { + data: pictures[1].clone(), + mime: "image/jpeg".into(), + }, + check, + )) }, None, true, @@ -936,7 +1029,7 @@ pub(super) mod tests { cache.to_str().unwrap(), "fresh", None, - read_cover, + read_artwork, None, true, &|| Ok(()), diff --git a/rust_backend/crates/extensions/src/backend/library.rs b/rust_backend/crates/extensions/src/backend/library.rs index 26b799b6a..877354575 100644 --- a/rust_backend/crates/extensions/src/backend/library.rs +++ b/rust_backend/crates/extensions/src/backend/library.rs @@ -1,6 +1,8 @@ //! Backend operations for local library files: audio metadata reads and CUE sheet parsing and scanning. use super::Backend; +use super::cover::FolderArtwork; +use crate::files::SyncBatch; use cap_std::fs::OpenOptions; use chrono::{SecondsFormat, Utc}; use mornye_core::cue::{self, CueSheet}; @@ -10,6 +12,7 @@ use mornye_core::tags::{ }; use serde_json::{Value, json}; use std::cell::RefCell; +use std::collections::BTreeSet; use std::path::Path; use std::time::UNIX_EPOCH; @@ -22,6 +25,7 @@ struct FolderImage { path: String, size: u64, modified: i64, + artwork: FolderArtwork, } impl FolderImage { @@ -93,7 +97,7 @@ impl Backend { cache_key: &str, scan_time: &str, mod_time: i64, - covers: Option<&crate::files::SyncBatch>, + covers: Option<&SyncBatch>, folder_image: Option<&FolderImage>, check: &dyn Fn() -> Result<(), String>, ) -> Result { @@ -155,6 +159,7 @@ impl Backend { &image.path, &directory, &image.cache_key(song), + &image.artwork, covers, check, ) @@ -202,11 +207,14 @@ impl Backend { cue::parse(&mut file, &check) } + /// `walked` holds files a scan's walk just found and validated; those + /// need no probe. fn resolve_cue_audio( &self, path: &str, name: &str, audio_directory: &str, + walked: Option<&BTreeSet<&str>>, check: &dyn Fn() -> Result<(), String>, ) -> Result { let base = Path::new(path).parent().unwrap_or(Path::new(".")); @@ -220,6 +228,9 @@ impl Backend { check()?; let candidate = crate::files::clean(&directory.join(name.trim_start_matches('/'))); let candidate = candidate.to_string_lossy(); + if walked.is_some_and(|walked| walked.contains(candidate.as_ref())) { + return Ok(Some(candidate.into_owned())); + } let input = files.resolve_legacy(&candidate)?; input.native_display()?; Ok(input.metadata().is_ok().then(|| candidate.into_owned())) @@ -287,7 +298,7 @@ impl Backend { .parse_cue_file(path, &check) .map_err(|error| format!("failed to parse cue file: {error}"))?; let audio = self - .resolve_cue_audio(path, &sheet.file_name, audio_directory, &check) + .resolve_cue_audio(path, &sheet.file_name, audio_directory, None, &check) .map_err(|error| { error.replace( "audio file not found for cue:", @@ -339,7 +350,8 @@ impl Backend { }) }; let sheet = self.parse_cue_file(path, &check)?; - let audio = self.resolve_cue_audio(path, &sheet.file_name, audio_directory, &check)?; + let audio = + self.resolve_cue_audio(path, &sheet.file_name, audio_directory, None, &check)?; self.scan_cue_sheet( path, &sheet, @@ -349,6 +361,7 @@ impl Backend { cache_key, scan_time, None, + None, &check, ) } @@ -399,6 +412,7 @@ impl Backend { mod_time: i64, cache_key: &str, scan_time: &str, + covers: Option<&SyncBatch>, folder_image: Option<&FolderImage>, check: &dyn Fn() -> Result<(), String>, ) -> Result { @@ -435,7 +449,7 @@ impl Backend { let cover = if directory.is_empty() { String::new() } else { - self.save_cover_to_cache_with_hint_and_key(audio, "", &directory, cache_key, check) + self.save_cover_to_cache_batched(audio, "", &directory, cache_key, covers, check) .ok() .filter(|cover| !cover.is_empty()) .or_else(|| { @@ -449,7 +463,8 @@ impl Backend { &image.path, &directory, &image.cache_key(song), - None, + &image.artwork, + covers, check, ) .ok() diff --git a/rust_backend/crates/extensions/src/backend/library/scan.rs b/rust_backend/crates/extensions/src/backend/library/scan.rs index 5ec736a1f..3a9705f60 100644 --- a/rust_backend/crates/extensions/src/backend/library/scan.rs +++ b/rust_backend/crates/extensions/src/backend/library/scan.rs @@ -30,6 +30,16 @@ pub(in crate::backend) struct ScanState { // before the native scan starts still holds it at its first checkpoint. paused: Mutex, resumed: Condvar, + /// The CUE sheets each folder's last scan found, so an unchanged sheet is + /// not read again. + cue_sheets: Mutex>>, +} + +/// The audio reference of a CUE sheet with the size and time it was read at. +struct KnownCue { + size: u64, + modified: i64, + file_name: String, } #[derive(Default)] @@ -464,6 +474,7 @@ impl Backend { } } let mut skipped = 0; + let mut unchanged = BTreeSet::new(); let tasks: Vec<_> = current .iter() .filter(|file| { @@ -477,6 +488,7 @@ impl Backend { }); if old == Some(file.modified) { skipped += 1; + unchanged.insert(file.path.as_str()); false } else { true @@ -484,21 +496,61 @@ impl Backend { }) .collect(); let time = scan_time(); + // Thumbnails get one folder flush when the scan finishes, also when + // it fails. + let covers = SyncBatch::default(); let mut referenced = BTreeSet::new(); let mut parsed = BTreeMap::new(); + let mut known = self + .library_scan + .cue_sheets + .lock() + .expect("library scan CUE lock") + .remove(folder) + .unwrap_or_default(); + let mut sheets = BTreeMap::new(); // An unchanged CUE still owns its backing audio. Inspect all current // sheets so incremental scans never re-add that audio as a full album. + // A sheet the scan skips keeps the reference read at its size and time. for file in ¤t { check()?; - if library_extension(&file.path, "") == "cue" - && let Ok(sheet) = self.parse_cue_file(&file.path, &check) - && !sheet.file_name.is_empty() - && let Ok(audio) = self.resolve_cue_audio(&file.path, &sheet.file_name, "", &check) + if library_extension(&file.path, "") != "cue" { + continue; + } + let reused = known.remove(&file.path).filter(|cue| { + unchanged.contains(file.path.as_str()) + && (cue.size, cue.modified) == (file.size, file.modified) + }); + let (file_name, sheet) = match reused { + Some(cue) => (cue.file_name, None), + None => match self.parse_cue_file(&file.path, &check) { + Ok(sheet) => (sheet.file_name.clone(), Some(sheet)), + Err(_) => continue, + }, + }; + sheets.insert( + file.path.clone(), + KnownCue { + size: file.size, + modified: file.modified, + file_name: file_name.clone(), + }, + ); + if !file_name.is_empty() + && let Ok(audio) = + self.resolve_cue_audio(&file.path, &file_name, "", Some(&paths), &check) { referenced.insert(audio.clone()); - parsed.insert(file.path.as_str(), (sheet, audio)); + if let Some(sheet) = sheet { + parsed.insert(file.path.as_str(), (sheet, audio)); + } } } + self.library_scan + .cue_sheets + .lock() + .expect("library scan CUE lock") + .insert(folder.to_owned(), sheets); check()?; let mut results: BTreeMap> = BTreeMap::new(); let mut audio = Vec::new(); @@ -515,6 +567,7 @@ impl Backend { file.modified, "", &time, + Some(&covers), file.folder_image.as_deref(), &check, ), @@ -561,9 +614,6 @@ impl Backend { }; let next = AtomicUsize::new(0); let stop = AtomicBool::new(false); - // Thumbnails get one folder flush when the workers finish, also when - // the scan fails. - let covers = SyncBatch::default(); thread::scope(|scope| -> Result<(), String> { let (sender, receiver) = mpsc::sync_channel(workers * 16); for _ in 0..workers { @@ -675,6 +725,7 @@ fn folder_image( path, size: metadata.len(), modified: modified_time(&metadata), + artwork: Default::default(), })) } @@ -1056,13 +1107,21 @@ mod tests { /// Scans `library` in full and maps each song's path below it to the /// bytes of its cover, if any. fn scanned_covers(root: &Path, library: &Path) -> BTreeMap>> { + scanned_covers_with(root, library, &|| Ok(())) + } + + fn scanned_covers_with( + root: &Path, + library: &Path, + check: Check<'_>, + ) -> BTreeMap>> { let backend = backend(root, library); let covers = root.join("data/library_covers"); backend .set_library_cover_cache_directory(&covers.to_string_lossy()) .unwrap(); let result = backend - .scan_library_folder_incremental(&library.to_string_lossy(), "{}", &|| Ok(())) + .scan_library_folder_incremental(&library.to_string_lossy(), "{}", check) .unwrap(); result["scanned"] .as_array() @@ -1242,6 +1301,252 @@ mod tests { ); } + /// A PNG beyond the 8 MiB thumbnail cache budget, `extra` bytes apart in + /// size. Trailing bytes leave the decoded pixels unchanged. + fn large_png(red: u8, extra: usize) -> Vec { + let mut png = std::io::Cursor::new(Vec::new()); + image::RgbImage::from_pixel(1000, 1000, image::Rgb([red, 90, 150])) + .write_to(&mut png, image::ImageFormat::Png) + .unwrap(); + let mut png = png.into_inner(); + png.resize((8 << 20) + 1 + extra, 0); + png + } + + fn written_thumbnails(covers: &Path) -> usize { + fs::read_dir(covers).map_or(0, |entries| { + entries + .filter(|entry| { + !entry + .as_ref() + .unwrap() + .file_name() + .to_string_lossy() + .ends_with(".partial") + }) + .count() + }) + } + + #[test] + fn a_scan_reads_a_folder_image_once_and_the_next_scan_reads_it_again() { + let root = tempfile::tempdir().unwrap(); + let library = fs::canonicalize(root.path()).unwrap().join("library"); + let album = library.join("Album"); + fs::create_dir_all(&album).unwrap(); + for track in 0..3 { + fs::write( + album.join(format!("{track:02}.flac")), + flac_without_picture(), + ) + .unwrap(); + } + let image = album.join("cover.png"); + let (old, new) = (large_png(10, 0), large_png(20, 1)); + fs::write(&image, &old).unwrap(); + let covers = root.path().join("data/library_covers"); + let replaced = AtomicBool::new(false); + + // Once the first song has its thumbnail, the image changes on disk. + // Every song of this scan still gets the image it started with. + let scanned = scanned_covers_with(root.path(), &library, &|| { + if !replaced.load(Ordering::Acquire) && written_thumbnails(&covers) > 0 { + fs::write(&image, &new).unwrap(); + replaced.store(true, Ordering::Release); + } + Ok(()) + }); + + assert!(replaced.load(Ordering::Acquire)); + assert_eq!(scanned.len(), 3); + assert!( + scanned + .values() + .all(|cover| *cover == Some(thumbnail(&old))) + ); + let scanned = scanned_covers(root.path(), &library); + assert!( + scanned + .values() + .all(|cover| *cover == Some(thumbnail(&new))) + ); + } + + #[test] + fn songs_of_a_folder_share_one_thumbnail_of_a_large_folder_image() { + use std::os::unix::fs::MetadataExt; + let root = tempfile::tempdir().unwrap(); + let library = fs::canonicalize(root.path()).unwrap().join("library"); + let album = library.join("Album"); + fs::create_dir_all(&album).unwrap(); + // Enough songs for several scan workers. + for track in 0..20 { + fs::write( + album.join(format!("{track:02}.flac")), + flac_without_picture(), + ) + .unwrap(); + } + let image = large_png(30, 0); + fs::write(album.join("folder.png"), &image).unwrap(); + + let scanned = scanned_covers(root.path(), &library); + + assert_eq!(scanned.len(), 20); + assert!( + scanned + .values() + .all(|cover| *cover == Some(thumbnail(&image))) + ); + let covers = root.path().join("data/library_covers"); + let names = fs::read_dir(&covers).unwrap().count(); + let files: BTreeSet<_> = fs::read_dir(&covers) + .unwrap() + .map(|entry| entry.unwrap().metadata().unwrap().ino()) + .collect(); + assert_eq!(names, 20); + if cfg!(any(target_vendor = "apple", target_os = "linux")) { + assert_eq!(files.len(), 1); + } + } + + /// Writes `album.cue` naming `audio` beside `a.flac` and `b.flac` and + /// returns its path. + fn cue_beside_two_songs(library: &Path, audio: &str) -> PathBuf { + let folder = library.join("Cue"); + fs::create_dir_all(&folder).unwrap(); + for song in ["a.flac", "b.flac"] { + fs::write(folder.join(song), flac_without_picture()).unwrap(); + } + let cue = folder.join("album.cue"); + fs::write( + &cue, + format!("FILE \"{audio}\" WAVE\nTRACK 01 AUDIO\nINDEX 01 00:00:00\n"), + ) + .unwrap(); + cue + } + + fn modified_millis(path: &Path) -> i64 { + fs::metadata(path) + .unwrap() + .modified() + .unwrap() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis() as i64 + } + + /// Scans with a snapshot that holds the CUE track at `cue_time` and lists + /// the scanned file names. + fn scanned_beside_cue( + backend: &Backend, + library: &Path, + cue: &Path, + cue_time: i64, + ) -> Vec { + let snapshot = json!({format!("{}#track01", cue.to_string_lossy()): cue_time}); + let result = backend + .scan_library_folder_incremental( + &library.to_string_lossy(), + &snapshot.to_string(), + &|| Ok(()), + ) + .unwrap(); + result["scanned"] + .as_array() + .unwrap() + .iter() + .map(|row| { + Path::new(row["filePath"].as_str().unwrap()) + .file_name() + .unwrap() + .to_string_lossy() + .into_owned() + }) + .collect() + } + + #[test] + fn an_unchanged_cue_sheet_is_not_read_again() { + let root = tempfile::tempdir().unwrap(); + let library = fs::canonicalize(root.path()).unwrap().join("library"); + let cue = cue_beside_two_songs(&library, "a.flac"); + let backend = backend(root.path(), &library); + let time = modified_millis(&cue); + assert_eq!( + scanned_beside_cue(&backend, &library, &cue, time), + ["b.flac"] + ); + + // Same size and time: the scan keeps the reference it read before, + // as it keeps an unchanged song. + let original = fs::metadata(&cue).unwrap().modified().unwrap(); + fs::write( + &cue, + "FILE \"b.flac\" WAVE\nTRACK 01 AUDIO\nINDEX 01 00:00:00\n", + ) + .unwrap(); + let file = fs::File::options().write(true).open(&cue).unwrap(); + file.set_modified(original).unwrap(); + assert_eq!( + scanned_beside_cue(&backend, &library, &cue, time), + ["b.flac"] + ); + + // A new time reads the sheet again. + file.set_modified(original + Duration::from_secs(10)) + .unwrap(); + let time = modified_millis(&cue); + assert_eq!( + scanned_beside_cue(&backend, &library, &cue, time), + ["a.flac"] + ); + } + + #[test] + fn an_unchanged_cue_sheet_follows_its_audio_file() { + let root = tempfile::tempdir().unwrap(); + let library = fs::canonicalize(root.path()).unwrap().join("library"); + let cue = cue_beside_two_songs(&library, "album.flac"); + let backend = backend(root.path(), &library); + let time = modified_millis(&cue); + // Without album.flac the sheet falls back to another extension. + fs::write(library.join("Cue/album.mp3"), b"not audio").unwrap(); + assert_eq!( + scanned_beside_cue(&backend, &library, &cue, time), + ["a.flac", "b.flac"] + ); + fs::write(library.join("Cue/album.flac"), flac_without_picture()).unwrap(); + assert_eq!( + scanned_beside_cue(&backend, &library, &cue, time), + ["a.flac", "album.mp3", "b.flac"] + ); + } + + #[test] + fn cue_audio_the_walk_found_needs_no_probe() { + let root = tempfile::tempdir().unwrap(); + let library = fs::canonicalize(root.path()).unwrap().join("library"); + fs::create_dir_all(&library).unwrap(); + let backend = backend(root.path(), &library); + let cue = library.join("album.cue").to_string_lossy().into_owned(); + let audio = library.join("album.flac").to_string_lossy().into_owned(); + let walked = BTreeSet::from([audio.as_str()]); + + assert_eq!( + backend + .resolve_cue_audio(&cue, "album.flac", "", Some(&walked), &|| Ok(())) + .unwrap(), + audio + ); + assert!( + backend + .resolve_cue_audio(&cue, "album.flac", "", None, &|| Ok(())) + .is_err() + ); + } + #[test] fn incremental_delta_matches_the_json_the_scan_always_returned() { let root = tempfile::tempdir().unwrap();